Use Python to find out if a timezone currently in

2019-01-09 01:50发布

问题:

This question already has an answer here:

  • Is a specific timezone using DST right now? 1 answer

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.

Thanks

Edit: 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? 

Edit: 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)

回答1:

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)

Usage:

>>> is_dst("America/Los_Angeles")
False

>>> is_dst("America/Sao_Paulo")
True


回答2:

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's stdlib-only version on Unix 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

The usage is the same:

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

Note: time.daylight is not used due to issues in some edge cases.