Replace individual datetime components without converting time zones.
How It Works
datetime.replace(year=..., hour=..., tzinfo=...) creates a new datetime with chosen fields. It changes wall-clock fields directly; replacing tzinfo is not a timezone conversion and can alter the apparent instant.
Step-by-Step Example
from datetime import datetime, timezone
original_time = datetime(2026, 10, 17, 9, 30, tzinfo=timezone.utc)
rescheduled_time = original_time.replace(hour=11)
print(original_time.hour)
print(rescheduled_time.hour)
Understanding the Example
- The expression 'datetime(2026, 10, 17, 9, 30, tzinfo=timezone.utc)' supplies the value stored as 'original_time'. This value is then used or checked by the later statements.
- The expression 'original_time.replace(hour=11)' supplies the value stored as 'rescheduled_time'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
9
11
Where This Fits in a Real Program
For event timestamps, distinguish the displayed local clock from the instant that it represents. Store or exchange an unambiguous aware value, then convert it when displaying it to a user. For repeated calendar appointments, use a geographic timezone so daylight-saving rules are not lost.
Practice: Try It Yourself
Replacing a day or month may raise ValueError for invalid calendar combinations.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Using replace() instead of astimezone() to move an event between geographic time zones.
- Change a meeting date but keep its time and timezone.
Key Takeaways
- Replace individual datetime components without converting time zones.
- datetime.replace(year=..., hour=..., tzinfo=...) creates a new datetime with chosen fields.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.