Convert date to datetime in Python

后端 未结 10 2382
感动是毒
感动是毒 2020-11-28 17:10

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 giv

相关标签:
10条回答
  • 2020-11-28 18:03

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

    0 讨论(0)
  • 2020-11-28 18:08

    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')
    
    0 讨论(0)
  • 2020-11-28 18:09

    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.

    0 讨论(0)
  • 2020-11-28 18:09

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

    0 讨论(0)
提交回复
热议问题