Programmatically get the time at clock-change [clo

2019-09-21 14:32发布

问题:

i am confused about timezone and countrys at time-changes. Carlifornia changes the time at 10am, NewYork at 7am.

How can i programmatically get informations when the time will change next in California?

回答1:

To find out DST transitions, you could access Olson timezone database e.g., to find out the time of the next DST transition, in Python:

#!/usr/bin/env python
from bisect import bisect
from datetime import datetime
import pytz # $ pip install pytz

def next_dst(tz):    
    dst_transitions = getattr(tz, '_utc_transition_times', [])
    index = bisect(dst_transitions, datetime.utcnow())
    if 0 <= index < len(dst_transitions):
        return dst_transitions[index].replace(tzinfo=pytz.utc).astimezone(tz)

e.g., in Los Angeles:

dt = next_dst(pytz.timezone('America/Los_Angeles'))
print(dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))

Output:

2014-11-02 01:00:00 PST-0800

or in a local timezone:

from tzlocal import get_localzone # $ pip install tzlocal

dt = next_dst(get_localzone())
if dt is not None:
   print(dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
else:
   print("no future DST transitions")