Time looks simple until a bug appears once a year, at 02:30 on a Sunday. A few clear ideas avoid most of the pain.
Instants and local times
An instant is a single point on the timeline, the same for everyone on Earth. A local time is what a wall clock shows in a place, and it needs a time zone to mean anything. "2026-03-29 02:30" without a zone does not identify an instant.
UTC and Unix time
UTC is the reference time with no daylight saving. Unix time counts the seconds since 1970-01-01 00:00 UTC, ignoring leap seconds, which makes arithmetic simple. Store and compare instants in UTC, or as Unix timestamps, and convert to a local time only for display.
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
instant = datetime(2026, 7, 1, 12, 0, tzinfo=timezone.utc)
print(instant.timestamp()) # Unix time, in seconds
print(instant.astimezone(ZoneInfo("Asia/Ho_Chi_Minh"))) # shown in local time
print(instant.astimezone(ZoneInfo("Europe/Berlin")))Offsets are not time zones
+02:00 is an offset, valid for one moment. A time zone such as Europe/Berlin is a set of rules, from the IANA database, saying which offset applies when, including daylight saving changes. For a future event at "9:00 in Berlin", store the zone name and the local time, because the offset may change if the rules do. Keep the zone database updated.
Daylight saving traps
- Some local times do not exist (clocks jump forward), and some happen twice (clocks go back).
- A day is not always 24 hours. "Add one day" and "add 24 hours" can differ.
- Schedules such as "every day at 02:30 local time" need a decision for the missing and repeated hours.
Rules of thumb
- Store instants in UTC with a time zone-aware type. In databases prefer
timestamptzover a naive timestamp. - Use a proper library for arithmetic and formatting. Do not write your own.
- Treat user-entered dates and times as local to the user's zone, then convert.
- Make servers and tests independent of the machine's local zone, and test around daylight saving changes.
- A birthday or a deadline "on a date" is a calendar date, not an instant.
Takeaway
Instants in UTC, zones by IANA name, conversion at the edges and distrust for anything called "midnight".
Comments