Time Zones with zoneinfo

Published by Brayan K

zoneinfo is the standard-library module that attaches real IANA time zones — like America/New_York — to a datetime, turning an ambiguous wall-clock reading into an exact, daylight-saving-aware moment in time.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A zone name supplies rules; an ambiguous wall time still needs a choice

An offset says how far a particular time is from UTC. An IANA zone name supplies the historical rules that choose offsets. Attaching a zone does not validate every local wall time or decide which occurrence you intended during a repeated hour. That qualification matters when interpreting the definition above.

These examples use fixed dates, never the computer’s current time. They need local Python with the IANA database available. If your system does not supply it, install the first-party package with python -m pip install tzdata. The site’s browser Python currently has no time-zone database. Keep the database updated for real scheduling because governments can change future rules.

from datetime import datetime, timezone
from zoneinfo import ZoneInfo

instant = datetime(2020, 7, 1, 12, 0, tzinfo=timezone.utc)
new_york = instant.astimezone(ZoneInfo("America/New_York"))
london = instant.astimezone(ZoneInfo("Europe/London"))
print(instant.isoformat())
print(new_york.isoformat())
print(london.isoformat())
print(new_york == instant)

# ✅ Expected output:
# 2020-07-01T12:00:00+00:00
# 2020-07-01T08:00:00-04:00
# 2020-07-01T13:00:00+01:00
# True

All three displays refer to the same instant. astimezone preserves that instant while changing the displayed local fields and offset. Date construction, parsing and timedelta basics are covered in Dates & Times (datetime). This lesson owns the extra decisions that appear when zone rules meet local times.

Replacing tzinfo relabels fields instead of converting the instant

from datetime import datetime, timezone
from zoneinfo import ZoneInfo

utc_time = datetime(2020, 7, 1, 12, 0, tzinfo=timezone.utc)
zone = ZoneInfo("America/New_York")
converted = utc_time.astimezone(zone)
relabeled = utc_time.replace(tzinfo=zone)
print(converted.isoformat())
print(relabeled.isoformat())
print(relabeled.astimezone(timezone.utc).isoformat())

# ✅ Expected output:
# 2020-07-01T08:00:00-04:00
# 2020-07-01T12:00:00-04:00
# 2020-07-01T16:00:00+00:00

replace(tzinfo=...) keeps the clock fields and attaches a new interpretation. It is suitable only when those fields already mean local time in the chosen zone, with ambiguity and validity handled separately. It is not a conversion of an already-known instant. Avoid astimezone on a naive input when you need reproducible behavior: it assumes the machine’s local zone.

from datetime import datetime, timezone
naive = datetime(2020, 7, 1, 12, 0)
aware = datetime(2020, 7, 1, 12, 0, tzinfo=timezone.utc)
print(naive < aware)

# ✅ Expected error:
# TypeError: can't compare offset-naive and offset-aware datetimes

The repeated hour contains two different instants

from datetime import datetime, timezone
from zoneinfo import ZoneInfo

zone = ZoneInfo("America/New_York")
first = datetime(2020, 11, 1, 1, 30, tzinfo=zone, fold=0)
second = first.replace(fold=1)
print(first.isoformat())
print(second.isoformat())
print(first.astimezone(timezone.utc).isoformat())
print(second.astimezone(timezone.utc).isoformat())
print(second.astimezone(timezone.utc) - first.astimezone(timezone.utc))

# ✅ Expected output:
# 2020-11-01T01:30:00-04:00
# 2020-11-01T01:30:00-05:00
# 2020-11-01T05:30:00+00:00
# 2020-11-01T06:30:00+00:00
# 1:00:00

During this backward transition, fold=0 selects the earlier occurrence and fold=1 the later one. Converting a known UTC instant into the zone sets fold appropriately. For user-entered local times, the application must ask for or document a choice; silently accepting the default can select an unintended appointment.

from datetime import datetime, timezone
from zoneinfo import ZoneInfo

zone = ZoneInfo("America/New_York")
first = datetime(2020, 11, 1, 1, 30, tzinfo=zone, fold=0)
second = first.replace(fold=1)
print(first == second)
print(second - first)
print(second.astimezone(timezone.utc) - first.astimezone(timezone.utc))

# ✅ Expected output:
# True
# 0:00:00
# 1:00:00

