Computer >> Computer tutorials >  >> Programming >> Python

How to convert date to datetime in Python?


You can use the datetime module's combine method to combine a date and a time to create a datetime object. If you have a date object and not a time object, you can initialize the time object to minimum using the datetime object(minimum time means midnight).

Example

from datetime import date
from datetime import datetime
my_date = date.today()
my_time = datetime.min.time()
my_datetime = datetime.combine(my_date, my_time)
print(my_datetime)

Output

2018-01-01 00:00:00

Example

from datetime import date
from datetime import datetime
my_date = date.today()
my_datetime = datetime(my_date.year, my_date.month, my_date.day)
print(my_datetime)

Output

2018-01-01 00:00:00