Code & computing / QUICK REFERENCE

Python datetime: parse, convert and handle DST

Parse an ISO timestamp, convert an instant between time zones, and resolve the repeated fall-back hour with tested inputs and outputs.

Two New York local readings of 01:30 on November 1, 2020. Fold 0 at UTC−04:00 is 05:30 UTC; fold 1 at UTC−05:00 is 06:30 UTC, one hour later.
One clock label can describe two different instants. The two source-tested code cases below produce these exact UTC results. Save the original diagram (SVG)
28 entries

Parse and identify the kind of time

Decide whether the input identifies a calendar date, a wall clock reading or an instant.

Parse an ISO timestamp with Z
from datetime import datetime print(datetime.fromisoformat('2026-05-12T14:30:00Z').isoformat())

Z identifies UTC. The result is aware, not an unlabelled local clock reading. [1]

  • Input"ISO text with Z"
    Result2026-05-12T14:30:00+00:00
Convert an explicit offset to UTC
from datetime import datetime, UTC print(datetime.fromisoformat('2026-05-12T14:30:00-04:00').astimezone(UTC).isoformat())

An offset-aware input identifies an instant. astimezone changes the clock display without changing that instant. [1]

  • Input"14:30 with UTC−04:00"
    Result2026-05-12T18:30:00+00:00
No offset means naive
from datetime import datetime print(datetime.fromisoformat('2026-05-12T14:30:00').tzinfo is None)

The text supplies no timezone rule or UTC offset; it does not uniquely identify a real-world instant. [1]

  • Input"14:30 with no offset"
    ResultTrue
Parse a custom date-time format
from datetime import datetime print(datetime.strptime('2026/05/12 14:30', '%Y/%m/%d %H:%M').isoformat())

strptime follows the explicitly supplied directives. Without %z, the result is naive. [1]

  • Input"Year/month/day and 24-hour time"
    Result2026-05-12T14:30:00
Parse a numeric UTC offset with %z
from datetime import datetime print(datetime.strptime('2026-05-12 14:30 +0200', '%Y-%m-%d %H:%M %z').isoformat())

%z parses a numeric offset into an aware datetime, but does not supply daylight-saving rules for a region. [1]

  • Input"Numeric +0200 offset supplied"
    Result2026-05-12T14:30:00+02:00
Invalid calendar dates fail parsing
from datetime import datetime try: datetime.strptime('2026-02-30', '%Y-%m-%d') except ValueError as error: print(type(error).__name__)

strptime rejects an impossible calendar date; do not silently treat a failed parse as a valid instant. [1]

  • Input"February 30, 2026"
    ResultValueError
Parse a calendar date only
from datetime import date print(date.fromisoformat('2026-05-12').isoformat())

A date is not a clock time or timezone-aware instant. [1]

  • Input"2026-05-12"
    Result2026-05-12
ISO week-year can differ from calendar year
from datetime import date d = date(2021, 1, 1) print(f'{d.isocalendar().year}-W{d.isocalendar().week:02d}-{d.isocalendar().weekday}')

Week 53 belongs to ISO week-year 2020. Use the ISO calendar's year for week-based reporting. [1]

  • Input"Friday, January 1, 2021"
    Result2020-W53-5

Convert a known instant

Use an aware instant as input. Named zones follow IANA history; a fixed UTC offset does not.

Convert the POSIX epoch to aware UTC
from datetime import datetime, UTC print(datetime.fromtimestamp(0, UTC).isoformat())

Passing UTC explicitly avoids a platform-dependent naive local-time result. [1]

  • Input"0 POSIX seconds"
    Result1970-01-01T00:00:00+00:00
Convert UTC to New York in summer
from datetime import datetime, UTC from zoneinfo import ZoneInfo instant = datetime(2020, 7, 1, 12, tzinfo=UTC) print(instant.astimezone(ZoneInfo('America/New_York')).isoformat())

This historical July instant falls during daylight time in New York, four hours behind UTC. [2][1]

  • Input"2020-07-01 12:00 UTC"
    Result2020-07-01T08:00:00-04:00
Convert UTC to New York in winter
from datetime import datetime, UTC from zoneinfo import ZoneInfo instant = datetime(2020, 1, 1, 12, tzinfo=UTC) print(instant.astimezone(ZoneInfo('America/New_York')).isoformat())

January uses the historical standard-time UTC−05:00 offset. Region rules are date-dependent. [2]

  • Input"2020-01-01 12:00 UTC"
    Result2020-01-01T07:00:00-05:00
Fixed offset is not a named zone
from datetime import datetime, timedelta, timezone from zoneinfo import ZoneInfo fixed = datetime(2020, 12, 1, 12, tzinfo=timezone(timedelta(hours=-4))) regional = datetime(2020, 12, 1, 12, tzinfo=ZoneInfo('America/New_York')) print(f'{fixed.strftime("%z")} | {regional.strftime("%z")}')

A constant −04:00 offset stays −04:00 in December; an IANA zone uses the offset applicable to that location and date. [2][1]

  • Input"2020-12-01 local noon: −04 fixed vs New York"
    Result-0400 | -0500
Convert a fixed-offset instant to UTC
from datetime import datetime, UTC a = datetime.fromisoformat('2026-05-12T09:30:00-04:00') print(a.astimezone(UTC).isoformat())

Conversion preserves the instant. Do not simply replace tzinfo with UTC for this operation. [1]

  • Input"09:30 with −04:00"
    Result2026-05-12T13:30:00+00:00
Format an aware timestamp
from datetime import datetime, UTC d = datetime(2020, 1, 1, 12, tzinfo=UTC) print(d.strftime('%Y-%m-%d %H:%M %z'))

%z emits a numeric UTC offset. This example avoids locale-dependent weekday and month names. [1]

  • Input"UTC noon with numeric-offset format"
    Result2020-01-01 12:00 +0000
Keep the zone identifier, not just an abbreviation
from zoneinfo import ZoneInfo print(ZoneInfo('America/New_York').key)

Persist the region key when the application's requirements involve future or historical timezone rules; abbreviations such as EST are not full rules. [2]

  • Input"IANA zone identifier"
    ResultAmerica/New_York

The fall-back hour: two different instants

The New York clock reads 01:30 twice on November 1, 2020. The fold flag chooses which.

First local 01:30 (fold 0)
from datetime import datetime from zoneinfo import ZoneInfo a = datetime(2020, 11, 1, 1, 30, fold=0, tzinfo=ZoneInfo('America/New_York')) print(a.isoformat())

fold=0 selects the earlier occurrence of the repeated wall-clock time. [2][3]

  • Input"New York 2020-11-01 01:30, fold=0"
    Result2020-11-01T01:30:00-04:00
Second local 01:30 (fold 1)
from datetime import datetime from zoneinfo import ZoneInfo b = datetime(2020, 11, 1, 1, 30, fold=1, tzinfo=ZoneInfo('America/New_York')) print(b.isoformat())

fold=1 selects the later occurrence. Both occurrences have the same displayed clock time. [2][3]

  • Input"New York 2020-11-01 01:30, fold=1"
    Result2020-11-01T01:30:00-05:00
First 01:30 becomes 05:30 UTC
from datetime import datetime, UTC from zoneinfo import ZoneInfo a = datetime(2020, 11, 1, 1, 30, fold=0, tzinfo=ZoneInfo('America/New_York')) print(a.astimezone(UTC).isoformat())

This is the earlier UTC instant. The diagram above represents this exact value. [2][3]

  • Input"Local 01:30, fold=0"
    Result2020-11-01T05:30:00+00:00
Second 01:30 becomes 06:30 UTC
from datetime import datetime, UTC from zoneinfo import ZoneInfo b = datetime(2020, 11, 1, 1, 30, fold=1, tzinfo=ZoneInfo('America/New_York')) print(b.astimezone(UTC).isoformat())

This later instant occurs one elapsed hour after the first local 01:30. [2][3]

  • Input"Local 01:30, fold=1"
    Result2020-11-01T06:30:00+00:00
Timestamp difference between the repeated times
from datetime import datetime from zoneinfo import ZoneInfo z = ZoneInfo('America/New_York') a = datetime(2020, 11, 1, 1, 30, fold=0, tzinfo=z) b = datetime(2020, 11, 1, 1, 30, fold=1, tzinfo=z) print(int(b.timestamp()-a.timestamp()))

POSIX timestamps distinguish the two instants, even though local hours and minutes match. [1][3]

  • Input"Later minus earlier instant (seconds)"
    Result3600
Conversion from UTC sets fold automatically
from datetime import datetime, UTC from zoneinfo import ZoneInfo z = ZoneInfo('America/New_York') a = datetime(2020, 11, 1, 5, 30, tzinfo=UTC).astimezone(z) b = datetime(2020, 11, 1, 6, 30, tzinfo=UTC).astimezone(z) print(f'{a.fold}, {b.fold}')

