all Python 3datetimeterm
datetime format codes
formatting
The codes for strftime/strptime: %Y year, %m month, %d day, %H hour (24h), %M minute, %S second, %A weekday, %B month, %p AM/PM.
Syntax
%Y %m %d %H %M %S %A %B %p
%H is the 24-hour field and %I the 12-hour one, and %p only means something alongside %I — bolted onto %H it changes nothing. When parsing, strptime is more forgiving about padding than it looks (%m accepts both 3 and 03), but the surrounding punctuation must match exactly, so a hyphen template will not read a dotted date. Only the documented codes are guaranteed portable; anything else is whatever the system C library happens to support.
Examples
from datetime import datetime
dt = datetime(2024, 3, 15, 14, 5, 9)
print(dt.strftime('%Y')) # → 2024
print(dt.strftime('%m')) # → 03
print(dt.strftime('%d')) # → 15
print(dt.strftime('%H:%M:%S')) # → 14:05:09
print(dt.strftime('%A')) # → Friday
print(dt.strftime('%B')) # → March
See also
Open in the full glossarydocs.python.orgReport an inaccuracy