replace(**fields) returns a new object that is a copy of the original with the given fields changed. Fields you do not pass keep their old values, and the original object is never modified, because datetime objects are immutable.
On a datetime you can change year, month, day, hour, minute, second, microsecond, tzinfo, and fold. replace(tzinfo=...) attaches or removes a zone without converting the clock time; use astimezone() to convert.
datetime.replace() is an instance method of datetime.datetime: call it on an existing object with dot notation, such as moment.replace(...). Import the class first, for example from datetime import datetime. The date and time classes have a method with the same name.
Syntax
Pass only the fields you want to change, as keyword arguments.
python
new = moment.replace(year=2025)
new = moment.replace(hour=0, minute=0, second=0, microsecond=0)
new = moment.replace(tzinfo=timezone.utc)
One field.year=2025 changes only the year; everything else is copied.
Start of day. Zeroing the four clock fields truncates the value to midnight.
Immutable original.moment still prints its old value because replace() returned new objects.
Example 2 — Handle Dates That Do Not Exist
Moving 29 February to another year only works for leap years.
python
from datetime import date
leap_day = date(2024, 2, 29)
for year in (2028, 2025):
try:
print(leap_day.replace(year=year))
except ValueError:
print(year, "has no February 29")
first_of_month = leap_day.replace(day=1)
print(first_of_month)
Output
2028-02-29
2025 has no February 29
2024-02-01
How It Works
Valid move. 2028 is a leap year, so 29 February exists there.
Invalid move. 2025 is not a leap year, so the constructor check raises ValueError.
First of the month.replace(day=1) is a quick way to get the month start.
Example 3 — replace(tzinfo=...) Relabels, astimezone() Converts
Attach UTC+05:30 to a UTC value both ways and compare with the original instant.