Invalid argument when converting float to datetime
I need to get datetime
from floats using Python. I am trying to use the following code:
import time
print (time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(float(63650571169.50261))))
But when executing this code, I get the error:
OSError: [Errno 22] Invalid argument
sys.float_info.max
displays 1.7976931348623157e+308
.
How to convert this float in datetime
?
+3
source to share
2 answers
It looks like your OS is using ISO 8601: 2004 (section 4.3.2.1 Gregorian calendar) with an epoch of Year 0. This can be converted by applying the correct zero offset as:
Code:
import datetime as dt
# define some constants
epoch = dt.datetime(1970, 1, 1)
gregorian_8601_to_unix_epoch = 62167305600
def gregorian_8601_to_datetime(gregorian_8601_seconds):
# get number of seconds from epoch
from_epoch = gregorian_8601_seconds - gregorian_8601_to_unix_epoch
# convert to python datetime
return epoch + dt.timedelta(seconds=from_epoch)
Test code:
print(gregorian_8601_to_datetime(63650571169.50261))
Results:
2017-01-01 10:12:49.502609
+1
source to share