Is a specific timezone using DST right now?
Asked Answered
M

2

16

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.

Mcdavid answered 18/6, 2013 at 15:46 Comment(0)
P
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"

alternative is to use:

now.timetuple().tm_isdst 

Which can have one of 3 values: 0 for no DST, 1 for DST and -1 for timezone not set.

Parrotfish answered 18/6, 2013 at 16:1 Comment(4)
my (independent) solution to the duplicate question is eerie similar (including variables names).Privett
@J.F.Sebastian: "There should be one— and preferably only one –obvious way to do it." PEP-20 aka The Zen of Python ;-)Parrotfish
that is why I love Python :)Privett
How to distinguish tm_isdst=0 in case of a timezone currently not in DST, from the timezone that does not use DST at all? In: datetime.datetime.now(pytz.timezone('Asia/Kolkata')).timetuple().tm_isdst Out: 0 In: datetime.datetime.now(pytz.timezone('Australia/Melbourne')).timetuple().tm_isdst Out: 0Miffy
G
3

Python 3.9 has added the zoneinfo module which replaces pytz. Here is a new updated version for modern Python versions.

from zoneinfo import ZoneInfo
from datetime import datetime

bool(datetime.now(tz=ZoneInfo("America/Chicago")).dst())
Glendoraglendower answered 3/1, 2022 at 21:43 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.