使用 Python 找出当前是否处于夏令时的时区 [英] Use Python to find out if a timezone currently in daylight savings time

查看:23
本文介绍了使用 Python 找出当前是否处于夏令时的时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个在 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

这篇关于使用 Python 找出当前是否处于夏令时的时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