Test calendar logic on days when the UTC offset changes.
How It Works
A local clock can skip an hour when daylight saving begins or repeat an hour when it ends. ZoneInfo tracks the rules for named zones; a fixed timezone offset does not. Create test cases immediately before and after transitions so the expected local times are explicit.
Transition rules differ by zone and year; do not hardcode a universal daylight-saving calendar.
Step-by-Step Example
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
paris = ZoneInfo("Europe/Paris")
for hour in (0, 1, 2):
utc_time = datetime(2026, 3, 29, hour, 30, tzinfo=timezone.utc)
print(utc_time.strftime("%H:%M"), utc_time.astimezone(paris).strftime("%H:%M %z"))
Understanding the Example
- The expression 'ZoneInfo("Europe/Paris")' supplies the value stored as 'paris'. This value is then used or checked by the later statements.
- The for loop processes one item per iteration rather than requiring a separate statement for each value.
A successful run of this example prints the following output:
00:30 01:30 +0100
01:30 03:30 +0200
02:30 04:30 +0200
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
Repeat the conversion for the autumn transition and identify repeated local clock times.
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
- Assuming that adding one hour to a local wall clock always advances it to the next displayed hour.
- Relying on today’s UTC offset when testing dates several months away.
Key Takeaways
- Test calendar logic on days when the UTC offset changes.
- A local clock can skip an hour when daylight saving begins or repeat an hour when it ends.
- Transition rules differ by zone and year; do not hardcode a universal daylight-saving calendar.