Convert Unix timestamp value to human python

I have a Unix timestamp whose value is 1502878840 . This Unix timestamp value can be converted to human-readable, for example Aug 16, 2017 10:20:40 . I have the following 2 python codes to convert 1502878840 to Aug 16, 2017 10:20:40 . Both of them give the same result ( Aug 16, 2017 10:20:40 )

  • First method
    utc = datetime.fromtimestamp(1502878840)
  • Second method
    utc = datetime(1970, 1, 1) + timedelta(seconds=1502878840)

Can anyone answer me the following two questions. 1. The result of the two methods is the same. But is there a case at the logical point of the Python code that could cause a difference in the result?
I ask this question because I see that most of the python code uses the First method.
2. When I read here , Unix time will have problems January 19, 2038 03:14:08 GMT.
I run a timestamp that has a date after 19.Jan, 2038 ( 2148632440 - Feb 01, 2038 10:20:40 ). The result is as follows: First method: ValueError: timestamp out of range for platform time_t
The second method: 2038-02-01 10:20:40
Question: Can I use the second method to overcome the problem of the โ€œ2038 problemโ€?

+5
source share
1 answer

Quoting documentation :

fromtimestamp () can raise an OverflowError if the timestamp is outside the range of values โ€‹โ€‹supported by the C localtime () or gmtime () functions of the platform, and OSError when localtime () or gmtime () fails. Its total for this should be limited to the years from 1970 to 2038. Note that on systems other than POSIX, which include seconds of jump in their timestamp view, jumping seconds are ignored by fromtimestamp (), and then it can have two timestamps that differ by a second, which give identical datetime objects . See Also utcfromtimestamp ().

The second solution solves your problem:

 utc = datetime(1970, 1, 1) + timedelta(seconds=1502878840) 
+2
source

Source: https://habr.com/ru/post/1270906/


All Articles