Formatting and reading dates
A printed datetime looks like 2026-03-14 09:05:00, which isn't how people usually write dates. The method strftime (string format time) turns a datetime into text in any format you like. You describe the format with codes that start with %:
from datetime import datetime
moment = datetime(2026, 3, 14, 9, 5)
print(moment.strftime("%d.%m.%Y"))
print(moment.strftime("%m/%d/%Y %H:%M"))
print(moment.strftime("%A %d %B %Y"))
14.03.2026
03/14/2026 09:05
Saturday 14 March 2026Everything in the format that isn't a code (the dots, slashes, spaces and any words) is copied into the result as it is. The most useful codes:
| Code | Means | For the moment above |
|---|---|---|
%d |
day of the month, two digits | 14 |
%m |
month, two digits | 03 |
%Y |
year, four digits | 2026 |
%H |
hour, 00 to 23 | 09 |
%M |
minutes | 05 |
%S |
seconds | 00 |
%A |
name of the weekday | Saturday |
%B |
name of the month | March |
The full list is in the documentation of the datetime module.
Small m, capital M
The classic mistake: %m is the month, %M the minutes. Mix them up and there's no error, just a wrong date:
from datetime import datetime
moment = datetime(2026, 3, 14, 9, 5)
print(moment.strftime("%d.%M.%Y"))
14.05.2026Python can't know you meant the month, so check the output of date formatting carefully.
From text to a datetime
strptime (string parse time) works the other way round: it reads a date written as text in a format you describe, and makes a datetime of it. You call it on the type itself, datetime.strptime(text, format):
from datetime import datetime
text = input("Date (dd.mm.yyyy): ")
day = datetime.strptime(text, "%d.%m.%Y")
print(day)
print(day.strftime("%A"))
24.12.2026Date (dd.mm.yyyy): 24.12.2026
2026-12-24 00:00:00
ThursdayWhen reading, a single-digit day or month is fine too: 5.1.2026 reads as 5 January. But if the text doesn't match the format, or the date doesn't exist, strptime raises a ValueError, such as ValueError: time data '2026-12-24' does not match format '%d.%m.%Y'. Catch it with try and except ValueError, just like a failed int(...).