使用 Python 找出当前时区是否处于夏令时 [英] Use Python to find out if a timezone currently in daylight savings time
问题描述
我们有一个在 GMT 时间运行的服务器.我需要编写一个 Python 脚本来确定它是否在加利福尼亚州洛杉矶当前(在这一秒)夏令时 (DST).我怎样才能做到这一点?我查看了 pytz 和 time,但我无法弄清楚.我意识到我可以创建一些逻辑,例如将 LA 的当前时间与 GMT 时间进行比较,但是如果我可以使用标准库来代替它会更清晰.
谢谢
这是我设置时区的一些示例代码:
from pytz 导入时区进口pytz从日期时间导入日期时间,时间增量tz = timezone('美国/洛杉矶')//使用 tz 实例化一个日期时间对象?
这是可以工作的代码片段.这并不优雅,这就是为什么我要问是否有图书馆或为此专门制作的东西.也许就像一个 is_dst() 函数.
utc = timezone("UTC")现在 = utc.localize(datetime.utcnow())los_angeles_tz = timezone('美国/洛杉矶')los_angeles_time = now.astimezone(los_angeles_tz)delta = los_angeles_time.utcoffset()dstDelta = timedelta(小时=-8)is_dst = (delta == dstDelta)
import pytz从日期时间导入日期时间,时间增量def is_dst(zonename):tz = pytz.timezone(zonename)现在 = pytz.utc.localize(datetime.utcnow())返回 now.astimezone(tz).dst() != timedelta(0)
用法:
<预><代码>>>>is_dst("美国/洛杉矶")错误的>>>is_dst("美国/圣保罗")真的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.
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.
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)
Usage:
>>> is_dst("America/Los_Angeles")
False
>>> is_dst("America/Sao_Paulo")
True
这篇关于使用 Python 找出当前时区是否处于夏令时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!