Sub topic 12
Formatting and parsing dates and times
This chapter assumes you can create date and datetime objects and do basic arithmetic with timedelta. Here you will convert those objects to text and text back to objects.
Two directions, four methods
Formatting turns an object into a string. Parsing turns a string into an object. The standard library has one pair for custom formats and one pair for ISO 8601, the standard YYYY-MM-DD style.
| Direction | Custom format | ISO 8601 |
|---|---|---|
| Object to string | `strftime(fmt)` | `isoformat()` |
| String to object | `datetime.strptime(text, fmt)` | `fromisoformat(text)` |
Format codes
strftime and strptime use the same percent codes. These are the ones you will use most.
| Code | Meaning | Example |
|---|---|---|
| `%Y` | Four-digit year | 2026 |
| `%y` | Two-digit year | 26 |
| `%m` | Month number, zero-padded | 11 |
| `%B` / `%b` | Month name, full / short | November / Nov |
| `%d` | Day of month, zero-padded | 26 |
| `%A` / `%a` | Weekday name, full / short | Thursday / Thu |
| `%H` / `%I` | Hour, 24-hour / 12-hour | 14 / 02 |
| `%M` / `%S` | Minute / second | 30 / 00 |
| `%p` | AM or PM | PM |
| `%j` | Day of the year | 330 |
| `%z` | UTC offset | +0000 |
Month and weekday names depend on the program's locale. In the default locale they are English.
Worked example
from datetime import date, datetime
dt = datetime(2026, 11, 26, 14, 30)
# Object to string
print(dt.isoformat()) # 2026-11-26T14:30:00
print(dt.strftime("%d %B %Y, %H:%M")) # 26 November 2026, 14:30
print(dt.strftime("%a %b %d, %I:%M %p")) # Thu Nov 26, 02:30 PM
# String to object
parsed = datetime.strptime("26/11/2026 09:05", "%d/%m/%Y %H:%M")
print(parsed) # 2026-11-26 09:05:00
print(date.fromisoformat("2026-11-26")) # 2026-11-26
print(datetime.fromisoformat("2026-11-26T14:30:00+00:00"))
# 2026-11-26 14:30:00+00:00The last line returns an aware datetime, because the string carries a UTC offset. A string without an offset produces a naive datetime. The next chapter covers the difference.
Choosing between the two parsers
Use fromisoformat when you control the format, such as in files, APIs, and logs. It is faster and needs no format string. Before Python 3.11 it accepted only the exact output of isoformat(). Later versions accept most ISO 8601 variants. If your code must run on older versions, test your input strings.
Use strptime when the text follows another layout, such as 26/11/2026 or Nov 26, 2026. The format string must match the text exactly, including separators and zero-padding rules.
Common errors
Parsing failures raise ValueError. Catch it where you handle user input.
from datetime import datetime
def parse_day(text):
try:
return datetime.strptime(text, "%Y-%m-%d").date()
except ValueError:
return None
print(parse_day("2026-11-26")) # 2026-11-26
print(parse_day("2026-13-01")) # None (there is no month 13)
print(parse_day("26-11-2026")) # None (wrong order for this format)Watch for these mistakes:
- Mixing up
%m(month) and%M(minute). Both are valid, so the code runs and gives wrong results. - Writing
%Dor%hand expecting a different meaning. Check the table above or the documentation. - Using
strftimeoutput as a sort key. Names like%Bsort alphabetically, so "April" comes before "January". Sort the objects themselves, or format as%Y-%m-%d. - Calling
strptimeon adateobject. It is a method ofdatetime. Call.date()on the result to get adate.
Exercise
Write the format string for strptime to parse "Nov 26, 2026 02:30 PM", and say what type of object strptime returns.
Show answer
The format is "%b %d, %Y %I:%M %p". It uses %b for the short month name, %I for the 12-hour clock, and %p for AM or PM. strptime returns a datetime object, here datetime(2026, 11, 26, 14, 30).