datetime.strptime(date_string, format) reads date_string using the layout described by format and returns a new datetime. It uses the same % codes as strftime(), in reverse.
Fields missing from the format get defaults: year 1900, month 1, day 1, and time 00:00:00. The result is naive unless the format includes %z and the text has an offset.
datetime.strptime() is a classmethod of datetime.datetime: call it on the class itself, as datetime.strptime(...), and it returns a new object. Import the class first, for example from datetime import datetime.
Syntax
Pass the text and a format string that matches it exactly.
Spaces in the format match any run of whitespace, and letters such as month names match case-insensitively.
Method signatures
python
classmethod datetime.strptime(date_string, format)
# date_string: str to parse
# format: str of literal text and % codes
# returns: datetime (aware only when %z matched an offset)
Parameters
Parameter
Description
date_string
The text to parse, such as "2024-03-15 10:30".
format
The layout, such as "%Y-%m-%d %H:%M". Every character outside a code must appear in the text literally.
Return Value
Return Value
Description
datetime
A new datetime built from the parsed fields.
Python Examples
Example 1 — Parse Three Common Date Layouts
Read an SQL-style timestamp, a day/month/year date, and a compact layout without separators.