Python Glossary Русский

all Python 3datetimefunction

datetime.datetime.strptime()

formatting

Parses a string into a datetime object following a format template (the codes %Y, %m, %d and so on). The inverse of strftime().

Syntax

datetime.strptime(date_string, format)

The template must consume the whole string: trailing text or a separator that does not match raises ValueError, so parsing user input belongs inside a try block. Without %z in the template the result is naive, and ordering a naive datetime against an aware one is a TypeError, while == silently gives False. For ISO-formatted strings skip the template entirely — fromisoformat() is simpler and noticeably faster.

Examples

from datetime import datetime
d = datetime.strptime('2024-03-15', '%Y-%m-%d')
print(d)  # → 2024-03-15 00:00:00
d2 = datetime.strptime('15/03/2024 14:30', '%d/%m/%Y %H:%M')
print(d2)  # → 2024-03-15 14:30:00
d3 = datetime.strptime('March 15, 2024', '%B %d, %Y')
print(d3.month)  # → 3
print(datetime.strptime('2024-01-01 12:00:00', '%Y-%m-%d %H:%M:%S'))

See also

Open in the full glossarydocs.python.orgReport an inaccuracy