Is there a way to fix this datetime error?
Unfortunately, the datetime.datetime
class only supports microseconds ranging from 0
to 999999
. Observe:
>>> import datetime
>>> datetime.datetime(2022, 1, 20, 15, 30, 57, 2648531)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
datetime.datetime(2022, 1, 20, 15, 30, 57, 2648531)
ValueError: microsecond must be in 0..999999
>>>
But even if you go out of your way to separate the microseconds from the string to add to the unix_time
, you will still run into the problem of losing the 1
:
import datetime
date_string = '2022-01-20T15:30:57.2648531Z'
index = date_string.rindex(".")
ms = float(date_string[index: -1])
date_format = datetime.datetime.strptime(date_string[:index], "%Y-%m-%dT%H:%M:%S")
unix_time = datetime.datetime.timestamp(date_format) + ms
print(unix_time)
Output:
1642721457.264853
That is because python simply doesn't support such precision on floats:
>>> 1642721457.2648531
1642721457.264853