45

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

Ninjakannon
  • 3,751
  • 7
  • 53
  • 76
Pravin
  • 469
  • 1
  • 4
  • 3

5 Answers5

63

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)
Community
  • 1
  • 1
tuomur
  • 6,888
  • 34
  • 37
26

Try this:

from datetime import datetime

datetime.fromtimestamp(*your_timestamp_here*).strftime('%Y-%m-%d')
fresheed
  • 103
  • 1
  • 7
Sagar Dawda
  • 1,126
  • 9
  • 17
13
import datetime, time

print datetime.datetime.fromtimestamp(time.time())
print datetime.datetime.fromtimestamp(43111.0)
jerboa
  • 1,371
  • 2
  • 12
  • 18
  • Thanks for your answer but 43111.0 is not the timestamp,it is the flaot number format for the date 11 January 2018. – Pravin Jul 15 '11 at 11:30
8

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.

Jacob
  • 41,721
  • 6
  • 79
  • 81
0

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.