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.
Code
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:00Runtime 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
ISO 8601 Duration ParserParse ISO 8601 durations like PT1H30M into year, month, week, day, and time components with exact or approximate total seconds.ISO Week CalculatorFind the ISO 8601 week number, ISO week-year, week start and end dates, and day of year for any calendar date, with strict date validation.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.