What is the replace() function of Python datetime?
What is the replace() method?
The replace() method replaces the attributes of a datetime object.
Attributes of a datetime object
A datetime object consists of date attributes, time attributes, and attributes related to timezone.
Date attributes
- Day
- Month
- Year
Time attributes
- Microsecond
- Second
- Minute
- Hour
Syntax
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)
Parameters
The parameters of this method are the date, time, and timezone attributes.
Return value
The replace() function returns a datetime object with new values for the specified attributes.
Code
Example 1
In the code below, we replace the date attributes of the datetime object.
import datetimetoday_date = datetime.datetime.today()print(f"Today's Date - {today_date}")new_today_date = today_date.replace(year=2022, month=12, day=31)print(f"New Today's Date - {new_today_date}")
Example 2
In the code below, we replace the time attributes of the datetime object.
import datetimetoday_date = datetime.datetime.today()print(f"Today's Date - {today_date}")new_today_time = today_date.replace(hour=15, minute=43, second=14)print(f"New Today's time - {new_today_time}")