Correct the timezone information on the given datetime If date arithmetic crosses DST boundaries, the tzinfo is not magically adjusted. This method normalizes the tzinfo to the correct one. To test, first we need to do some setup >>> from pytz import timezo
(self, dt)
| 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') |
| 214 | >>> eastern = timezone('US/Eastern') |
| 215 | >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)' |
| 216 | |
| 217 | We next create a datetime right on an end-of-DST transition point, |
| 218 | the instant when the wallclocks are wound back one hour. |
| 219 | |
| 220 | >>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc) |
| 221 | >>> loc_dt = utc_dt.astimezone(eastern) |
| 222 | >>> loc_dt.strftime(fmt) |
| 223 | '2002-10-27 01:00:00 EST (-0500)' |
| 224 | |
| 225 | Now, if we subtract a few minutes from it, note that the timezone |
| 226 | information has not changed. |
| 227 | |
| 228 | >>> before = loc_dt - timedelta(minutes=10) |
| 229 | >>> before.strftime(fmt) |
| 230 | '2002-10-27 00:50:00 EST (-0500)' |
| 231 | |
| 232 | But we can fix that by calling the normalize method |
| 233 | |
| 234 | >>> before = eastern.normalize(before) |
| 235 | >>> before.strftime(fmt) |
| 236 | '2002-10-27 01:50:00 EDT (-0400)' |
| 237 | |
| 238 | The supported method of converting between timezones is to use |
| 239 | datetime.astimezone(). Currently, normalize() also works: |
| 240 | |
| 241 | >>> th = timezone('Asia/Bangkok') |
| 242 | >>> am = timezone('Europe/Amsterdam') |
| 243 | >>> dt = th.localize(datetime(2011, 5, 7, 1, 2, 3)) |
| 244 | >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)' |
| 245 | >>> am.normalize(dt).strftime(fmt) |
| 246 | '2011-05-06 20:02:03 CEST (+0200)' |
| 247 | ''' |
| 248 | if dt.tzinfo is None: |
| 249 | raise ValueError('Naive time - no tzinfo set') |
| 250 | |
| 251 | # Convert dt in localtime to UTC |
| 252 | offset = dt.tzinfo._utcoffset |
| 253 | dt = dt.replace(tzinfo=None) |
| 254 | dt = dt - offset |
| 255 | # convert it back, and return it |
| 256 | return self.fromutc(dt) |
| 257 | |
| 258 | def localize(self, dt, is_dst=False): |
| 259 | '''Convert naive time to local time. |