CKTIS / Python
Parse a date from text and combine it with a time in Python
`strptime()` reads text using a supplied format and returns a `datetime`. Use `.date()` to extract the calendar date and `combine()` to pair it with a separate time.
Version: Python 3.12
Syntax
from datetime import datetime, time
parsed = datetime.strptime(date_string, format)
calendar_date = parsed.date()
combined = datetime.combine(calendar_date, time(hour, minute))In Python 3.12, datetime.datetime.strptime is a class method of the datetime class in the datetime module. After from datetime import datetime, call datetime.strptime(date_string, format). The format tells Python how to read the text: in %d/%m/%Y, the directives mean day of the month, month, and four-digit year, and the slashes are literal. With %d/%m/%Y, the method raises ValueError if the text does not match the format or if the day, month, and year do not form a valid date.
The result is a datetime even if the text contains only a date. Missing date and time fields come from 1900-01-01T00:00:00, so a complete date without a time gives midnight. February 29 fails without a year because 1900 was not a leap year. The numeric directives in the example do not rely on locale-specific month names, unlike %B. Without %z, the result is naive (tzinfo is None); %z parses a UTC offset and produces an aware object with a fixed offset.
parsed.date() is an instance method. It returns a date object with the same year, month, and day but no time or time-zone information. It leaves parsed unchanged.
datetime.combine(calendar_date, time(14, 30)) calls a class method that builds a new datetime from the supplied date and time object. The result takes tzinfo from the time object unless you explicitly pass tzinfo. If the first argument is a datetime, its time and tzinfo are ignored. combine() neither parses text nor converts between time zones.
Examples
from datetime import datetime, time
parsed = datetime.strptime("29/02/2024", "%d/%m/%Y")
calendar_date = parsed.date()
combined = datetime.combine(calendar_date, time(14, 30))
print(parsed.isoformat())
print(calendar_date.isoformat())
print(combined.isoformat())Result
2024-02-29T00:00:00 2024-02-29 2024-02-29T14:30:00
The three lines show the parsed date and time at midnight, the date alone, and the same date at `14:30:00`. The `isoformat()` method is only used to display the values.
Related lessons
- Python · Lesson 31 · Intermediate · Version: 3
Sources
- datetime — Basic date and time types — datetime.strptime()
- datetime — Basic date and time types — datetime.date() instance method
- datetime — Basic date and time types — datetime.combine()
- datetime — Basic date and time types — strftime() and strptime() Behavior
- datetime — Basic date and time types — datetime.isoformat()
- datetime — Basic date and time types — date.isoformat()