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

房东的猫 提交于 2020-02-26 15:52:56

问题


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?


回答1:


Looking at your json, you can see that the time stamp corresponds to 2015-06-17 07:03:40 locally.

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

Since this is what you get when using datetime.utcfromtimestamp(1434549820776/1000).strftime('%Y-%m-%d %H:%M:%S') (=> '2015-06-17 14:03:40'), this means that your time stamp is written in UTC time and you should therefore use utcfromtimestamp if you want to be exact.




回答2:


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.




回答3:


Basicly you want to use what works. Ideally your documentation will contain in what timezone the sensors report their time. Likely it's in the same timezone as the person setting up the sensors set their time in the first place, because it's unlikely sensors contain time zone awareness.

If you are free to decide what time is setup in the sensors i would generally recommend to use UTC because that will spare you all kinds of trouble with daylight saving time etc. Also it works well in international teams.

Maybe even datetime.fromtimestamp(1434549820776/1000, timezone) is the right answer if you can't be sure that the time zone setting of the PC the program runs on and the sensors match.



来源:https://stackoverflow.com/questions/30921399/datetime-fromtimestamp-vs-datetime-utcfromtimestamp-which-one-is-safer-to-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!