views:

2397

answers:

3

Silly question, but is there a built-in method for converting a date to a datetime in Python, ie. getting the datetime for the midnight of the date? The opposite conversion is easy - datetime has a .date() method. Do I really have to manually call datetime(d.year, d.month, d.day) ?

Edit: and the winner is:

datetime.combine(d, time())
+5  A: 

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

>>> 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.

Alex Martelli
+5  A: 

yeah, you pretty much do. you can use the timetuple() method and varargs though:

datetime.datetime(*(d.timetuple()[:6]))
teepark
-1 as being non obvious.
gahooa
Despite being clever, by the way.
gahooa
This is useful for my situation. I don't know if it's a date or a datetime I'm being passed, and it's not very pythonic to check which class it is. This method looks like it will work for both datetime and date objects.
Gattster
+19  A: 

You can use datetime.combine(date, time); for the time you create a datetime.time object initialized to midnight.

kiamlaluno
Thanks. Combined with the fact that time() returns (0,0) I think this comes out the cleanest: `datetime.combine(d, time())`
Evgeny
Just be careful not to let your code get datetime.time() confused with time.time(). Qualified names FTW!
Dustin
Yes, good point. Fortunately, combine() raises an exception if you pass in a `time.time` or anything else other than a `datetime.time`.
Evgeny