datetime Round Trips ISO 8601 Strings

isoformat() renders an aware datetime and fromisoformat() parses it back losslessly; Python 3.11 also accepts the web-style Z suffix and explicit offsets.

PythonData Integrity

Code

pythonsnippet
16 lines
from datetime import datetime, timezone

# isoformat() renders a datetime; fromisoformat() parses it back losslessly.
moment = datetime(2026, 11, 18, 9, 30, 0, tzinfo=timezone.utc)
text = moment.isoformat()
print("iso :", text)
print("round trip equal:", datetime.fromisoformat(text) == moment)

# Python 3.11+ also accepts the web-style 'Z' suffix for UTC.
zulu = datetime.fromisoformat("2026-11-18T09:30:00Z")
print("zulu:", zulu.tzinfo, zulu.utcoffset())

# Offsets ride along through parsing and conversion.
shifted = datetime.fromisoformat("2026-11-18T17:30:00+08:00")
print("shifted offset:", shifted.utcoffset())
print("as utc:", shifted.astimezone(timezone.utc).isoformat())

Output

Captured from a sandboxed run of this snippet in the build pipeline.

iso : 2026-11-18T09:30:00+00:00
round trip equal: True
zulu: UTC 0:00:00
shifted offset: 8:00:00
as utc: 2026-11-18T09:30:00+00:00

Runtime behavior

Module-level bindings hold the data — moment, text, zulu, shifted — with no function scope in between.

Caveats

  • Zero third-party dependencies — the runtime provides every API used here.

Putting it to use

Expect labeled output — iso :, round trip equal:, zulu: — when the file runs.

Interactive Tools for This Topic

FAQ

Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. Its state lives in module-level bindings: `moment`, `text`, `zulu`.