简体   繁体   English

使用python确定时间戳是否在夏令时之下

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

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. 相反,发生的情况是条件总是等于1,尽管其中一些时间戳在日间节省时间之内。

I am trying to make a python call match the behavior of a c-based call. 我正在尝试使python调用匹配基于c的调用的行为。

To find out whether a given timestamp corresponds to daylight saving time (DST) in the local time zone: 要查找给定的时间戳是否与本地时区中的夏令时(DST)相对应:

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: 要解决这些问题,您可以使用pytz模块对tz数据库进行可移植的访问:

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 . 相关: 使用Python来确定当前时区是否为夏时制

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. 在服务器上,您坚持使用没有DST的UTC。 On a desktop, you should look up the latest moment of the DST change (on or off), and correct the time accordingly. 在台式机上,您应该查找DST更改的最新时刻(打开或关闭),并相应地更正时间。 I don't know if pytz has this information, but this information is definitely available on the web in a machine-readable form. 我不知道pytz是否具有此信息,但是此信息绝对可以在网上以机器可读的形式获得。

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 (eg 2:30 am) occurred before or after the switch (within an hour). 请注意, 从DST过渡的某些时刻某些本地时间值会出现两次 ,并且无法判断特定的时间戳(例如,凌晨2:30)是在切换之前还是之后(在一小时之内)发生的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM