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

I am collecting data from sensors and I am getting a 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 data coming from sensors (incoming data is json format), I take a value time

and convert to readable time format.

I used datetime.fromtimestamp(1434549820776/1000).strftime('%Y-%m-%d %H:%M:%S')

and returned'2015-06-17 15:03:40'

Where as datetime.utcfromtimestamp(1434549820776/1000).strftime('%Y-%m-%d %H:%M:%S')

Returned:'2015-06-17 14:03:40'

As you can, there is a difference in hours, so my question is which one is better to use?

+3


source to share


3 answers


Looking at your json, you can see that the timestamp corresponds to the local location 2015-06-17 07:03:40.

Time ProbeOffset tells you that the difference between local time and UTC time is 7 hours => UTC time corresponding to your json is 2015-06-17 14:03:40.



Since this is what you get when you use datetime.utcfromtimestamp(1434549820776/1000).strftime('%Y-%m-%d %H:%M:%S')

(=> '2015-06-17 14:03:40'), this means that your timestamp is written in UTC, and therefore you must use utcfromtimestamp

if you want to be precise.

+3


source


Both are correct, they just don't give you the same time. Both assume the timestamp is a millisecond from EPOCH (usually 1/01/1970 00:00 UTC) and:

  • fromtimestamp

    specify the date and time in local time.
  • utcfromtimestamp

    gives you the date and time in UTC.


As I don't know where you live (UK?) I can't say more, in Spain, France, Belgium and Denmark, the local time is UTC + 1 in winter and UTC + 2 in summer.

You need to know if UTC time or local time is required.

+3


source


Basically you want to use what works. Ideally, your documentation will contain in what time zone the sensors report their time. It is probably in the same time zone as the person installing the sensors set their time in the first place, because unlikely sensors contain time zone information.

If you can work out what time is set on the sensors, I would recommend using UTC because it will save you any daylight saving time issues etc. It also works well in international teams.

Maybe even datetime.fromtimestamp(1434549820776/1000, timezone)

the correct answer if you cannot be sure that the time zone setting of the PC on which the program is running and the sensors match.

0


source







All Articles