datetime.fromisoformat / isoformat
The machine-readable pair. isoformat() writes 2026-09-29T14:30:00+02:00, fromisoformat() reads it back unchanged — and since Python 3.11 it also reads Z, basic formats like 20260929T1430 and ISO week dates.
Demo
from datetime import datetime datetime.fromisoformat('2026-09-29T14:30:05.123+02:00')
fromisoformat validates twice: the text must be ISO 8601 ("Invalid isoformat string"), and the numbers must make a real date ("day is out of range for month" for 30 February). isoformat never rounds: 14:30:59.999999 with timespec="minutes" is 14:30. UTC is written +00:00, not Z — fromisoformat accepts both.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| date_string | str | yes | ISO 8601 text. date: YYYY-MM-DD, YYYYMMDD, YYYY-Www[-D]. time: HH[:MM[:SS[.ffffff]]] plus an optional offset or Z. datetime: a date, any ONE separator character, a time. |
| sep | str | no ('T') | isoformat() on datetime only: the single character between date and time. |
| timespec | str | no ('auto') | isoformat(): 'auto', 'hours', 'minutes', 'seconds', 'milliseconds' or 'microseconds'. Extra digits are truncated, not rounded. |
Return value
datetime — fromisoformat: a new date / time / datetime (aware when the text has an offset or Z). isoformat: a str.
Common patterns
import json from datetime import datetime payload = json.dumps({'at': dt.isoformat()}) at = datetime.fromisoformat(json.loads(payload)['at'])
stamp = dt.astimezone(UTC).isoformat().replace('+00:00', 'Z')
from datetime import date try: due = date.fromisoformat(form['due']) except ValueError as e: errors['due'] = str(e)
Examples
Pitfalls
from datetime import date date.fromisoformat('2026-09-29T14:30')
from datetime import datetime datetime.fromisoformat('2026-09-29T14:30').date()
from datetime import datetime datetime.fromisoformat('2026-9-5')
from datetime import datetime datetime.strptime('2026-9-5', '%Y-%m-%d')
from datetime import datetime datetime(2026, 9, 29, 14, 30, 59, 999999).isoformat(timespec='seconds')
from datetime import datetime, timedelta dt = datetime(2026, 9, 29, 14, 30, 59, 999999) (dt + timedelta(microseconds=500000)).isoformat(timespec='seconds')
When to use
- Storing timestamps as text: JSON, CSV, logs, databases without a datetime type
- Reading API timestamps (RFC 3339 is a profile of ISO 8601)
- Form inputs of type date / time / datetime-local (they send ISO text)
- Human-facing text → strftime
- Arbitrary layouts (29/09/2026) → strptime
- ISO durations (P3DT4H) and intervals → not supported; third-party isodate
Notes
FAQ
On Python 3.11+ datetime.fromisoformat("2026-09-29T14:30:00Z") works directly and returns an aware datetime in UTC. On 3.7–3.10, replace the Z first: fromisoformat(s.replace("Z", "+00:00")).