CKTIS / Python
Python `date`: parse text, extract the date, and combine it with a time
In Python 3.12, `strptime()` returns a `datetime`, `.date()` extracts the calendar date, and `combine()` pairs it with a chosen time.
Version: Python 3.12
Syntax
from datetime import date, datetime, time
calendar_day = date(year, month, day)
parsed = datetime.strptime(text, format_string)
calendar_day = parsed.date()
combined = datetime.combine(calendar_day, clock_time)
combined = datetime.combine(calendar_day, clock_time, tzinfo=zone)In Python 3.12, datetime.date is an immutable class in the datetime module. A date stores a year, month, and day, with no time of day or time zone. After from datetime import date, date(year, month, day) constructs a date from three integers. If the arguments fit in a C int, an invalid calendar date such as February 29, 2023, raises ValueError. In CPython 3.12, an integer that cannot be converted to a C int, such as the year in date(10**100, 1, 1), raises OverflowError before calendar validation.
After from datetime import datetime, the name datetime refers to the datetime.datetime class, not the module. The class method datetime.strptime(text, format_string) parses text using the given format and returns a datetime, even if the text contains only a date. In %d/%m/%Y, slashes separate the day, month, and four-digit year. When no time is specified, the result has time 00:00:00. A format mismatch or an invalid date raises ValueError. The date class has no strptime() method in Python 3.12.
The instance method parsed.date() returns a date with the same year, month, and day. It leaves parsed unchanged, carries over neither time nor time-zone information, and performs no time-zone conversion. This differs from the constructor date(year, month, day), which takes the date components separately.
The class method datetime.combine(calendar_day, clock_time) creates a new datetime from a date and a datetime.time object, not a string. By default it takes tzinfo from the time object; an explicit tzinfo=zone overrides that value without converting the clock time. If the first argument is a datetime, its time and tzinfo are ignored.
Examples
from datetime import date, datetime, time
parsed = datetime.strptime("29/02/2024", "%d/%m/%Y")
calendar_day = parsed.date()
assert type(calendar_day) is date
combined = datetime.combine(calendar_day, time(14, 30))
print(parsed.isoformat())
print(calendar_day.isoformat())
print(combined.isoformat())Result
2024-02-29T00:00:00 2024-02-29 2024-02-29T14:30:00
The first line shows midnight after parsing date-only text, the second shows just the date, and the third shows that same date at 14:30 with no time zone.
Related lessons
- Python · Lesson 31 · Intermediate · Version: 3