13

In Python, I convert a date to datetime by:

  1. converting from date to string
  2. converting 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 this is far from the most efficient way to do this. What is the most efficient way to convert a date to datetime in Python?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Joseph Victor Zammit
  • 14,760
  • 10
  • 76
  • 102
  • 2
    Does this answer your question? [Convert date to datetime in Python](https://stackoverflow.com/questions/1937622/convert-date-to-datetime-in-python) – Sławomir Lenart Jul 21 '20 at 18:10

2 Answers2

38

Use datetime.datetime.combine() with a time object, datetime.time.min represents 00:00 and would 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)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
12

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

datetime(date.year, date.month, date.day)
Community
  • 1
  • 1
J0ANMM
  • 7,849
  • 10
  • 56
  • 90