Python Date & Time replace() : Update date object by changing the parameters with new value .
from datetime import datetime
dt=datetime(2019,12,31)
print(dt.replace(year=2018,day=14,month=7))
Output
2018-07-14 00:00:00
Date with time
import datetime
# Year, Month, date, Hour, Minute , Second, mircosecond
dt=datetime.datetime(2019,12,31,23,59,59,345234)
print(dt.replace(day=14))
Output
2019-12-14 23:59:59.345234
Using date object and adding new time part
from datetime import datetime
dt=datetime(2019,12,31)
print(dt.replace(year=2018,day=14,month=7,hour=13,minute=35,second=55,microsecond=324356))
Output
2018-07-14 13:35:55.324356
All parameters are optional
from datetime import datetime
dt=datetime(2019,12,31)
print(dt.replace())
2019-12-31 00:00:00
Replacing month with invalid date.
This code will generate ValueError
from datetime import datetime
dt=datetime(2020,3,31)
dt=dt.replace(month=4)
print(dt)
We can use Exception Handling to manage the code in this case.
from datetime import datetime
try:
dt=datetime(2020,3,31)
dt=dt.replace(month=4)
print(dt)
except ValueError as my_msg:
print ("This is a ValueError")
print (my_msg)
Output is here
This is a ValueError
day is out of range for month
« All Date Objects
← Subscribe to our YouTube Channel here