Python: the most efficient way to convert date to datetime

In Python, I convert date to datetime with:

  • conversion from date to string
  • conversion from string to datetime

code:

 import datetime dt_format="%d%m%Y" my_date = datetime.date.today() datetime.datetime.strptime(my_date.strftime(dt_format), dt_format) 

I suspect that this is far from the most effective way to do this. What is the most efficient way to convert dates to datetime in Python?

+6
source share
2 answers

Use the datetime.datetime.combine() time object, datetime.time.min represents 00:00 and will match the output of your date-string-datetime path:

 datetime.datetime.combine(my_date, datetime.time.min) 

Demo:

 >>> import datetime >>> my_date = datetime.date.today() >>> datetime.datetime.combine(my_date, datetime.time.min) datetime.datetime(2013, 3, 27, 0, 0) 
+18
source

Alternatively, as suggested here , this may be more readable:

 datetime(date.year, date.month, date.day) 
+4
source

All Articles