The Basics of Handling Time Zones in Python
Time zones in Python's datetime: naive vs. aware objects, attaching zones with the standard library, storing in UTC, and arithmetic across DST changes.
When handling time zones in Python, misunderstanding how the standard datetime module actually works can lead to bugs that quietly shift your times in unintended ways.
"Naive" vs. "aware" datetimes
Python's datetime objects come in two flavors: "naive," which carries no time zone information, and "aware," which does. A naive datetime is really just a bundle of numbers — "August 6, 2026, 9:00 PM" — and the program itself has no idea which time zone that refers to. Comparing or doing arithmetic between naive datetimes that actually belong to different time zones is a classic source of incorrect results.
Attaching a time zone using the standard library
Since Python 3.9, the standard library has included the zoneinfo module, which lets you create aware datetimes using IANA time zone identifiers like "Asia/Tokyo." Before that, third-party libraries like pytz were widely used instead. For new code, using the standard library's zoneinfo is the recommended approach. When migrating existing pytz-dependent code, watch out for small differences in the two libraries' APIs.
Storing in UTC and converting for display
Many Python applications follow the pattern of using aware UTC datetimes internally — for both calculations and storage — and converting to the target time zone with the astimezone() method only right before displaying to the user (see also "UTC Storage vs. Local Display: A Best Practice for Datetime Design").
Watch out for arithmetic that crosses a DST transition
Subtracting one aware datetime from another (to calculate elapsed time) is internally normalized to UTC, so it produces correct results even across a DST transition. Adding a timedelta directly to a naive datetime, on the other hand, doesn't account for any DST change in between — so what's meant to be "24 hours later" can actually land 23 or 25 hours later, a subtle pitfall (see also "Real-World Bugs Daylight Saving Time Causes in Computer Systems").