0

I have tried the following and got the error:

>>> datetime.utcfromtimestamp(1539065539).strftime('%Y-%m-%d %H:%M:%S.%f')
'2018-10-09 6:12:19.000000'.
>>> datetime.utcfromtimestamp(int(1539065539013987670)).strftime('%Y-%m-%d %H:%M:%S.%f')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument
>>> datetime.utcfromtimestamp(153906553901).strftime('%Y-%m-%d %H:%M:%S.%f')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument

I think the number is going beyond the size of int data type. Hence this error is coming. How to get rid of it and have the correct answer in the microseconds, which I am expecting.

Jaffer Wilson
  • 7,029
  • 10
  • 62
  • 139
  • It's not that "the number is going beyond the size of an int" but that you are calling the function with the wrong data. "The unix time stamp is a way to track time as a running total of seconds. This count starts at the Unix Epoch on January 1st, 1970 at UTC" so you must call the utcfromtimestamp(timestamp) with a valid timestamp in seconds. – Stuart Woodward Oct 09 '18 at 06:55

2 Answers2

2

Divide the value (which actually seems to be nanoseconds) by 1e9 to get seconds, which you can pass to utcfromtimestamp.

>>> datetime.datetime.utcfromtimestamp(1539065539013987670 / 1e9)
datetime.datetime(2018, 10, 9, 6, 12, 19, 13988)
AKX
  • 152,115
  • 15
  • 115
  • 172
1

This is answered on Python - Convert epoch time with nanoseconds to human-readable?

>>> datetime.utcfromtimestamp(1539065539013987670/1000000000).strftime('%Y-%m-%d %H:%M:%S.%f')
'2018-10-09 06:12:19.013988'
Slim
  • 648
  • 4
  • 15