Use Python to find out if a timezone currently in daylight savings time(使用 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 找出当前是否处于夏令时的时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Python 找出当前是否处于夏令时的时区


基础教程推荐
- 筛选NumPy数组 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01