A timezone that has a variable offset from UTC The offset might change if daylight saving time comes into effect, or at a point in history when the region decides to change their timezone definition.
| 154 | |
| 155 | |
| 156 | class DstTzInfo(BaseTzInfo): |
| 157 | '''A timezone that has a variable offset from UTC |
| 158 | |
| 159 | The offset might change if daylight saving time comes into effect, |
| 160 | or at a point in history when the region decides to change their |
| 161 | timezone definition. |
| 162 | ''' |
| 163 | # Overridden in subclass |
| 164 | |
| 165 | # Sorted list of DST transition times, UTC |
| 166 | _utc_transition_times = None |
| 167 | |
| 168 | # [(utcoffset, dstoffset, tzname)] corresponding to |
| 169 | # _utc_transition_times entries |
| 170 | _transition_info = None |
| 171 | |
| 172 | zone = None |
| 173 | |
| 174 | # Set in __init__ |
| 175 | |
| 176 | _tzinfos = None |
| 177 | _dst = None # DST offset |
| 178 | |
| 179 | def __init__(self, _inf=None, _tzinfos=None): |
| 180 | if _inf: |
| 181 | self._tzinfos = _tzinfos |
| 182 | self._utcoffset, self._dst, self._tzname = _inf |
| 183 | else: |
| 184 | _tzinfos = {} |
| 185 | self._tzinfos = _tzinfos |
| 186 | self._utcoffset, self._dst, self._tzname = ( |
| 187 | self._transition_info[0]) |
| 188 | _tzinfos[self._transition_info[0]] = self |
| 189 | for inf in self._transition_info[1:]: |
| 190 | if inf not in _tzinfos: |
| 191 | _tzinfos[inf] = self.__class__(inf, _tzinfos) |
| 192 | |
| 193 | def fromutc(self, dt): |
| 194 | '''See datetime.tzinfo.fromutc''' |
| 195 | if (dt.tzinfo is not None and |
| 196 | getattr(dt.tzinfo, '_tzinfos', None) is not self._tzinfos): |
| 197 | raise ValueError('fromutc: dt.tzinfo is not self') |
| 198 | dt = dt.replace(tzinfo=None) |
| 199 | idx = max(0, bisect_right(self._utc_transition_times, dt) - 1) |
| 200 | inf = self._transition_info[idx] |
| 201 | return (dt + inf[0]).replace(tzinfo=self._tzinfos[inf]) |
| 202 | |
| 203 | def normalize(self, dt): |
| 204 | '''Correct the timezone information on the given datetime |
| 205 | |
| 206 | If date arithmetic crosses DST boundaries, the tzinfo |
| 207 | is not magically adjusted. This method normalizes the |
| 208 | tzinfo to the correct one. |
| 209 | |
| 210 | To test, first we need to do some setup |
| 211 | |
| 212 | >>> from pytz import timezone |
| 213 | >>> utc = timezone('UTC') |
nothing calls this directly
no outgoing calls
no test coverage detected