CKTIS / Python
Combine a date and a time with datetime.combine()
Parse date text with `strptime()`, extract the calendar date with `.date()`, and pair it with a separate time using `datetime.combine()`.
Version: Python 3.12
Syntax
from datetime import datetime, time
parsed = datetime.strptime(date_string, format)
day = parsed.date()
result = datetime.combine(day, time(hour, minute))
# Optional: override the time object's tzinfo.
result = datetime.combine(day, time(hour, minute), tzinfo=zone)In Python 3.12, after from datetime import datetime, time, datetime names the class from the module of the same name. The class method datetime.strptime(text, format) returns a datetime, not a date, even if the text contains only a date. With %d/%m/%Y, the time defaults to 00:00:00. If the text does not match the format or names an invalid date, parsing raises ValueError.
The instance method parsed.date() returns a date with the same year, month, and day, but no time or time-zone information. The class method datetime.combine(day, time(14, 30)) creates a new datetime from the calendar fields of day and the clock fields of the time object. You can pass a datetime as the first argument instead, but its time fields and tzinfo are ignored. Calling .date() makes it clear that only the calendar date is needed.
If you omit tzinfo, combine takes it from the time object. An explicit tzinfo overrides that default; tzinfo=None gives a result with no time-zone information. Setting tzinfo does not convert the clock time to another zone.
Examples
from datetime import datetime, time
parsed = datetime.strptime("29/02/2024", "%d/%m/%Y")
day = parsed.date()
appointment = datetime.combine(day, time(14, 30))
print(parsed.isoformat())
print(day.isoformat())
print(appointment.isoformat())Result
2024-02-29T00:00:00 2024-02-29 2024-02-29T14:30:00
The first line shows the parsed value at midnight, the second shows just the date, and the third shows the same date at 14:30 without time-zone information.
Related lessons
- Python · Lesson 31 · Intermediate · Version: 3