replace()
method?The replace()
method replaces the attributes of a datetime
object.
datetime
objectA datetime
object consists of date attributes, time attributes, and attributes related to timezone.
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)
The parameters of this method are the date
, time
, and timezone attributes.
The replace()
function returns a datetime
object with new values for the specified attributes.
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}")
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}")