unix timestamp’s output using datetime.utcfromtimestamp() differs from its correct value

I have followed following answer in order to convert unix timestamp string into a readable date.

from datetime import datetime ts = int("1284101485")
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

As input when I provider 1607111882000; it prints 2020-12-04 19:58:02. But on the following site (https://www.unixtimestamp.com/index.php), the output is as follows:

Is equivalent to:

05/06/52897 @ 11:13pm (UTC)
52897-05-06T23:13:20+00:00 in ISO 8601

Mon, 06 May 52897 23:13:20 +0000 in RFC 822, 1036, 1123, 2822

Monday, 06-May-97 23:13:20 UTC in RFC 2822

52897-05-06T23:13:20+00:00 in RFC 3339

Why is there this difference and which one is correct? What should I do to obtain the same result as in the unixtimestamp.com site?


That website is probably using time.ctime or an equivalent function:

>>> time.ctime(time.mktime(time.gmtime(1607111882000)))
'Mon May  6 23:13:20 52897'

As to whether or not it’s correct to use that is debatable. The date might not be 100% accurate.

For your number, I think you put milliseconds instead of seconds as on my machine it gives an error (ValueError: year is out of range), but dividing by 1000 gives the correct date for both functions:

>>> ts = 1607111882
>>> print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
2020-12-04 19:58:02
>>> time.ctime(time.mktime(time.gmtime(ts)))
'Fri Dec  4 19:58:02 2020'

Leave a Reply

Your email address will not be published. Required fields are marked *