1 from datetime import tzinfo, timedelta, datetime
4 HOUR = timedelta(hours=1)
7 def first_sunday_on_or_after(dt):
8 days_to_go = 6 - dt.weekday()
10 dt += timedelta(days_to_go)
16 # This is a simplified (i.e., wrong for a few cases) set of rules for US
17 # DST start and end times. For a complete and up-to-date set of DST rules
18 # and timezone definitions, visit the Olson Database (or try pytz):
19 # http://www.twinsun.com/tz/tz-link.htm
20 # http://sourceforge.net/projects/pytz/ (might not be up-to-date)
22 # In the US, since 2007, DST starts at 2am (standard time) on the second
23 # Sunday in March, which is the first Sunday on or after Mar 8.
24 DSTSTART_2007 = datetime(1, 3, 8, 2)
25 # and ends at 2am (DST time; 1am standard time) on the first Sunday of Nov.
26 DSTEND_2007 = datetime(1, 11, 1, 1)
27 # From 1987 to 2006, DST used to start at 2am (standard time) on the first
28 # Sunday in April and to end at 2am (DST time; 1am standard time) on the last
29 # Sunday of October, which is the first Sunday on or after Oct 25.
30 DSTSTART_1987_2006 = datetime(1, 4, 1, 2)
31 DSTEND_1987_2006 = datetime(1, 10, 25, 1)
32 # From 1967 to 1986, DST used to start at 2am (standard time) on the last
33 # Sunday in April (the one on or after April 24) and to end at 2am (DST time;
34 # 1am standard time) on the last Sunday of October, which is the first Sunday
36 DSTSTART_1967_1986 = datetime(1, 4, 24, 2)
37 DSTEND_1967_1986 = DSTEND_1987_2006
40 class USTimeZone(tzinfo):
42 def __init__(self, hours, reprname, stdname, dstname):
43 self.stdoffset = timedelta(hours=hours)
44 self.reprname = reprname
45 self.stdname = stdname
46 self.dstname = dstname
57 def utcoffset(self, dt):
58 return self.stdoffset + self.dst(dt)
61 if dt is None or dt.tzinfo is None:
62 # An exception may be sensible here, in one or both cases.
63 # It depends on how you want to treat them. The default
64 # fromutc() implementation (called by the default astimezone()
65 # implementation) passes a datetime with dt.tzinfo is self.
67 assert dt.tzinfo is self
69 # Find start and end times for US DST. For years before 1967, return
72 dststart, dstend = DSTSTART_2007, DSTEND_2007
73 elif 1986 < dt.year < 2007:
74 dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006
75 elif 1966 < dt.year < 1987:
76 dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986
80 start = first_sunday_on_or_after(dststart.replace(year=dt.year))
81 end = first_sunday_on_or_after(dstend.replace(year=dt.year))
83 # Can't compare naive to aware objects, so strip the timezone from
85 if start <= dt.replace(tzinfo=None) < end:
91 Eastern = USTimeZone(-5, "Eastern", "EST", "EDT")
92 Central = USTimeZone(-6, "Central", "CST", "CDT")
93 Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
94 Pacific = USTimeZone(-8, "Pacific", "PST", "PDT")