Convert date to datetime in Python
You can convert a date to datetime in Python using the datetime module. The datetime module has a class called date
, which can be used to create a date object. To convert a date object to a datetime object, you can use the combine()
function from the datetime module. Here is an example:
from datetime import date, datetime
# create a date object
date_object = date(2022, 12, 25)
# convert date to datetime
datetime_object = datetime.combine(date_object, datetime.min.time())
print(datetime_object)
# Output: 2022-12-25 00:00:00
Watch a video course
Python - The Practical Guide
In this example, the date(2022, 12, 25)
creates a date object representing December 25th, 2022.
The datetime.combine(date_object, datetime.min.time())
function is used to combine the date object with the minimum time (00:00:00), creating a datetime object representing December 25th, 2022 at 00:00:00.