When both datetimes share the same tzinfo object, comparison and subtraction ignore the fold distinction and use the local fields. Normalize to UTC when you mean elapsed time or chronological ordering of instants. Storing a local datetime alone is therefore not a safe substitute for deciding which instant it represents.

The skipped hour can be constructed even though it never occurred

from datetime import datetime, timezone
from zoneinfo import ZoneInfo

zone = ZoneInfo("America/New_York")
local = datetime(2020, 3, 8, 2, 30, tzinfo=zone)
returned = local.astimezone(timezone.utc).astimezone(zone)
print(local.isoformat())
print(returned.isoformat())
print(returned.replace(tzinfo=None) == local.replace(tzinfo=None))

# ✅ Expected output:
# 2020-03-08T02:30:00-05:00
# 2020-03-08T03:30:00-04:00
# False

The constructor does not reject a time in the spring-forward gap. A UTC round trip exposes that the chosen local fields do not map back to themselves. A scheduling interface needs a stated policy: reject the entry, ask for another time or deliberately move it. Do not describe attaching ZoneInfo as automatic validation.

from datetime import datetime, timezone
from zoneinfo import ZoneInfo

def candidates(wall, zone):
    by_instant = {}
    for fold in (0, 1):
        candidate = wall.replace(tzinfo=zone, fold=fold)
        instant = candidate.astimezone(timezone.utc)
        returned = instant.astimezone(zone)
        if returned.replace(tzinfo=None) == wall:
            by_instant[instant] = returned
    return [by_instant[key] for key in sorted(by_instant)]

zone = ZoneInfo("America/New_York")
for wall in [datetime(2020, 2, 1, 12), datetime(2020, 3, 8, 2, 30), datetime(2020, 11, 1, 1, 30)]:
    print([value.isoformat() for value in candidates(wall, zone)])

# ✅ Expected output:
# ['2020-02-01T12:00:00-05:00']
# []
# ['2020-11-01T01:30:00-04:00', '2020-11-01T01:30:00-05:00']

The helper’s input contract is a naive local datetime plus a named zone. It tries both folds, rejects failed round trips and deduplicates by UTC instant. Ordinary times have one candidate, a gap has none, and this repeated hour has two. An application still has to decide what to do with those candidates.

A calendar day and twenty-four elapsed hours can end differently

from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo

zone = ZoneInfo("America/New_York")
start = datetime(2020, 3, 7, 12, tzinfo=zone)
wall_day = start + timedelta(days=1)
elapsed_day = (start.astimezone(timezone.utc) + timedelta(hours=24)).astimezone(zone)
print(wall_day.isoformat())
print(elapsed_day.isoformat())
print(wall_day.astimezone(timezone.utc) - start.astimezone(timezone.utc))

# ✅ Expected output:
# 2020-03-08T12:00:00-04:00
# 2020-03-08T13:00:00-04:00
# 23:00:00

A recurring noon event follows local calendar rules. A twenty-four-hour timeout follows elapsed time. They are different requirements across a transition. For future recurring events, retain the named zone and recurrence policy as well as any computed UTC occurrence. UTC storage alone does not encode that policy.

from zoneinfo import ZoneInfo
ZoneInfo("Not/A_Real_Zone")

# ✅ Expected error:
# zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key Not/A_Real_Zone'

ZoneInfoNotFoundError can mean an unknown key or an unavailable database. Check the supplied identifier and deployment dependencies rather than silently substituting the server’s zone. A fixed offset also cannot reproduce a named zone’s changing rules.

Convert the later occurrence before adding elapsed time

Choose the later repeated time, convert it to UTC, then add thirty minutes. The original local fields should not be relabeled as UTC.

from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo

local = datetime(2020, 11, 1, 1, 30, tzinfo=ZoneInfo("America/New_York"), fold=___)
instant = local.___(timezone.utc)
finish = instant + timedelta(minutes=___)
print(instant.isoformat())
print(finish.isoformat())

# 👉 replace ___ with 1
# 👉 replace ___ with astimezone
# 👉 replace ___ with 30

# ✅ Expected output:
# 2020-11-01T06:30:00+00:00
# 2020-11-01T07:00:00+00:00

Produce a meeting record with an explicit ambiguity policy

Use the candidates helper from above for a requested New York wall time. Reject a request with no valid candidate; when two exist, deliberately choose the later instant. Schedule ninety elapsed minutes. For 1 November 2020 at 01:30, print the chosen local start, UTC start and local finish. Then test 8 March 2020 at 02:30 and print a clear rejection. Use fixed inputs and keep the selected zone name in the record.

