Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a specific timezone using DST right now?

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.

like image 308
Jonny Flowers Avatar asked Jun 18 '13 15:06

Jonny Flowers


2 Answers

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.

like image 200
vartec Avatar answered Sep 21 '22 17:09

vartec


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())
like image 22
ayao1337 Avatar answered Sep 21 '22 17:09

ayao1337