Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date to datetime in Python

Is there a built-in method for converting a date to a datetime in Python, for example getting the datetime for the midnight of the given 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)?

like image 697
EMP Avatar asked Dec 21 '09 00:12

EMP


People also ask

How do I convert a date to datetime?

You can use the datetime module's combine method to combine a date and a time to create a datetime object. If you have a date object and not a time object, you can initialize the time object to minimum using the datetime object(minimum time means midnight).

How do I convert a string to a datetime in Python?

To convert string to datetime in Python, use the strptime() method. The strptime() is a built-in function of the Python datetime class used to convert a string representation of the​ date/time to a date object.


2 Answers

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()) 
like image 82
apaderno Avatar answered Oct 13 '22 09:10

apaderno


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.

like image 41
Alex Martelli Avatar answered Oct 13 '22 09:10

Alex Martelli