🎓 A1Learner
🔍

Python Formatting & Parsing Dates

strftime turns a date into text in a chosen format. strptime parses text back into a date.

Names and numbers

%A is the weekday name. %B is the month name. %d and %Y are numbers.

from datetime import datetime
d = datetime(2026, 10, 22, 14, 30, 5)
print(d.strftime("%A, %B %d, %Y"))

Time codes

%H is the hour. %M is the minute. %S is the second.

from datetime import datetime
d = datetime(2026, 10, 22, 14, 30, 5)
print(d.strftime("%H:%M:%S"))

Day and week numbers

%j is the day number in the year. %U is the week number in the year.

from datetime import datetime
d = datetime(2026, 10, 22, 14, 30, 5)
print("Day of year:", d.strftime("%j"))
print("Week number:", d.strftime("%U"))

Parse text with strptime

Give strptime the text and its format. It returns a datetime.

from datetime import datetime
print(datetime.strptime("22/Oct/2026 14:30", "%d/%b/%Y %H:%M"))

Round-trip a string

Format a date to text. Parse that text back. The values should match.

from datetime import datetime
d = datetime(2026, 10, 22, 14, 30, 5)
text = d.strftime("%Y-%m-%d")
print(text)
print(datetime.strptime(text, "%Y-%m-%d").date() == d.date())

Example

from datetime import datetime

parsed = datetime.strptime("22/Oct/2026 14:30", "%d/%b/%Y %H:%M")
print(parsed.strftime("%Y-%m-%d %H:%M"))
print(parsed.strftime("%A, %B %d, %Y at %H:%M"))
print(parsed.strftime("%d/%m/%Y"))

Key points

  • Use strftime() to format a date or datetime as text
  • Use strptime() to parse text into a datetime
  • Each % code stands for one part of the date or time
  • Round-trip: format text, then parse it back to the same value

In this example, one fixed text value is parsed first. The format %d/%b/%Y %H:%M describes that text. The same datetime is then formatted three ways. The first way is short and sortable. The second way spells out the weekday and month. The third way uses day, month, and year with slashes.

Note

Day and month names depend on the system locale.

The names here use this system's plain English spellings.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which pair does opposite jobs?