datetime.fromtimestamp vs datetime.utcfromtimestamp, which one is safer to use?

cyberbemon picture cyberbemon · Jun 18, 2015 · Viewed 50k times · Source

I'm collecting some data from sensors and I get the timestamp from it like this:

   "time": {
            "seconds": 40, 
            "year": 115, 
            "month": 5, 
            "hours": 7, 
            "time": 1434549820776, 
            "date": 17, 
            "minutes": 3, 
            "day": 3, 
            "timezoneOffset": 420
        },

I have a python script that processes the data coming from the sensors (incoming data is json format), I take the value of time and converts into readable time format.

I used datetime.fromtimestamp(1434549820776/1000).strftime('%Y-%m-%d %H:%M:%S') and that returned '2015-06-17 15:03:40'

Where as the datetime.utcfromtimestamp(1434549820776/1000).strftime('%Y-%m-%d %H:%M:%S') Returned: '2015-06-17 14:03:40'

As you can there is an hour Difference, so my question is which one is better to use?

Answer

Serge Ballesta picture Serge Ballesta · Jun 18, 2015

Both are correct, simply they do not give you same time. Both assume that timestamp is the number of millisecond from EPOCH (normally 1/01/1970 00:00 UTC) and :

  • fromtimestamp give you the date and time in local time
  • utcfromtimestamp gives you the date and time in UTC.

As I do not know where you live (UK ?) I cannot say more, in Spain, France, Belgium and Danmark, local time is UTC + 1 in winter and UTC + 2 in summer.

You must know if you need UTC time or local time.