How to replace date and time of a python datetime object

Introduction :

One Python datetime object consists of various date and time information. datetime module provides one method called replace to replace any one of the date or time component of an datetime object.

For example, we can replace year, month, day, hour, minute, second, microsecond or time zone info of a datetime object.

Definition of replace :

replace method is defined as below :

datetime.replace(year=self.year, month=self.month, day=self.day, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0

It returns one new datetime object with the new attributes that we are providing and old attributes for those we are not . year, month, day are date related attributes and hour, minute, second, microsecond are time related attributes. tzinfo is to define time zone and fold is for DST attributes. fold was introduced in python 3.6.

Example program :

Let me show you an example :

import datetime as dt

given_date = dt.datetime(2020, 1, 1, 10, 10, 0, 0)
new_date = given_date.replace(2021)

print(given_date)
print(new_date)

Here, given_date is a datetime object we created with some default values. new_date is a new date we created by using the replace method to replace the year with 2021.

It will print the below output :

2020-01-01 10:10:00
2021-01-01 10:10:00