Batu Lab NotesPractical developer guides

Convert a UTC timestamp to a named time zone

By Batu · English technical notes

Also published in our Blogger archive.

A UTC timestamp is most useful when it is represented by an aware datetime: one whose tzinfo explicitly identifies UTC. This example starts with noon UTC on 1 July 2024 and converts that same instant to America/New_York. datetime.astimezone() changes the displayed clock fields and offset while preserving the instant. The assertion that converts the result back to UTC demonstrates that both values represent the same moment.

ZoneInfo uses IANA zone names, so it can apply the historical and daylight-saving rules available in the local time-zone database. Here, New York is observing UTC−04:00, producing 08:00. That offset is not a permanent property of the zone; a winter date normally produces a different offset. Do not replace a named zone with a fixed timezone(timedelta(...)) when the application needs daylight-saving transitions.

zoneinfo was added in Python 3.9. On systems without time-zone data, ZoneInfo may raise ZoneInfoNotFoundError; install or provide appropriate time-zone data rather than silently guessing an offset. The input must also be aware: attaching UTC to a wall-clock value is only correct when that value is actually known to be UTC. See the official zoneinfo documentation and datetime.astimezone() reference.

AI assistance disclosure: this article was drafted with AI assistance and should be reviewed for the application's time-zone requirements.

from datetime import datetime, timezone
from zoneinfo import ZoneInfo

utc_timestamp = datetime(2024, 7, 1, 12, 0, tzinfo=timezone.utc)
new_york = ZoneInfo("America/New_York")
local_timestamp = utc_timestamp.astimezone(new_york)

assert local_timestamp.isoformat() == "2024-07-01T08:00:00-04:00"
assert local_timestamp.astimezone(timezone.utc) == utc_timestamp

print(local_timestamp.isoformat())
2024-07-01T08:00:00-04:00