Deividas Liveris
Deividas Liveris

Reputation: 53

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?

Upvotes: 2

Views: 6856

Answers (2)

monkut
monkut

Reputation: 43840

Convert microseconds to seconds, then you can use fromtimestamp() to convert seconds since the UNIX epoch to a datetime object.

import datetime
timestamp_microseconds = 1571299045371875
timestamp_seconds = timestamp_microseconds/1000000
dobj = datetime.datetime.fromtimestamp(timestamp_seconds)
print(dobj.isoformat())

>>> datetime.datetime(2019, 10, 17, 16, 57, 25, 371875)
>>> '2019-10-17T16:57:25.371875'

As mentioned by @MrFuppes this will return a datetime object based on the machine's local time.

From the documentation:

classmethod datetime.fromtimestamp(timestamp, tz=None)
Return the local date and time corresponding to the POSIX timestamp, such as is returned by time.time(). If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.

Upvotes: 3

FObersteiner
FObersteiner

Reputation: 25564

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'

Upvotes: 1

Related Questions