'How to convert microsecond timestamp to readable date?
I want to convert the following timestamp - "1571299045371875" which is in microseconds to a date format of "2019-10-17T07:57:35.333333Z".
I've tried using:
date_time = datetime.utcfromtimestamp(timestamp)
st = date_time.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
But this gives me [Errno 22] Invalid argument, when trying to convert the timestamp.
Converting a timestamp of milliseconds works fine, but I can't lose precision.
Is there any way to convert microsecond timestamp?
Solution 1:[1]
given your expected output, you should use a datetime object that resembles UTC:
from datetime import datetime, timezone
ts = 1571299045371875
dtobj = datetime.fromtimestamp(ts/1e6, tz=timezone.utc)
# datetime.datetime(2019, 10, 17, 7, 57, 25, 371875, tzinfo=datetime.timezone.utc)
isostring = dtobj.isoformat()
# '2019-10-17T07:57:25.371875+00:00'
# or as specified in the question
isostring = dtobj.isoformat().replace('+00:00', 'Z')
# '2019-10-17T07:57:25.371875Z'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | FObersteiner |
