36

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,551
  • 6
  • 50
  • 70
Pravin
  • 379
  • 1
  • 3
  • 3

5 Answers5

49

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,470
  • 31
  • 35
  • In my opinion, this isn't too dirty, since Excel dates really are just a timestamp with a different starting point. Two things to be aware of: (1) fromtimestamp() includes timezone information, which may or may not be desirable (I would guess usually not desirable - notice the 2, 0 at the end of your result). To get rid of this, use utcfromtimestamp() instead. (2) This method can't support dates earlier than 1970. – John Y Jul 15 '11 at 13:32
  • Edited my answer to use utcfromtimestamp() :) – tuomur Jul 15 '11 at 14:26
  • It is 2022 and @tuomur 's reply saved my day! :) – Rodolfo Viana Jan 14 '22 at 11:17
19

Try this:

from datetime import datetime

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

print datetime.datetime.fromtimestamp(time.time())
print datetime.datetime.fromtimestamp(43111.0)
jerboa
  • 1,271
  • 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
  • 39,723
  • 6
  • 76
  • 81
1

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.