Search code examples
pythonpython-3.xdatetimetimeunix-timestamp

Unix time to real time in microseconds python


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.


Solution

  • 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)