Converting actual UTC instants into a region assigns the correct fold: no guess based on a wall-clock string is needed. [2][3]

  • Input"05:30 and 06:30 UTC converted to New York"
    Result0, 1
Same-zone equality can hide the fold
from datetime import datetime from zoneinfo import ZoneInfo z = ZoneInfo('America/New_York') a = datetime(2020, 11, 1, 1, 30, fold=0, tzinfo=z) b = datetime(2020, 11, 1, 1, 30, fold=1, tzinfo=z) print(a == b)

Python ignores fold for comparison when both aware values share the identical tzinfo object; equality here does not mean the same instant. [1][3]

  • Input"Same local time with fold=0 and fold=1"
    ResultTrue

Elapsed time, missing hours and comparisons

Wall-clock arithmetic and comparison are not always the same as elapsed-time arithmetic.

Same-zone subtraction uses the wall clock
from datetime import datetime from zoneinfo import ZoneInfo z = ZoneInfo('America/New_York') a = datetime(2020, 11, 1, 1, 30, fold=0, tzinfo=z) b = datetime(2020, 11, 1, 1, 30, fold=1, tzinfo=z) print(int((b - a).total_seconds()))

When two aware datetimes share the same tzinfo object, direct subtraction ignores offsets. This is a wall-clock result. [1]

  • Input"Second fold minus first, as local datetimes"
    Result0
UTC subtraction measures elapsed seconds
from datetime import datetime, UTC from zoneinfo import ZoneInfo z = ZoneInfo('America/New_York') a = datetime(2020, 11, 1, 1, 30, fold=0, tzinfo=z) b = datetime(2020, 11, 1, 1, 30, fold=1, tzinfo=z) print(int((b.astimezone(UTC) - a.astimezone(UTC)).total_seconds()))

Convert both instants to UTC before subtracting when true elapsed duration matters. [1][3]

  • Input"Second fold minus first, after UTC conversion"
    Result3600
One calendar day can span 25 elapsed hours
from datetime import datetime, UTC, timedelta from zoneinfo import ZoneInfo start = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo('America/New_York')) tomorrow = start + timedelta(days=1) print(int((tomorrow.astimezone(UTC) - start.astimezone(UTC)).total_seconds()/3600))

Across this fall-back transition, tomorrow at the same clock time is 25 elapsed hours later. [1][2]

  • Input"Oct 31 at noon + one local calendar day"
    Result25
Adding 24 UTC hours preserves elapsed duration
from datetime import datetime, UTC, timedelta from zoneinfo import ZoneInfo z = ZoneInfo('America/New_York') start = datetime(2020, 10, 31, 12, tzinfo=z) print((start.astimezone(UTC) + timedelta(hours=24)).astimezone(z).isoformat())

The local clock shows 11:00 the following day, not 12:00. Choose calendar-day or elapsed-hour arithmetic deliberately. [1][2]

  • Input"Oct 31 at noon + 24 elapsed hours"
    Result2020-11-01T11:00:00-05:00
Do not order a naive and aware datetime
from datetime import datetime, UTC try: print(datetime(2026, 5, 12) < datetime(2026, 5, 12, tzinfo=UTC)) except TypeError as error: print(type(error).__name__)

Python rejects ordering values whose timezone interpretations differ. Equality behaves differently; prefer an explicit normalization strategy. [1]

  • Input"naive datetime < aware UTC datetime"
    ResultTypeError
Spring-forward local 02:30 did not occur
from datetime import datetime, UTC from zoneinfo import ZoneInfo z = ZoneInfo('America/New_York') candidate = datetime(2020, 3, 8, 2, 30, tzinfo=z) print(candidate.astimezone(UTC).astimezone(z).strftime('%H:%M'))

Attaching ZoneInfo does not reject a missing local time. This zone/date example roundtrips to 03:30; validate user-supplied local wall times rather than assuming construction detects gaps. [2][3]

  • Input"Constructed NY 2020-03-08 02:30 roundtrip"
    Result03:30

Reserved placement, separate from reference controls. No ad network is active.

Updated Python 3.14 · IANA America/New_York; historical 2020 examples

Sources

  1. datetime — Basic date and time types (Python 3.14) ↗
  2. zoneinfo — IANA time zone support (Python 3.14) ↗
  3. PEP 495 — Local Time Disambiguation ↗