Convert date to datetime in Python
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)
?
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
d = date.today()
datetime.combine(d, datetime.min.time())
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
.
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."
链接地址: http://www.djcxy.com/p/25190.html下一篇: 在Python中将日期转换为日期时间