Is there a built-in method for converting a date
to a datetime
in Python, for example getting the datetime
for the midnight of the giv
You can use datetime.combine(date, time); for the time, you create a datetime.time
object initialized to midnight.
from datetime import date
from datetime import datetime
dt = datetime.combine(date.today(), datetime.min.time())
You can use the date.timetuple()
method and unpack operator *
.
args = d.timetuple()[:6]
datetime.datetime(*args)
Do I really have to manually call datetime(d.year, d.month, d.day)
No, you'd rather like to call
date_to_datetime(dt)
which you can implement once in some utils/time.py
in your project:
from typing import Optional
from datetime import date, datetime
def date_to_datetime(
dt: date,
hour: Optional[int] = 0,
minute: Optional[int] = 0,
second: Optional[int] = 0) -> datetime:
return datetime(dt.year, dt.month, dt.day, hour, minute, second)
You can use easy_date to make it easy:
import date_converter
my_datetime = date_converter.date_to_datetime(my_date)
If you need something quick, datetime_object.date()
gives you a date of a datetime object.
I am a newbie to Python. But this code worked for me which converts the specified input I provide to datetime. Here's the code. Correct me if I'm wrong.
import sys
from datetime import datetime
from time import mktime, strptime
user_date = '02/15/1989'
if user_date is not None:
user_date = datetime.strptime(user_date,"%m/%d/%Y")
else:
user_date = datetime.now()
print user_date