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

2022-01-16 00:00:00 python time timezone pytz dst

问题描述

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

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.

谢谢

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

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? 

这是一段可以工作的代码.它并不优雅,这就是为什么我要问是否有图书馆或为此而设计的东西.也许就像一个 is_dst() 函数.

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.

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)


解决方案

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)

用法:

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

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

相关文章