Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Unix timestamp value to human readable python

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

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

Could anyone answer me 2 following questions.
1. The result of 2 methods are same. But at the logic view point of Python code, is there any case that may cause the difference in result?
I ask this question because I see most of the python code use First method.
2. As I read here, the Unix time will have a problem on 19 January, 2038 03:14:08 GMT.
I run a timestamp which 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
Second method: 2038-02-01 10:20:40
Question is: Can I use Second method to overcome the problem of "Year 2038 problem"?

like image 443
jackbk Avatar asked Oct 18 '22 07:10

jackbk


1 Answers

Quoting the documentation:

fromtimestamp() may raise OverflowError, if the timestamp is out of the range of values supported by the platform C localtime() or gmtime() functions, and OSError on localtime() or gmtime() failure. It’s common for this to be restricted to years in 1970 through 2038. Note that on non-POSIX systems that include leap seconds in their notion of a timestamp, leap seconds are ignored by fromtimestamp(), and then it’s possible to have two timestamps differing by a second that yield identical datetime objects. See also utcfromtimestamp().

The second solution solves your problem:

utc = datetime(1970, 1, 1) + timedelta(seconds=1502878840)
like image 183
Laurent LAPORTE Avatar answered Oct 21 '22 03:10

Laurent LAPORTE