Convert date to datetime in Python

Question:

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)?

Asked By: EMP

||

Answers:

There are several ways, although I do believe the one you mention (and dislike) is the most readable one.

>>> import datetime
>>> 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.

Answered By: Alex Martelli

You can use the date.timetuple() method and unpack operator *.

args = d.timetuple()[:6]
datetime.datetime(*args)
Answered By: teepark

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())
Answered By: apaderno

If you need something quick, datetime_object.date() gives you a date of a datetime object.

Answered By: Bassdread

I am a newbie to Python. But this code worked for me which converts the specified input I provide to datetime. Here’s the code. Correct me if I’m wrong.

import sys
from datetime import datetime
from time import mktime, strptime

user_date = '02/15/1989'
if user_date is not None:
     user_date = datetime.strptime(user_date,"%m/%d/%Y")
else:
     user_date = datetime.now()
print user_date
Answered By: napier

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.”

Answered By: Wes Winham

One way to convert from date to datetime that hasn’t been mentioned yet:

from datetime import date, datetime
d = date.today()
datetime.strptime(d.strftime('%Y%m%d'), '%Y%m%d')
Answered By: kadee

You can use easy_date to make it easy:

import date_converter
my_datetime = date_converter.date_to_datetime(my_date)
Answered By: Raphael Amoedo

Today being 2016, I think the cleanest solution is provided by pandas Timestamp:

from datetime import date
import pandas as pd
d = date.today()
pd.Timestamp(d)

Timestamp is the pandas equivalent of datetime and is interchangable with it in most cases. Check:

from datetime import datetime
isinstance(pd.Timestamp(d), datetime)

But in case you really want a vanilla datetime, you can still do:

pd.Timestamp(d).to_datetime()

Timestamps are a lot more powerful than datetimes, amongst others when dealing with timezones. Actually, Timestamps are so powerful that it’s a pity they are so poorly documented…

Answered By: kadee

Do I really have to manually call datetime(d.year, d.month, d.day)

No, you’d rather like to call

date_to_datetime(dt)

which you can implement once in some utils/time.py in your project:

from typing import Optional
from datetime import date, datetime

def date_to_datetime(
    dt: date,
    hour: Optional[int] = 0,
    minute: Optional[int] = 0, 
    second: Optional[int] = 0) -> datetime:

    return datetime(dt.year, dt.month, dt.day, hour, minute, second)
Answered By: SÅ‚awomir Lenart

You can use this class:

import time 

import datetime

class TimingClass():

    def __init__(self):

        self.YEAR        = datetime.date.today().year
        self.MONTH       = datetime.date.today().month
        self.DATE        = datetime.date.today().day
        self.HOUR        = datetime.datetime.now().hour
        self.MINUTE      = datetime.datetime.now().minute
        self.SECONDS     = datetime.datetime.now().second
        
        self.TODAY       = datetime.date.today()
        self.YESTERDAY   = datetime.datetime.strftime( (self.TODAY - datetime.timedelta(days = 1)) , '%Y-%m-%d')
        self.TOMORROW   = datetime.datetime.strftime( (self.TODAY + datetime.timedelta(days = 1)) , '%Y-%m-%d')
        
        self.TODAY_datetime = datetime.datetime.combine(datetime.date.today(), datetime.datetime.min.time())
Answered By: Kris Lukacs

you can also use

date = datetime.utcnow().date()
dt = datetime.fromisoformat(date.isoformat())

print(dt)

datetime.datetime(2021, 11, 15, 0, 0)

Answered By: NONONONONO

To make dt timezone aware datetime (with Django timezone util):

from django.utils import timezone


timezone.now().replace(*(*dt.timetuple()[:6], 0))
Answered By: dqd

An alternative to toisoformat/fromisoformat: you can use date.toordinal and datetime.fromordinal:

import datetime

start_date = datetime.date(1991, 2, 20)
start_date_midnight = datetime.datetime.fromordinal(start_date.toordinal())

I suspect this is more efficient than converting to/from a string.

You can test this process as so:

def test_datetime_from_date():
    for x in range(1,1000000):
        date_ = datetime.date.fromordinal(x)
        datetime_ = datetime.datetime.fromordinal(date_.toordinal())
        datetime_iso_date, t, datetime_iso_time = datetime_.isoformat().partition("T")
        assert datetime_iso_date == date_.isoformat()
Answered By: Jack Deeth
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.