python - 检查日期是否为没有 pytz 的时区的夏令时

标签 python python-3.x datetime

由于某些原因,我的雇主不想使用 pip 安装第三方软件包,并希望我使用仅托管在 trusty 上的软件包。因此,我现在无法在代码中使用 pytz。我将如何检查时区中的某个日期是否采用夏令时?这是我使用 pytz 的原始代码。

    import pytz
    import datetime
    ...

    target_date = datetime.datetime.strptime(arg_date, "%Y-%m-%d")
    time_zone = pytz.timezone('US/Eastern')
    dst_date = time_zone.localize(target_date, is_dst=None)
    est_hour = 24
    if bool(dst_date.dst()) is True:
        est_hour -= 4
    else:
        est_hour -= 5

最佳答案

在一般情况下,这是一个复杂的问题,无法手动解决。依赖由专门负责该任务的人员审查和维护的外部模块(例如 pytz)是唯一明智的选择。

但是,考虑到您只对美国时区(尤其是东部时区)感兴趣,因此可以编写一个简单的函数。这显然只适用于当前(2016)规则,last changed in 2007并且随时可能再次改变。这些规则规定 DST starts on the second Sunday in March and ends on the first Sunday in November .

此代码基于 my algorithm for finding a particular day of a month .

def is_dst(dt):
    if dt.year < 2007:
        raise ValueError()
    dst_start = datetime.datetime(dt.year, 3, 8, 2, 0)
    dst_start += datetime.timedelta(6 - dst_start.weekday())
    dst_end = datetime.datetime(dt.year, 11, 1, 2, 0)
    dst_end += datetime.timedelta(6 - dst_end.weekday())
    return dst_start <= dt < dst_end

关于python - 检查日期是否为没有 pytz 的时区的夏令时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38722792/

相关文章:

python - 如何在子图之间创建空间?

python - 值错误 : dictionary update sequence element #0 has length 3; 2 is required when attempting to coerce generator function into dictionary

python - 根据数据框列的部分添加一列规范化值

python - 如何在 python 中自动显示已编辑的 datetime.now()?

python - 将 pandas 日期转换为周数

python - 在python中将字符串转换为日期时间对象

python - 在 Pandas 中广播 bool 运算

python - 当一个模块被导入两次时会发生什么?

python - 使用 sqlalchemy 的 row_to_json 语法

javascript - Django,如何为网站上显示的脚本制作下载按钮