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

  1. Day
  2. Month
  3. Year

Time attributes

  1. Microsecond
  2. Second
  3. Minute
  4. 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 datetime
today_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 datetime
today_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}")
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources