datetime.datetime.strptime
Parse a string with a date and time using the given format.
Python 3.13
datetime.datetime.strptime(date_string, format)Parameters
- date_stringstr
- A string with a date and time.
- formatstr
- The string format made of codes: %Y for the year, %m for the month, %d for the day, %H for hours, %M for minutes, %S for seconds.
Return value
A datetime object; raises ValueError for a string that does not match the format.
Examples
Date in day.month.year format
Python 3.13
from datetime import datetime
moment = datetime.strptime('20.05.2026 14:30', '%d.%m.%Y %H:%M')
print(moment)2026-05-20 14:30:00
The string does not match the format
Python 3.13
from datetime import datetime
try:
datetime.strptime('2026-05-20', '%d.%m.%Y')
except ValueError as error:
print(error)time data '2026-05-20' does not match format '%d.%m.%Y'
Details
The string must match the format completely, including separators and spaces, otherwise ValueError is raised. The reverse conversion is the strftime method with the same codes. For ISO strings such as 2026-05-20T14:30:00, datetime.fromisoformat is simpler.
