使用 Python 找出当前时区是否处于夏令时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19774709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:34:38  来源:igfitidea点击:

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

pythontimetimezonedstpytz

提问by Joey Mason

We have a server that runs on GMT time. I need to write a Python script that determines if it's currently (at this very second) Daylight Savings Time (DST) in Los Angeles, CA. How can I accomplish this? I took a look at pytz and time, but I can't figure it out. I realize that I could create some logic such as comparing the current time in LA to GMT time, but it would be a lot cleaner if I could use a standard library instead.

我们有一个在 GMT 时间运行的服务器。我需要编写一个 Python 脚本来确定它是否在加利福尼亚州洛杉矶当前(在这一秒)夏令时 (DST)。我怎样才能做到这一点?我看了一下pytz和时间,但我想不通。我意识到我可以创建一些逻辑,例如将 LA 的当前时间与 GMT 时间进行比较,但是如果我可以使用标准库来代替它会更清晰。

Thanks

谢谢

Edit: Here's some sample code of me setting up the timezone:

编辑:这是我设置时区的一些示例代码:

from pytz import timezone
import pytz
from datetime import datetime, timedelta

tz = timezone('America/Los_Angeles')
// Instantiate a datetime object using tz? 

Edit: Here's a snippet of code that will work. It's not elegant, which is why I'm asking if there's a library or something that is made for this. Maybe like a is_dst() function.

编辑:这是一段可以工作的代码。这并不优雅,这就是为什么我要问是否有图书馆或为此专门制作的东西。也许就像一个 is_dst() 函数。

utc = timezone("UTC")
now = utc.localize(datetime.utcnow())
los_angeles_tz = timezone('America/Los_Angeles')
los_angeles_time = now.astimezone(los_angeles_tz)

delta = los_angeles_time.utcoffset()
dstDelta = timedelta(hours=-8)

is_dst = (delta == dstDelta)

回答by Matt Johnson-Pint

import pytz
from datetime import datetime, timedelta

def is_dst(zonename):
    tz = pytz.timezone(zonename)
    now = pytz.utc.localize(datetime.utcnow())
    return now.astimezone(tz).dst() != timedelta(0)

Usage:

用法:

>>> is_dst("America/Los_Angeles")
False

>>> is_dst("America/Sao_Paulo")
True

回答by jfs

from datetime import datetime
import pytz

isdst_now_in = lambda zonename: bool(datetime.now(pytz.timezone(zonename)).dst())

Example:

例子:

>>> isdst_now_in("America/Los_Angeles") # 2014-10-27 12:32:07 PDT-0700
True
>>> isdst_now_in("Australia/Melbourne") # 2014-10-28 06:32:07 AEDT+1100
True

Here's stdlib-only version on Unix using time.tzset()function:

这是 Unix 上使用time.tzset()function的 stdlib-only 版本:

import os
import time
from contextlib import contextmanager

@contextmanager
def local_timezone(zonename):
    #NOTE: it manipulates global state
    oldname = os.environ.get('TZ')
    try:
        os.environ['TZ'] = zonename
        time.tzset()
        yield
    finally:
        if oldname is None:
           del os.environ['TZ']
        else:
           os.environ['TZ'] = oldname
        time.tzset()

def time_isdst_now_in(zonename):
    with local_timezone(zonename):
         return time.localtime().tm_isdst > 0

The usage is the same:

用法是一样的:

>>> time_isdst_now_in('Europe/London') # 2014-04-17 18:42:11 BST+0100
True

Note: time.daylightis not used due to issues in some edge cases.

注意:time.daylight由于某些边缘情况下的问题,不使用。