Sub topic 6
Parsing and formatting: ISO 8601, strptime, strftime
This chapter assumes you know the date, datetime, and timedelta types, the difference between naive and aware datetimes, and how to attach a ZoneInfo zone. Here you will turn text into datetimes (parsing) and datetimes into text (formatting). Both directions are common sources of bugs, because text carries less information than a datetime object, or different information.
Three tools, three jobs
Python gives you three main tools for text conversion.
| Tool | Direction | Best for |
|---|---|---|
| `isoformat()` | datetime to text | Storing and exchanging timestamps |
| `fromisoformat()` | text to datetime | Reading ISO 8601 input |
| `strptime()` | text to datetime | Reading any fixed, non-ISO layout |
| `strftime()` | datetime to text | Human-readable display |
Prefer ISO 8601 wherever you control the format. It sorts correctly as text, it is unambiguous about day and month order, and it can carry a UTC offset.
Writing ISO 8601 with isoformat
isoformat() produces YYYY-MM-DDTHH:MM:SS[.ffffff][+HH:MM]. The offset appears only for aware datetimes. Two arguments control the output: sep (the character between date and time, default T) and timespec (how much of the time to print).
from datetime import datetime, timezone
dt = datetime(2026, 11, 26, 11, 7, 59, 123456, tzinfo=timezone.utc)
print(dt.isoformat())
print(dt.isoformat(timespec="seconds"))
print(dt.isoformat(sep=" ", timespec="milliseconds"))This prints:
2026-11-26T11:07:59.123456+00:00
2026-11-26T11:07:59+00:00
2026-11-26 11:07:59.123+00:00The valid timespec values are auto, hours, minutes, seconds, milliseconds, and microseconds. With auto, the microseconds are omitted when they are zero. That makes the output length vary, so pass timespec="seconds" or "microseconds" if a downstream system expects a fixed width.
Python writes UTC as +00:00, not Z. Both are valid ISO 8601. If a consumer demands Z, convert to UTC first and then replace the suffix:
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
local = datetime(2026, 11, 26, 9, 0, tzinfo=ZoneInfo("America/New_York"))
utc_text = local.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
print(utc_text)This prints 2026-11-26T14:00:00Z. The conversion step matters. Replacing a non-zero offset with Z would silently change the moment in time.
Reading ISO 8601 with fromisoformat
datetime.fromisoformat() is the fast, strict way to read ISO text. Its behavior depends on your Python version, which is the main gotcha.
| Input | Python 3.9 and 3.10 | Python 3.11 and later |
|---|---|---|
| `2026-11-26T11:07:59+00:00` | works | works |
| `2026-11-26T11:07:59Z` | `ValueError` | works, gives UTC |
| `20261126T110759` | `ValueError` | works |
| `2026-11-26` | works, midnight | works, midnight |
| `2026-11-26T11:07:59.5` | `ValueError` | works |
In 3.9 and 3.10 the method accepts only what isoformat() can emit, so fractional seconds must have exactly 3 or 6 digits. If you must support those versions and receive Z, normalize first:
from datetime import datetime
def parse_iso(text: str) -> datetime:
if text.endswith("Z"):
text = text[:-1] + "+00:00"
return datetime.fromisoformat(text)
print(parse_iso("2026-11-26T11:07:59Z"))
print(parse_iso("2026-11-26T11:07:59+05:30"))This prints 2026-11-26 11:07:59+00:00 and 2026-11-26 11:07:59+05:30.
The date and time classes have their own fromisoformat() methods, so you can parse "2026-11-26" straight into a date.
An offset is not a zone
When the string contains an offset, you get a fixed-offset tzinfo. It records that the time was 5 hours 30 minutes ahead of UTC. It does not record that the zone was Asia/Kolkata, so you cannot ask it what the offset will be next summer.
from datetime import datetime
dt = datetime.fromisoformat("2026-11-26T11:07:59+05:30")
print(dt.tzinfo)
print(dt.utcoffset())This prints UTC+05:30 and 5:30:00. If your program needs the real zone, store the zone name in a separate field.
Parsing custom layouts with strptime
When the input is not ISO, datetime.strptime(text, format) parses it according to a format string. Each directive such as %d or %H matches one piece of the text, and all other characters must match literally.
from datetime import datetime
from zoneinfo import ZoneInfo
naive = datetime.strptime("26/11/2026 09:00", "%d/%m/%Y %H:%M")
print(naive)
local = naive.replace(tzinfo=ZoneInfo("America/New_York"))
print(local.isoformat())This prints 2026-11-26 09:00:00 and 2026-11-26T09:00:00-05:00. The parsed value is naive, so you attach the zone yourself. Use replace(tzinfo=...) here, because you are declaring what the wall-clock reading meant. Use astimezone() only when converting an aware value.
Missing fields get defaults
Fields absent from the format fall back to defaults: year 1900, month 1, day 1, and zero for time parts. Parsing only a time produces a datetime in 1900.
from datetime import datetime
t = datetime.strptime("11:07", "%H:%M")
print(t)
print(t.time())This prints 1900-01-01 11:07:00 and 11:07:00. If you only want the time of day, call .time() on the result. Never keep the 1900 date, because arithmetic on it will be wrong for any real zone.
Offsets in strptime
The %z directive reads a UTC offset and produces an aware datetime. It accepts +0530, +05:30, and Z.
from datetime import datetime
dt = datetime.strptime("2026-11-26 11:07 +0530", "%Y-%m-%d %H:%M %z")
print(dt)
print(dt.utcoffset())This prints 2026-11-26 11:07:00+05:30 and 5:30:00.
Errors
strptime raises ValueError when the text does not match, when text remains after the format is consumed, or when a value is out of range.
from datetime import datetime
try:
datetime.strptime("2026-11-26", "%d/%m/%Y")
except ValueError as e:
print(e)This prints time data '2026-11-26' does not match format '%d/%m/%Y'. Catch ValueError at the boundary where untrusted text enters your program, and report the offending value. Python's trailing-text failure reads unconverted data remains: ....
Formatting with strftime
strftime(format) turns a datetime into text. The same directives are used as in strptime. A datetime also works in f-strings and format(), using the directives after a colon.
from datetime import datetime
dt = datetime(2026, 11, 26, 14, 5, 9)
print(dt.strftime("%A, %d %B %Y"))
print(f"{dt:%Y-%m-%d %H:%M}")
print(dt.strftime("%I:%M %p"))
print(dt.strftime("day %j of the year"))This prints:
Thursday, 26 November 2026
2026-11-26 14:05
02:05 PM
day 330 of the yearThe directives you will use most often:
| Directive | Meaning | Example |
|---|---|---|
| `%Y` | Four-digit year | `2026` |
| `%y` | Two-digit year | `26` |
| `%m` | Month, zero-padded | `11` |
| `%d` | Day, zero-padded | `26` |
| `%H` | Hour, 24-hour clock | `14` |
| `%I` | Hour, 12-hour clock | `02` |
| `%M` | Minute | `05` |
| `%S` | Second | `09` |
| `%f` | Microseconds, six digits | `000000` |
| `%p` | AM or PM | `PM` |
| `%A` / `%a` | Weekday name, full or short | `Thursday` / `Thu` |
| `%B` / `%b` | Month name, full or short | `November` / `Nov` |
| `%z` | UTC offset | `+0000` |
| `%Z` | Zone name | `UTC` |
| `%j` | Day of year | `330` |
Gotchas when formatting
- Names depend on the locale.
%A,%B, and%pfollow the process locale, so the same code can printThursdayon one machine and a translated name on another. Never parse these back from stored text, and never use them in machine-readable output. - Padding flags are not portable. Directives such as
%-d(no zero padding) work on Linux and macOS but fail or behave differently on Windows. If you need5 Marchinstead of05 March, build it in Python:f"{dt.day} {dt:%B}". %zand%Zare empty for naive datetimes. A format ending in%zsilently produces a string without an offset, which is easy to miss.%yguesses the century. Values 69 to 99 become 1969 to 1999, and 0 to 68 become 2000 to 2068. Avoid two-digit years in anything you store.%falways prints six digits. For milliseconds, useisoformat(timespec="milliseconds").
A complete round trip
This example combines the pieces. It reads a local timestamp from a legacy export, attaches the zone the export is known to use, stores it as UTC ISO text, and later formats it for display in another zone.
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
# 1. Parse legacy text; the export is documented as Europe/Berlin local time.
naive = datetime.strptime("26.11.2026 18:30", "%d.%m.%Y %H:%M")
berlin = naive.replace(tzinfo=ZoneInfo("Europe/Berlin"))
# 2. Store as UTC ISO 8601.
stored = berlin.astimezone(timezone.utc).isoformat(timespec="seconds")
print(stored)
# 3. Read it back (the stored text always uses +00:00, so this works on 3.9+).
restored = datetime.fromisoformat(stored)
# 4. Format for a reader in Tokyo.
shown = restored.astimezone(ZoneInfo("Asia/Tokyo"))
print(shown.strftime("%Y-%m-%d %H:%M %z"))This prints 2026-11-26T17:30:00+00:00 and 2026-11-27 02:30 +0900. Berlin is UTC+1 in November, and Tokyo is UTC+9. The date changes in Tokyo, which is why display should always follow a conversion and never string editing.
Summary of rules
- Write ISO 8601 with
isoformat(), and prefer an explicittimespec. - Read ISO 8601 with
fromisoformat(), and check your Python version before relying onZ. - An offset in text gives you a fixed offset, not an IANA zone.
strptime()returns naive datetimes unless the text includes%z. Attach the zone deliberately.- Treat
%Zand locale-dependent names as display-only. - Catch
ValueErrorwhere outside text enters your program.
Exercise
The string "2026-11-26T11:07:59Z" fails with fromisoformat on Python 3.10. Write a one-line expression that parses it into an aware UTC datetime without using any library beyond the standard datetime module, and say why datetime.strptime(text, "%Y-%m-%dT%H:%M:%S%z") would also work.
Show answer
Use datetime.fromisoformat(text.replace("Z", "+00:00")), which gives 2026-11-26 11:07:59+00:00 with tzinfo equal to timezone.utc. The strptime version works because the %z directive accepts "Z" as well as offsets like "+0000" and "+00:00".
Exercise
A log line reads "03/04/26 07:15 PM" and the system that wrote it is documented to use the format day/month/two-digit-year with a 12-hour clock, in the America/Chicago zone. Write the format string for strptime, and state what the parsed datetime's tzinfo is before and after you attach the zone.
Show answer
The format string is "%d/%m/%y %I:%M %p". Straight after strptime the result is naive, so tzinfo is None. After naive.replace(tzinfo=ZoneInfo("America/Chicago")) it is aware, representing 2026-04-03 19:15 Central time. (%y maps 26 to 2026.)
Exercise
Why is f"{dt:%A %d %B}" a poor choice for a value written to a database column that other programs will parse?
Show answer
%A and %B produce locale-dependent names, so the text can change between machines or configurations, and it contains no year or offset. Store dt.isoformat() instead, and format names only when showing the value to a person.