Parse a date and print another format
Parse a date string with datetime.strptime and print it in another format with strftime. The two format strings use the same codes but run in opposite directions.
A date arrives as 05/03/2026 and the next system wants 2026-03-05.
from datetime import datetime
d = datetime.strptime("05/03/2026", "%d/%m/%Y")
print(d.strftime("%Y-%m-%d"))
print(d.strftime("%A %d %B %Y"))
print(d.date().isoformat())
try:
datetime.strptime("05/03/2026", "%m-%d-%Y")
except ValueError as e:
print("ValueError:", e)2026-03-05
Thursday 05 March 2026
2026-03-05
ValueError: time data '05/03/2026' does not match format '%m-%d-%Y'strptime reads a string into a datetime using a format, and strftime writes a datetime out with another one. Both use the codes in the format code table. A format that does not match the text raises ValueError, which the last block prints, so a bad input never turns into a wrong date. For ISO output isoformat() needs no format at all.
Month and day names follow the process locale, which is C unless the program changes it. Day first or month first is a property of the data, not the code: 05/03/2026 is read as March 5 here only because the format says so. %z parses offsets, and a result without one is a naive datetime that carries no zone.