Python daylight savings time

二次信任 提交于 2019-11-26 22:38:08

You can use time.localtime and look at the tm_isdst flag in the return value.

>>> import time
>>> time.localtime()
(2010, 5, 21, 21, 48, 51, 4, 141, 0)
>>> _.tm_isdst
0

Using time.localtime(), you can ask the same question for any arbitrary time to see whether DST would be (or was) in effect for your current time zone.

The accepted answer is fine if you are running code on your laptop, but most python applications are running on a server using UTC as local time, so they will NEVER be in daylight savings time according to the accepted answer.

The second problem is that different regions implement daylight savings on different days and times. So even if you have an unambiguous time, such as datetime.utcnow(), it could be daylight savings time in one timezone but not in another.

The best we can do then, is tell whether a given time occurs during DST for a specific timezone, and the best method I can find for doing it has already been implemtend by pytz localize function and we can use it to get a pretty good answer that works both on our laptop and on a server.

import pytz

from datetime import datetime

def is_dst(dt=None, timezone="UTC"):
    if dt is None:
        dt = datetime.utcnow()
    timezone = pytz.timezone(timezone)
    timezone_aware_date = timezone.localize(dt, is_dst=None)
    return timezone_aware_date.tzinfo._dst.seconds != 0

Some examples

>>> is_dst() # it is never DST in UTC
False
>>> is_dst(datetime(2019, 1, 1), timezone="US/Pacific")
False
>>> is_dst(datetime(2019, 4, 1), timezone="US/Pacific")
True
>>> is_dst(datetime(2019, 3, 10, 2), timezone="US/Pacific")
NonExistentTimeError
>>> is_dst(datetime(2019, 11, 3, 1), timezone="US/Pacific")
AmbiguousTimeError

In our is_dst function, we specified is_dst=None as a parameter to timezone.localize, which will cause nonsense times to throw errors. You could use is_dst=False to ignore these errors and return False for those times.

Expanding @Greg Hewgill's answer above, plus coping with local timezone (with help of pip install tzlocal), you get:

import time
from datetime import datetime, timedelta
from tzlocal import get_localzone

def to_local(dt):
    """From any timezone to local datetime - also cope with DST"""
    localtime = time.localtime()
    if localtime.tm_isdst:
        utctime = time.gmtime()
        hours_delta = timedelta(hours=(localtime.tm_hour - utctime.tm_hour))
        dt = dt - hours_delta

    return dt.replace(tzinfo=get_localzone())
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!