Skip to content
devtoolbox.cc

Python · Chapter 17 of 21

Python datetime and zoneinfo: dates, time zones, timestamps

12 min study · Examples checked with Python 3.14 and 3.15 ·

“When” sounds like a simple question, but it hides several different ones. A birthday is a calendar date with no time zone. A meeting at 9:00 in Berlin is a local time that follows that city’s daylight-saving rules. “Published at” is an exact instant that every country sees at the same moment. “This took 2.3 seconds” is a duration. Python has a type for each, and most date bugs come from using one where another was meant. This chapter covers the datetime and zoneinfo modules, Unix timestamps, daylight saving, and clocks for measuring time.

Four types for four questions

from datetime import UTC, date, datetime, time, timedelta

course_start = date(2026, 11, 14)
lesson_time = time(9, 30)
lesson_length = timedelta(minutes=45)
published = datetime(2026, 11, 14, 8, 30, tzinfo=UTC)

print(course_start.isoformat(), course_start.strftime("%A"))  # 2026-11-14 Saturday
print(lesson_time, lesson_length.total_seconds())             # 09:30:00 2700.0
print(published.isoformat())                                  # 2026-11-14T08:30:00+00:00
print((date(2026, 12, 25) - course_start).days)               # 41
print(timedelta(days=1, seconds=30).seconds)                  # 30

date is a calendar day, time a time of day, datetime both together, and timedelta a length of time. Subtracting two dates or datetimes gives a timedelta; adding a timedelta moves a date or datetime. The last line shows a trap: .seconds is only the leftover seconds after whole days are removed, so for the full length always use total_seconds().

Aware datetimes and time zones

A datetime without tzinfo is “naive”: it is a reading on some clock, but nobody knows which. With tzinfo it is “aware” and identifies an exact instant. Store and compute instants as aware UTC values, and convert to a local zone only for display:

from datetime import UTC, datetime
from zoneinfo import ZoneInfo

now = datetime.now(UTC)
berlin = now.astimezone(ZoneInfo("Europe/Berlin"))
tokyo = now.astimezone(ZoneInfo("Asia/Tokyo"))
print(now == berlin == tokyo)                    # True: one instant, three clock readings
print(berlin.utcoffset() != tokyo.utcoffset())   # True

meeting = datetime(2026, 11, 20, 9, 0, tzinfo=ZoneInfo("Europe/Berlin"))
print(meeting.astimezone(UTC).isoformat())       # 2026-11-20T08:00:00+00:00
print(meeting.replace(tzinfo=UTC).isoformat())   # 2026-11-20T09:00:00+00:00 (a different instant)

ZoneInfo uses the IANA time zone database, with names such as Europe/Berlin or America/New_York. Never use fixed offsets like +01:00 for a place, because the offset changes with daylight saving and sometimes with politics. On Windows, install the tzdata package so the database is available, and keep it updated.

The last two lines show the difference between converting and relabelling. astimezone converts: same instant, different clock reading. replace(tzinfo=...) only changes the label, so 9:00 Berlin becomes 9:00 UTC, an hour later in reality. Use replace only to attach a zone to a naive value whose zone you know. datetime.utcnow() is deprecated, because it returns a naive value that looks local; use datetime.now(UTC).

Parse and format: ISO 8601 and Unix timestamps

from datetime import UTC, datetime, timedelta

instant = datetime.fromisoformat("2026-11-14T08:30:00+00:00")
print(instant + timedelta(hours=36))            # 2026-11-15 20:30:00+00:00
form = datetime.strptime("14/11/2026 09:30", "%d/%m/%Y %H:%M")
print(form, form.tzinfo)                        # 2026-11-14 09:30:00 None
print(instant.strftime("%d %b %Y, %H:%M"))      # 14 Nov 2026, 08:30

print(int(instant.timestamp()))                 # 1794645000
print(datetime.fromtimestamp(1_800_000_000, UTC).isoformat())  # 2027-01-15T08:00:00+00:00

