all Python 3datetimefunction
datetime.datetime.strftime()
formatting
Formats a datetime object into a string following a format template (the codes %Y, %m, %d, %H and so on).
Syntax
dt.strftime(format)
The format string is ultimately handed to the platform's C library, so only the documented codes are portable: tricks like %-d (day without a leading zero) work on Linux and raise on Windows. Weekday and month names (%A, %B) and AM/PM follow the current locale, which makes strftime a display tool — for data interchange isoformat() is the safer choice. The same template language also works as a format spec inside an f-string, so a separate call is not always needed.
Examples
from datetime import datetime
dt = datetime(2024, 3, 15, 14, 30, 45)
print(dt.strftime('%Y-%m-%d')) # → 2024-03-15
print(dt.strftime('%d/%m/%Y %H:%M')) # → 15/03/2024 14:30
print(dt.strftime('%A, %B %d, %Y')) # → Friday, March 15, 2024
print(dt.strftime('%I:%M %p')) # → 02:30 PM
print(dt.strftime('%Y%m%d_%H%M%S')) # → 20240315_143045
See also
Open in the full glossarydocs.python.orgReport an inaccuracy