5

Is there a built-in function that converts a datetime.date object into a datetime.datetime object with 0's for the missing stuff? For example, suppose

tdate = datetime.date(2012,1,31)

I want to write something like either of these

tdatetime = datetime.date.datetime()
tdatetime = datetime.datetime(tdate)

and I want the output to be

datetime.datetime(2012, 1, 31, 0, 0)

But neither works. There is a builtin function to go from datetime.datetime to datetime.date, but I'm looking for the reverse operation.

One very poor solution would be to write:

datetime.datetime(tdate.year(), tdate.month(), tdate.day(), 0, 0)

I specifically want to avoid this bad way of doing it.

I've already written my own small function to do this, but I think it should be provided in the module. It's cluttering up some system-wide imports to use my function. It's workable, just not very Pythonic.

I'm just asking to see if anyone knows whether there is an efficient way to do it using only datetime module functions.

Community
  • 1
  • 1
ely
  • 63,678
  • 30
  • 130
  • 206

1 Answers1

13

Use .combine(date, time) with an empty time instance:

>>> import datetime
>>> tdate = datetime.date(2012,1,31)
>>> datetime.datetime.combine(tdate, datetime.time())
datetime.datetime(2012, 1, 31, 0, 0)

If you like to use a constant instead, use time.min:

>>> datetime.datetime.combine(tdate, datetime.time.min)
datetime.datetime(2012, 1, 31, 0, 0)
Martijn Pieters
  • 889,049
  • 245
  • 3,507
  • 2,997
  • This worked. It's saying I have to wait 11 minutes to accept, but I will at that time. Thanks. – ely Jun 25 '12 at 15:59
  • @EMS: That's because others may have even better answers for you and they need a chance too. :-) I am in no hurry. – Martijn Pieters Jun 25 '12 at 16:03
  • @EMS: For example, I just realized the hour argument to the time instance is just as optional; not giving a 0 gives the same result. – Martijn Pieters Jun 25 '12 at 16:08