Sub topic 12
Formatting and parsing dates and times
This chapter assumes you can create date, datetime, and timedelta objects and do arithmetic with them, as covered in the previous chapters. It also assumes you know the difference between naive and aware datetimes. Here you will turn those objects into text and text back into objects.
Why formatting and parsing matter
Programs rarely keep dates as objects. Dates arrive as strings in files, web forms, JSON, and logs, and they leave as strings in reports, filenames, and messages. Two operations convert between the two forms:
- Formatting turns a
date,time, ordatetimeinto a string. - Parsing turns a string into one of those objects.
Python gives you two families of tools for this. The ISO 8601 methods (isoformat and fromisoformat) are simple and unambiguous. The format-code methods (strftime and strptime) handle any layout you can describe.
flowchart LRISO 8601 with isoformat and fromisoformat
ISO 8601 is the international standard for writing dates and times, for example 2026-11-26T14:30:05. It sorts correctly as plain text and every major system understands it. When you control both ends of the exchange, use it.
from datetime import date, datetime, time
d = date(2026, 11, 26)
dt = datetime(2026, 11, 26, 14, 30, 5, 123456)
print(d.isoformat()) # 2026-11-26
print(dt.isoformat()) # 2026-11-26T14:30:05.123456
print(dt.isoformat(sep=" ", timespec="seconds")) # 2026-11-26 14:30:05
print(time(9, 5).isoformat()) # 09:05:00isoformat takes two useful arguments for datetime. sep replaces the T between date and time. timespec controls precision and accepts "hours", "minutes", "seconds", "milliseconds", and "microseconds".
The matching parsers are class methods:
from datetime import date, datetime
print(date.fromisoformat("2026-11-26"))
print(datetime.fromisoformat("2026-11-26T14:30:05+09:00"))
# 2026-11-26 14:30:05+09:00A UTC offset in the string produces an aware datetime. A string without one produces a naive datetime.
Custom layouts with strftime
strftime ("string from time") takes a format string made of literal text and % codes. Each code is replaced by part of the date.
from datetime import datetime
dt = datetime(2026, 11, 26, 14, 30, 5)
print(dt.strftime("%A, %d %B %Y")) # Thursday, 26 November 2026
print(dt.strftime("%a %b %d")) # Thu Nov 26
print(dt.strftime("%I:%M %p")) # 02:30 PM
print(dt.strftime("%H:%M:%S")) # 14:30:05
print(dt.strftime("%j")) # 330
print(dt.strftime("%y%m%d")) # 261126These codes cover most needs:
| Code | Meaning | Example |
|---|---|---|
| `%Y` | Four-digit year | `2026` |
| `%y` | Two-digit year | `26` |
| `%m` | Month, zero-padded | `11` |
| `%B` / `%b` | Full / abbreviated month name | `November` / `Nov` |
| `%d` | Day of month, zero-padded | `26` |
| `%A` / `%a` | Full / abbreviated weekday name | `Thursday` / `Thu` |
| `%j` | Day of year, zero-padded | `330` |
| `%H` / `%I` | Hour, 24-hour / 12-hour clock | `14` / `02` |
| `%M` / `%S` | Minute / second | `30` / `05` |
| `%f` | Microseconds, six digits | `123456` |
| `%p` | AM or PM | `PM` |
| `%z` / `%Z` | UTC offset / zone name | `+0900` / `JST` |
You can also use the same codes inside f-strings, because datetime supports the format-spec protocol:
from datetime import date
d = date(2026, 3, 5)
print(f"{d:%d/%m/%Y}") # 05/03/2026
print(f"{d.day} {d:%B %Y}") # 5 March 2026The last line shows the portable way to print a day without a leading zero. Some platforms accept %-d (Linux and macOS) or %#d (Windows), but neither works everywhere. Using d.day always works.
Locale and naive-time caveats
%A,%a,%B,%b, and%pfollow the process locale. Python starts in the "C" locale, which gives English names unless your program callslocale.setlocale. Do not use these codes for text that a machine will read back.%zand%Zare empty strings for naive datetimes. No error is raised, so a missing offset is easy to overlook.strftimeis for output only. Do not store dates as"%d/%m/%Y"text if you can store ISO 8601 instead.
Parsing with strptime
strptime ("string parsed to time") is the inverse of strftime. You give it the text and the format that describes it. It returns a datetime.
from datetime import datetime
dt = datetime.strptime("26 November 2026, 14:30", "%d %B %Y, %H:%M")
print(dt) # 2026-11-26 14:30:00
d = datetime.strptime("2026-11-26", "%Y-%m-%d").date()
print(d) # 2026-11-26strptime always returns a datetime, even when the text has no time. To get a date, call .date() on the result. To get a time, call .time().
Fields that the format does not mention take defaults. The year defaults to 1900, the month and day to 1, and the time to midnight:
from datetime import datetime
t = datetime.strptime("14:30", "%H:%M")
print(t) # 1900-01-01 14:30:00
print(t.time()) # 14:30:00Parsing offsets
If the format includes %z, the result is aware. %z accepts +0900, +09:00, and Z.
from datetime import datetime
dt = datetime.strptime("2026-11-26 14:30 +0900", "%Y-%m-%d %H:%M %z")
print(dt) # 2026-11-26 14:30:00+09:00
print(dt.utcoffset()) # 9:00:00A zone name parsed with %Z is limited to a few values (such as UTC, GMT, and the local zone names). It does not give you a usable zone. When you have a name such as Asia/Tokyo, parse the naive part and attach a ZoneInfo yourself, as covered in the next chapter.
Common parsing errors
strptime is strict. The text must match the format exactly, including separators, padding rules, and length.
from datetime import datetime
for text, fmt in [
("26/11/2026", "%Y-%m-%d"),
("2026-11-26 14:30", "%Y-%m-%d"),
("2026-02-30", "%Y-%m-%d"),
]:
try:
datetime.strptime(text, fmt)
except ValueError as exc:
print(exc)All three raise ValueError, for three different reasons:
- The separators and order differ, so the message is
time data '26/11/2026' does not match format '%Y-%m-%d'. - The text has a time part that the format does not cover, so the message begins
unconverted data remains. - The text matches the pattern, but 30 February does not exist, so the message says the day is out of range for the month.
A few more details are worth knowing:
%d,%m,%H, and similar codes accept one or two digits when parsing, so2026-3-5matches%Y-%m-%d.- Month and weekday names are matched without regard to case, in the current locale.
%ymaps two-digit years 69 to 99 to 1969 to 1999, and 00 to 68 to 2000 to 2068. Prefer four-digit years.strptimeis much slower thanfromisoformat. For large ISO 8601 inputs, usefromisoformat.
Accepting several input formats
When data comes from people, you often need to accept more than one layout. Try each format in turn and raise an error if none match.
from datetime import date, datetime
FORMATS = ("%Y-%m-%d", "%d/%m/%Y", "%d %B %Y")
def parse_date(text: str) -> date:
cleaned = text.strip()
for fmt in FORMATS:
try:
return datetime.strptime(cleaned, fmt).date()
except ValueError:
continue
raise ValueError(f"Unrecognised date: {text!r}")
for sample in ["2026-11-26", "26/11/2026", " 26 November 2026 "]:
print(parse_date(sample)) # 2026-11-26 each timeKeep the list short and ordered from most to least common. Every format you add increases the chance that some unusual input is accepted with a meaning you did not intend.
Round trips
A good test of any storage scheme is that parsing the formatted text gives back an equal object. isoformat and fromisoformat satisfy this, including microseconds and offsets:
from datetime import datetime, timezone
original = datetime(2026, 11, 26, 14, 30, 5, 123456, tzinfo=timezone.utc)
text = original.isoformat()
print(text) # 2026-11-26T14:30:05.123456+00:00
print(datetime.fromisoformat(text) == original) # TrueA custom strftime format round-trips only if it keeps every field you need. A format such as "%d/%m/%y" drops the century, and "%H:%M" drops seconds and any offset.
Choosing a tool
| Task | Use |
|---|---|
| Store or exchange a date or time | `isoformat()` and `fromisoformat()` |
| Show a date to a person in a chosen layout | `strftime()` or an f-string with a format spec |
| Read a date in a fixed non-ISO layout | `strptime()` |
| Read dates in unknown or mixed layouts | A list of formats tried in order, or a third-party parser |
Exercise
The call datetime.strptime("2026-11-26 14:30", "%Y-%m-%d") raises ValueError. Why, and how do you fix it?
Show answer
The format describes only the date, so the text " 14:30" is left over and Python reports "unconverted data remains". Extend the format to cover the whole text: "%Y-%m-%d %H:%M".
Exercise
Write the strftime format string that turns datetime(2026, 11, 26, 14, 30) into "Thu 26 Nov 2026, 02:30 PM". Which of its codes depend on the locale?
Show answer
"%a %d %b %Y, %I:%M %p". The codes %a, %b, and %p depend on the locale because they produce names and AM/PM text.