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 找出当前是否处于夏令时的时区
基础教程推荐
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 包装空间模型 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
