Use Python to find out if the time zone is in summer

We have a server that runs in GMT. I need to write a Python script that determines whether it will currently (at this very second) Daylight Savings Time (DST) in Los Angeles, California. How can i do this? I took a look at pytz and time, but I can't figure it out. I understand that I could create some logic, such as comparing the current time in LA with GMT, but it would be much cleaner if I could use the standard library.

thank

Edit: Here is an example code that sets up the time zone:

from pytz import timezone import pytz from datetime import datetime, timedelta tz = timezone('America/Los_Angeles') // Instantiate a datetime object using tz? 

Edit: Here is a piece of code that will work. This is not elegant, so I ask if there is a library or something that has been done for this. Maybe like the function is_dst ().

 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) 
+13
python timezone time dst pytz
Nov 04 '13 at 18:39
source share
2 answers
 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) 

Using:

 >>> is_dst("America/Los_Angeles") False >>> is_dst("America/Sao_Paulo") True 
+28
Nov 04 '13 at
source share
 from datetime import datetime import pytz isdst_now_in = lambda zonename: bool(datetime.now(pytz.timezone(zonename)).dst()) 

Example:

 >>> isdst_now_in("America/Los_Angeles") # 2014-10-27 12:32:07 PDT-0700 True >>> isdst_now_in("Australia/Melbourne") # 2014-10-28 06:32:07 AEDT+1100 True 

Here is the stdlib version for Unix only using time.tzset() function :

 import os import time from contextlib import contextmanager @contextmanager def local_timezone(zonename): #NOTE: it manipulates global state oldname = os.environ.get('TZ') try: os.environ['TZ'] = zonename time.tzset() yield finally: if oldname is None: del os.environ['TZ'] else: os.environ['TZ'] = oldname time.tzset() def time_isdst_now_in(zonename): with local_timezone(zonename): return time.localtime().tm_isdst > 0 

Usage is the same:

 >>> time_isdst_now_in('Europe/London') # 2014-04-17 18:42:11 BST+0100 True 

Note: time.daylight not used due to problems in some cases with edges .

+8
Nov 14 '13 at 2:40
source share



All Articles