Convert an aware datetime to another timezone while preserving the instant.
How It Works
datetime.astimezone(target_timezone) changes the displayed wall-clock components while keeping the same point in time. Use timezone.utc or ZoneInfo for destinations; replace(tzinfo=...) attaches metadata without converting the instant.
Step-by-Step Example
from datetime import datetime, timezone, timedelta
original_time = datetime(2026, 10, 17, 12, tzinfo=timezone.utc)
other_time = original_time.astimezone(timezone(timedelta(hours=2)))
print(other_time.hour)
print(original_time.timestamp() == other_time.timestamp())
Understanding the Example
- The expression 'datetime(2026, 10, 17, 12, 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.astimezone(timezone(timedelta(hours=2)))' supplies the value stored as 'other_time'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
14
True
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
DST-aware named zones are different from fixed UTC offsets.
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(tzinfo=...) when a timezone conversion is required.
- Convert a UTC event to a named time zone and compare both timestamps.
Key Takeaways
- Convert an aware datetime to another timezone while preserving the instant.
- datetime.astimezone(target_timezone) changes the displayed wall-clock components while keeping the same point in time.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.