Fetching datetime from float in Python

前端 未结 5 1903
天涯浪人
天涯浪人 2020-11-28 09:29

How does one get a datetime from a float in Python?

For e.g, I have a float such as 43111.0 and I want to get the datetime for

相关标签:
5条回答
  • 2020-11-28 09:44

    Try this:

    from datetime import datetime
    
    datetime.fromtimestamp(*your_timestamp_here*).strftime('%Y-%m-%d')
    
    0 讨论(0)
  • 2020-11-28 09:59
    import datetime, time
    
    print datetime.datetime.fromtimestamp(time.time())
    print datetime.datetime.fromtimestamp(43111.0)
    
    0 讨论(0)
  • 2020-11-28 10:01

    Looks like an Excel datetime format, called serial date. Quick and dirty way to convert it:

    >>> import datetime
    >>> serial = 43111.0
    >>> seconds = (serial - 25569) * 86400.0
    >>> datetime.datetime.utcfromtimestamp(seconds)
    datetime.datetime(2018, 1, 11, 0, 0)
    
    0 讨论(0)
  • 2020-11-28 10:10

    So, with a little math:

    If 43111 is 11 January 2018, then 0 is 30th December 1899. Python has datetime.date.fromordinal()

    Return the date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1. ValueError is raised unless 1 <= ordinal <= date.max.toordinal(). For any date d, date.fromordinal(d.toordinal()) == d.

    If you use that with an offset, you have:

    >>> dateoffset = 693594
    >>> datetime.date.fromordinal(dateoffset + 43111)
    datetime.date(2018, 1, 11)
    

    Hope that helps, even if it does not work for floats.

    0 讨论(0)
  • 2020-11-28 10:10

    Here is another way

    from pyxlsb import convert_date
    convert_date(value)
    

    You can use

    format(convert_date(value), '%m/%d/%Y')
    

    if you want to format it.

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