from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo

def candidates(wall, zone):
    by_instant = {}
    for fold in (0, 1):
        candidate = wall.replace(tzinfo=zone, fold=fold)
        instant = candidate.astimezone(timezone.utc)
        returned = instant.astimezone(zone)
        if returned.replace(tzinfo=None) == wall:
            by_instant[instant] = returned
    return [by_instant[key] for key in sorted(by_instant)]

def meeting(wall, zone_name):
    zone = ZoneInfo(zone_name)
    choices = candidates(wall, zone)
    if not choices:
        raise ValueError("local time does not exist")
    start = choices[-1]
    utc_start = start.astimezone(timezone.utc)
    finish = (utc_start + timedelta(minutes=90)).astimezone(zone)
    return zone_name, start, utc_start, finish

record = meeting(datetime(2020, 11, 1, 1, 30), "America/New_York")
print(record[0])
for value in record[1:]:
    print(value.isoformat())
try:
    meeting(datetime(2020, 3, 8, 2, 30), "America/New_York")
except ValueError as error:
    print(str(error))

# ✅ Expected output:
# America/New_York
# 2020-11-01T01:30:00-05:00
# 2020-11-01T06:30:00+00:00
# 2020-11-01T03:00:00-05:00
# local time does not exist

Choosing the later occurrence is this exercise’s explicit policy, not a universal scheduling rule. A real interface may instead require the person entering the time to choose.

Practice quiz

Which operation preserves a known instant while changing its zone display?

  • replace(tzinfo=zone)
  • astimezone(zone)
  • Removing tzinfo
  • Changing only the hour

Answer: astimezone(zone). astimezone converts; replace relabels unchanged local fields.

What does this program print? from datetime import datetime, timezone from zoneinfo import ZoneInfo x = datetime(2020, 7, 1, 12, tzinfo=timezone.utc) print(x.astimezone(ZoneInfo("America/New_York")).isoformat())

  • 2020-07-01T12:00:00-04:00
  • 2020-07-01T08:00:00+00:00
  • 2020-07-01T16:00:00-04:00
  • 2020-07-01T08:00:00-04:00

Answer: 2020-07-01T08:00:00-04:00. The July offset changes the local display while preserving the instant.

What does fold=1 select during the repeated New York hour shown here?

  • The later occurrence
  • A nonexistent time
  • Always standard time in every possible zone
  • The first occurrence

Answer: The later occurrence. fold distinguishes the later occurrence of an ambiguous local reading.

What does this program print? from datetime import datetime from zoneinfo import ZoneInfo a = datetime(2020, 11, 1, 1, 30, tzinfo=ZoneInfo("America/New_York")) b = a.replace(fold=1) print(a == b)

  • False
  • TypeError
  • True
  • None

Answer: True. Same-tzinfo comparison ignores fold; compare UTC instants when that distinction matters.

Does constructing a datetime with ZoneInfo reject a spring-forward gap automatically?

  • Yes, on every date
  • Only if fold is zero
  • Yes, unless UTC is used
  • No; validate the local reading and apply an explicit policy

Answer: No; validate the local reading and apply an explicit policy. Attaching the zone is not a validity check.

Which error ends this program? from datetime import datetime, timezone a = datetime(2020, 1, 1) b = datetime(2020, 1, 1, tzinfo=timezone.utc) print(a < b)

  • TypeError: can't compare offset-naive and offset-aware datetimes
  • True
  • False
  • ValueError: invalid date

Answer: TypeError: can't compare offset-naive and offset-aware datetimes. Ordering cannot infer the naive value’s zone.

Where should a fixed elapsed duration be added across a zone transition?

  • To a naive copy of the local fields
  • To the UTC instant before converting back
  • To an offset string
  • To fold

Answer: To the UTC instant before converting back. UTC arithmetic expresses elapsed time without a repeated or skipped local hour.

What does an IANA zone name retain that a fixed offset does not?

  • A guarantee about all future legislation
  • The computer’s current clock
  • Historical and evolving transition rules
  • The user’s choice for every repeated time

Answer: Historical and evolving transition rules. A named zone supplies rules; ambiguity and future scheduling policy still need decisions.

Continue this course

Related lessons