Content · Programming · Python

Python Build a Time Zone Converter

Convert an aware UTC datetime between two named IANA time zones.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Convert an aware UTC datetime between two named IANA time zones.

How It Works


ZoneInfo tracks geographic timezone rules. Convert using astimezone() rather than editing tzinfo, and format the result with an explicit offset so users can see the actual meaning.

Step-by-Step Example


from datetime import datetime, timezone
from zoneinfo import ZoneInfo
utc_event = datetime(2026, 1, 20, 15, tzinfo=timezone.utc)
tokyo_event = utc_event.astimezone(ZoneInfo('Asia/Tokyo'))
print(tokyo_event.hour)
print(utc_event.timestamp() == tokyo_event.timestamp())

Understanding the Example


  • The expression 'datetime(2026, 1, 20, 15, tzinfo=timezone.utc)' supplies the value stored as 'utc_event'. This value is then used or checked by the later statements.
  • The expression "utc_event.astimezone(ZoneInfo('Asia/Tokyo'))" supplies the value stored as 'tokyo_event'. This value is then used or checked by the later statements.

A successful run of this example prints the following output:

0
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


If the host has no timezone database, supply the maintained tzdata dependency.

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


  • Hardcoding geographic offsets and ignoring daylight-saving transitions.
  • Add a second target city and show both conversions for winter and summer.

Key Takeaways


  • Convert an aware UTC datetime between two named IANA time zones.
  • ZoneInfo tracks geographic timezone rules.
  • Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.
Share this resourceSend this page to someone who may find it useful.