14

How would I get my python script to check whether or not a specific timezone that is stored in a variable using DST right now? My server is set to UTC. So I have say for instance

zonename = Pacific/Wallis

I want to run the query about if it is using DST right now and have the reply come back as either true of false.

4

2 回答 2

19
from pytz import timezone
from datetime import datetime

zonename = "Pacific/Wallis"
now = datetime.now(tz=timezone(zonename))
dst_timedelta = now.dst()
### dst_timedelta is offset to the winter time, 
### thus timedelta(0) for winter time and timedelta(0, 3600) for DST; 
### it returns None if timezone is not set

print "DST" if dst_timedelta else "no DST"

替代方法是使用:

now.timetuple().tm_isdst 

可以有 3 个值之一:0没有 DST、1DST 和-1未设置时区。

于 2013-06-18T16:01:18.813 回答
2

Python 3.9 添加了替换 pytz的zoneinfo 模块。这是现代 Python 版本的新更新版本。

from zoneinfo import ZoneInfo
from datetime import datetime

bool(datetime.now(tz=ZoneInfo("America/Chicago")).dst())
于 2022-01-03T21:43:16.283 回答