← Python lessons

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

CodeMeansExample
%dday, two digits14
%mmonth, two digits03
%Yyear, four digits2026
%yyear, two digits26
%B / %bmonth name, full or shortMarch / Mar
%A / %aweekday name, full or shortSaturday / Sat
%Hhour, 24-hour clock18
%Ihour, 12-hour clock06
%pAM or PMPM
%Mminute30
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

Practise this in the free Python course, where every exercise checks your code instantly.