The Python Oracle

Convert date to datetime in Python

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle2

--

Chapters
00:00 Convert Date To Datetime In Python
00:24 Answer 1 Score 222
00:49 Answer 2 Score 60
01:01 Accepted Answer Score 1280
01:18 Answer 4 Score 132
01:52 Thank you

--

Full question
https://stackoverflow.com/questions/1937...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #datetime #date

#avk47



ACCEPTED ANSWER

Score 1280


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())



ANSWER 2

Score 222


There are several ways, although I do believe the one you mention (and dislike) is the most readable one.

>>> import datetime
>>> t=datetime.date.today()
>>> datetime.datetime.fromordinal(t.toordinal())
datetime.datetime(2009, 12, 20, 0, 0)

>>> datetime.datetime(t.year, t.month, t.day)
datetime.datetime(2009, 12, 20, 0, 0)

>>> datetime.datetime(*t.timetuple()[:-4])
datetime.datetime(2009, 12, 20, 0, 0)

and so forth -- but basically they all hinge on appropriately extracting info from the date object and ploughing it back into the suitable ctor or classfunction for datetime.




ANSWER 3

Score 132


The accepted answer is correct, but I would prefer to avoid using datetime.min.time() because it's not obvious to me exactly what it does. If it's obvious to you, then more power to you. I also feel the same way about the timetuple method and the reliance on the ordering.

In my opinion, the most readable, explicit way of doing this without relying on the reader to be very familiar with the datetime module API is:

from datetime import date, datetime
today = date.today()
today_with_time = datetime(
    year=today.year, 
    month=today.month,
    day=today.day,
)

That's my take on "explicit is better than implicit."




ANSWER 4

Score 60


You can use the date.timetuple() method and unpack operator *.

args = d.timetuple()[:6]
datetime.datetime(*args)