Python strftime and strptime: Format and Parse Dates
strftime() turns a date into text in the format you choose. strptime() does the reverse: it reads text such as "14/03/2026" and gives back a datetime.
Read datetime first.
Format a date with strftime()
Call strftime() on a date and pass a format string. Each % code is
replaced by one part of the date.
from datetime import date
launch = date(2026, 3, 14)
print(launch.strftime("%d/%m/%Y"))
print(launch.strftime("%A %d %B %Y"))
Everything that is not a % code, such as / and spaces, is copied as it
is.
strftime format codes
| Code | Means | Example |
|---|---|---|
%d | day, two digits | 14 |
%m | month, two digits | 03 |
%Y | year, four digits | 2026 |
%y | year, two digits | 26 |
%B / %b | month name, full or short | March / Mar |
%A / %a | weekday name, full or short | Saturday / Sat |
%H | hour, 24-hour clock | 18 |
%I | hour, 12-hour clock | 06 |
%p | AM or PM | PM |
%M | minute | 30 |
from datetime import datetime
kickoff = datetime(2026, 3, 14, 18, 30)
print(kickoff.strftime("%H:%M"))
print(kickoff.strftime("%I:%M %p"))
print(kickoff.strftime("%a %d %b"))
Watch the case: %M is minutes but %m is the month. Mixing them up is the
most common format bug.
Format a date inside an f-string
Put the format codes after a colon inside the curly brackets.
from datetime import date
due = date(2026, 5, 1)
print(f"Due on {due:%d %B}")
This does the same as due.strftime("%d %B"), right inside the
f-string.
Parse a date string with strptime()
Call datetime.strptime() with the text and a format that describes it. The
codes are the same as for strftime().
from datetime import datetime
entered = "25/12/2026"
day = datetime.strptime(entered, "%d/%m/%Y")
print(day)
print(day.date())
print(day.strftime("%A"))
The text had no time, so the result is midnight. .date() keeps only the
day. Now Python knows it falls on a Friday.
When the text doesn't match the format
The format must match the text exactly, separators included. If it doesn't,
strptime() raises ValueError.
from datetime import datetime
print(datetime.strptime("2026-12-25", "%Y-%m-%d"))
print(datetime.strptime("25 Dec 2026", "%d/%m/%Y")) # this line raises ValueError
The second text uses spaces and a month name, but the format expects / and
digits. Wrap strptime() in try and except when the
text comes from a user.
Note: For text already in the 2026-12-25 form, date.fromisoformat()
is shorter and needs no format string.
See also: datetime, Days between two dates.
Your turn
Parse text as day/month/year, then print it in the form shown below.
from datetime import datetime
text = "07/02/2026"
# add two lines: parse text with strptime(), then print it with strftime()
Expected output
Sat 07 Feb 2026