1

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:

1607111882000
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?

alper
  • 2,919
  • 9
  • 53
  • 102

2 Answers2

1

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'
>>> 
user
  • 675
  • 4
  • 11
  • Can the result converted into different time-zone such as for `Istanbul`? – alper Dec 06 '20 at 11:54
  • 1
    @alper Yes. A simple trick would just be to add the offset in seconds to the timestamp. For a better solution, check the [docs](https://docs.python.org/3/library/datetime.html#datetime.timezone); something like `datetime.fromtimestamp(ts, timezone(timedelta(hours=timezone_offset)))` could be used. – user Dec 07 '20 at 21:29
0

You right. And unixtimestamp (UT) wrong. I think UT mistake between second and milliseconds.

Let access https://unixtime.org/ , this website Supports Unix timestamps in seconds, milliseconds, microseconds and nanoseconds.

Example: 1607111882000 Result: Format Milliseconds (1/1,000 second) GMT Fri Dec 04 2020 19:58:02 GMT+0000 Relative 3 months ago

Bao Nam
  • 69
  • 4