ISO 8601 (2026-11-14T08:30:00+00:00) is the format to exchange: unambiguous, sortable as text, and understood by every language. fromisoformat reads it, isoformat writes it. For other layouts, strptime parses with format codes (%d day, %m month, %Y year, %H:%M hours and minutes) and strftime formats. Text without an offset parses to a naive value, so decide at the input boundary which zone it is in.

A Unix timestamp counts seconds since 1970-01-01 00:00 UTC, and many APIs and databases use them. timestamp() converts an aware datetime to one; fromtimestamp(ts, UTC) converts back. Some systems send milliseconds instead, so a value 1000 times too big lands tens of thousands of years in the future. The Unix timestamp converter on this site shows both readings side by side.

Daylight saving: lost and repeated hours

Calendar arithmetic and elapsed time differ when the clocks change. In Berlin, clocks jump from 2:00 to 3:00 on 29 March 2026 and fall back from 3:00 to 2:00 on 25 October 2026:

from datetime import UTC, datetime, timedelta
from zoneinfo import ZoneInfo

berlin = ZoneInfo("Europe/Berlin")
saturday = datetime(2026, 3, 28, 12, 0, tzinfo=berlin)
sunday = saturday + timedelta(days=1)          # same wall time next day
print((sunday.astimezone(UTC) - saturday.astimezone(UTC)) / timedelta(hours=1))  # 23.0

repeated = datetime(2026, 10, 25, 2, 30, tzinfo=berlin)
print(repeated.isoformat(), repeated.replace(fold=1).isoformat())
# 2026-10-25T02:30:00+02:00 2026-10-25T02:30:00+01:00

Adding a timedelta to an aware local datetime keeps the wall-clock time (“noon tomorrow”), even though that day had only 23 real hours. For an elapsed deadline such as “48 hours from now”, calculate in UTC. On the autumn night, 2:30 happens twice; the fold attribute picks the first (0) or second (1) occurrence. In spring, 2:30 never happens at all. When users type local times, decide what to do with such values: reject them, or move them, and tell the user.

Months are not durations, so timedelta has no months argument. “One month after 31 January” needs a rule. A common one is to clamp to the last day of the target month, which calendar.monthrange(year, month)[1] gives you; the third-party python-dateutil package implements this as relativedelta.

Clocks for measuring time

Wall-clock time can jump when the computer synchronizes its clock or someone changes it. To measure how long something takes, use a clock that only moves forward:

import time

start = time.perf_counter()
total = sum(n * n for n in range(100_000))
elapsed = time.perf_counter() - start
print(total, f"{elapsed:.4f}s")    # 333328333350000 0.0038s (the time varies)

deadline = time.monotonic() + 0.05
while time.monotonic() < deadline:
    time.sleep(0.01)
print("waited until the deadline")

perf_counter has the highest resolution and suits measuring code. monotonic suits timeouts and deadlines. Both start from an arbitrary point, so their values only make sense as differences within one process; store datetime.now(UTC) when you need a moment to record. For running jobs on a schedule, time.sleep in a loop or the sched module works inside a running program, but a job that must survive restarts belongs in an external scheduler such as cron, a systemd timer or a task queue.

Practice

Write due_at(start_iso: str, hours: int, zone: str) -> str that takes an ISO timestamp with an offset, adds the hours as elapsed time, and returns the result as ISO in the given zone. Then write add_month(d: date) -> date that clamps to the end of the month.

Answer check: due_at("2026-03-28T12:00:00+01:00", 24, "Europe/Berlin") returns 2026-03-29T13:00:00+02:00, because 24 elapsed hours cross the spring change. Convert to UTC, add, and use astimezone(ZoneInfo(zone)). add_month(date(2026, 1, 31)) returns 2026-02-28, using calendar.monthrange(2026, 2)[1] for the last day.

Summary

Use date for calendar days, aware datetime for instants (stored in UTC), ZoneInfo names for places, and timedelta for durations, with total_seconds(). Exchange ISO 8601, know whether a Unix timestamp is in seconds or milliseconds, handle the missing and repeated hours of daylight saving deliberately, and measure work with perf_counter, not the wall clock.

All Python chapters