Datetime.replace() Function in Python
Datetime.replace() function is used to replace the contents of the DateTime object with the given parameters.
Syntax: Datetime_object.replace(year,month,day,hour,minute,second,microsecond,tzinfo)
Parameters:
- year: New year value in range-[1,9999],
- month: New month value in range-[1,12],
- day: New day value in range-[1,31],
- hour: New hour value in range-[24],
- minute: New minute value in range-[60],
- second: New second value in range-[60],
- microsecond: New microsecond value in range-[1000000],
- tzinfo: New time zone info.
Returns: It returns the modified datetime object
Note:
- In the replace() we can only pass the parameter the DateTime object is already having, replacing a parameter that is not present in the DateTime object will raise an Error
- It does not replace the original DateTime object but returns a modified DateTime object
Example 1: Replace the current date’s year with the year 2000.
Python3
import datetime
todays_date = datetime.date.today()
print ( "Original Date:" , todays_date)
modified_date = todays_date.replace(year = 2000 )
print ( "Modified Date:" , modified_date)
|
Output:
Original Date: 2021-07-27
Modified Date: 2000-07-27
Example 2: Replace a parameter that is not present in the datetime object.
Python3
import datetime
todays_date = datetime.date.today()
print ( "Original Date:" , todays_date,)
modified_date = todays_date.replace(hour = 3 )
print ( "Modified Date:" , modified_date)
|
Output:
Traceback (most recent call last):
File “/home/6e1aaed34d749f5b15af6dc27ce73a2d.py”, line 9, in <module>
modified_date = todays_date.replace(hour=3)
TypeError: ‘hour’ is an invalid keyword argument for this function
So we observe that we get an error as the hour is not present in the datetime object. Now we will create a datetime object with hour property and try to change it to 03 and we will also change the date to 10.
Python3
import datetime
todays_date = datetime.datetime.now()
print ( "Today's date and time:" , todays_date)
modified_date = todays_date.replace(day = 10 , hour = 3 )
print ( "Modified date and time:" , modified_date)
|
Output:
Today's date and time: 2021-07-28 09:08:47.563144
Modified date and time: 2021-07-10 03:08:47.563144
Last Updated :
28 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...