Convert a datetime.date object into a datetime.datetime object with zeros for any missing time attributes

假如想象 提交于 2019-11-30 09:23:41

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/11192814/convert-a-datetime-date-object-into-a-datetime-datetime-object-with-zeros-for-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!