Using python to determine if a timestamp is under daylight savings time

冷暖自知 提交于 2019-12-11 00:25:02

问题


This does not work:

t = os.path.getmtime(filename)
dTime = datetime.datetime.fromtimestamp(t)
justTime = dTime.timetuple()
if justTime.tm_isdst == 0 :
    tDelta = datetime.timedelta(hours=0)
else:
    tDelta = datetime.timedelta(hours=1)

What happens instead is that the conditional always equals 1, despite some of the timestamps being within daytime savings time.

I am trying to make a python call match the behavior of a c-based call.


回答1:


To find out whether a given timestamp corresponds to daylight saving time (DST) in the local time zone:

import os
import time

timestamp = os.path.getmtime(filename)
isdst = time.localtime(timestamp).tm_isdst > 0

It may fail. To workaround the issues, you could get a portable access to the tz database using pytz module:

from datetime import datetime
import tzlocal  # $ pip install tzlocal

local_timezone = tzlocal.get_localzone() # get pytz tzinfo
isdst = bool(datetime.fromtimestamp(timestamp, local_timezone).dst())

Related: Use Python to find out if a timezone currently in daylight savings time.




回答2:


Why do you assume that your filesystem writes down timestamps with a timezone?

On a server, you stick to UTC which does not have DST. On a desktop, you should look up the latest moment of the DST change (on or off), and correct the time accordingly. I don't know if pytz has this information, but this information is definitely available on the web in a machine-readable form.

Note that for some moments during the transition from DST some values of local time occur twice, and it's impossible to tell if a particular timestamp (e.g. 2:30 am) occurred before or after the switch (within an hour).



来源:https://stackoverflow.com/questions/36506874/using-python-to-determine-if-a-timestamp-is-under-daylight-savings-time

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