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. It covers converting between datetimes and text.
Two directions, three tools
Parsing turns text into a datetime. Formatting turns a datetime into text. Python gives you these tools:
| Tool | Direction | Use it for |
|---|---|---|
| `fromisoformat()` | text to datetime | ISO 8601 strings |
| `isoformat()` | datetime to text | ISO 8601 output |
| `strptime()` | text to datetime | any fixed layout you describe |
| `strftime()` | datetime to text | human-readable layouts |
ISO 8601 first
ISO 8601 is the standard text form, such as 2026-11-26T11:07:59+00:00. Prefer it for storage, logs, and APIs, because it sorts correctly as text and carries the offset.
from datetime import datetime
dt = datetime.fromisoformat("2026-11-26T11:07:59+00:00")
print(dt.isoformat())
print(dt.tzinfo)
print(dt.isoformat(timespec="minutes"))This prints 2026-11-26T11:07:59+00:00, then UTC, then 2026-11-26T11:07+00:00. The timespec argument controls precision. It accepts "hours", "minutes", "seconds", "milliseconds" and "microseconds".
date.fromisoformat() and time.fromisoformat() work the same way for their own types. Invalid input raises ValueError:
from datetime import datetime
try:
datetime.fromisoformat("26/11/2026")
except ValueError as e:
print(type(e).__name__)Custom layouts with strptime
When the text is not ISO 8601, describe its layout with format codes. The name strptime means "string parse time".
from datetime import datetime
parsed = datetime.strptime("26/11/2026 11:07", "%d/%m/%Y %H:%M")
print(parsed.strftime("%A, %d %B %Y"))This prints Thursday, 26 November 2026. The strftime ("string format time") call uses the same codes in the other direction.
Common codes:
| Code | Meaning | Example |
|---|---|---|
| `%Y` | four-digit year | 2026 |
| `%m` | month number | 11 |
| `%d` | day of month | 26 |
| `%H`, `%M`, `%S` | hour (24-hour), minute, second | 11, 07, 59 |
| `%f` | microseconds | 000123 |
| `%A`, `%B` | weekday and month name | Thursday, November |
| `%z` | UTC offset | +0100 |
Time zones when parsing
strptime() returns a naive datetime unless the text includes an offset and your format has %z. The code %z accepts +0100, +01:00, and Z.
from datetime import datetime
from zoneinfo import ZoneInfo
with_offset = datetime.strptime("26/11/2026 11:07 +0100", "%d/%m/%Y %H:%M %z")
print(with_offset)
naive = datetime.strptime("26/11/2026 11:07", "%d/%m/%Y %H:%M")
print(naive.tzinfo)
aware = naive.replace(tzinfo=ZoneInfo("Europe/Paris"))
print(aware.isoformat())The output is 2026-11-26 11:07:00+01:00, then None, then 2026-11-26T11:07:00+01:00. Use replace(tzinfo=...) only when you know which zone the text was written in. It does not convert anything. It labels the same wall-clock time.
Common errors
- Format mismatch.
strptime()raisesValueErrorif the text does not match the format exactly. This includes extra characters and missing zero padding in some cases. Catch the error at input boundaries. - Month and day swapped.
%d/%m/%Yand%m/%d/%Yboth parse03/08/2026without error and give different dates. Confirm which convention your source uses. - Assuming
%Zparses names. On input,%Zrecognises onlyUTC,GMT, and your machine's local zone names. It cannot turnESTorEurope/Parisinto a zone. Use%zwith an offset, or parse naively and attach aZoneInfo. - Locale-dependent names.
%Aand%Bfollow the process locale, so output may not be English. Do not use them in data meant for machines. - Platform-specific codes.
%-d(no padding) works on Linux and macOS but not on Windows. Usedt.dayin an f-string instead.
Exercise
A form submits "03/08/2026 09:15" meaning month/day/year in America/New_York. How do you turn it into an ISO 8601 string in UTC, and what is the result?
Show answer
Parse it with datetime.strptime(text, "%m/%d/%Y %H:%M"), attach the zone with .replace(tzinfo=ZoneInfo("America/New_York")), convert with .astimezone(timezone.utc), and call .isoformat(). Daylight saving time began at 02:00 on 8 March 2026, so 09:15 is EDT (UTC-4). The result is 2026-03-08T13:15:00+00:00.