Convert naive time to local time. This method should be used to construct localtimes, rather than passing a tzinfo argument to a datetime constructor. is_dst is used to determine the correct timezone in the ambiguous period at the end of daylight saving time.
(self, dt, is_dst=False)
| 256 | return self.fromutc(dt) |
| 257 | |
| 258 | def localize(self, dt, is_dst=False): |
| 259 | '''Convert naive time to local time. |
| 260 | |
| 261 | This method should be used to construct localtimes, rather |
| 262 | than passing a tzinfo argument to a datetime constructor. |
| 263 | |
| 264 | is_dst is used to determine the correct timezone in the ambiguous |
| 265 | period at the end of daylight saving time. |
| 266 | |
| 267 | >>> from pytz import timezone |
| 268 | >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)' |
| 269 | >>> amdam = timezone('Europe/Amsterdam') |
| 270 | >>> dt = datetime(2004, 10, 31, 2, 0, 0) |
| 271 | >>> loc_dt1 = amdam.localize(dt, is_dst=True) |
| 272 | >>> loc_dt2 = amdam.localize(dt, is_dst=False) |
| 273 | >>> loc_dt1.strftime(fmt) |
| 274 | '2004-10-31 02:00:00 CEST (+0200)' |
| 275 | >>> loc_dt2.strftime(fmt) |
| 276 | '2004-10-31 02:00:00 CET (+0100)' |
| 277 | >>> str(loc_dt2 - loc_dt1) |
| 278 | '1:00:00' |
| 279 | |
| 280 | Use is_dst=None to raise an AmbiguousTimeError for ambiguous |
| 281 | times at the end of daylight saving time |
| 282 | |
| 283 | >>> try: |
| 284 | ... loc_dt1 = amdam.localize(dt, is_dst=None) |
| 285 | ... except AmbiguousTimeError: |
| 286 | ... print('Ambiguous') |
| 287 | Ambiguous |
| 288 | |
| 289 | is_dst defaults to False |
| 290 | |
| 291 | >>> amdam.localize(dt) == amdam.localize(dt, False) |
| 292 | True |
| 293 | |
| 294 | is_dst is also used to determine the correct timezone in the |
| 295 | wallclock times jumped over at the start of daylight saving time. |
| 296 | |
| 297 | >>> pacific = timezone('US/Pacific') |
| 298 | >>> dt = datetime(2008, 3, 9, 2, 0, 0) |
| 299 | >>> ploc_dt1 = pacific.localize(dt, is_dst=True) |
| 300 | >>> ploc_dt2 = pacific.localize(dt, is_dst=False) |
| 301 | >>> ploc_dt1.strftime(fmt) |
| 302 | '2008-03-09 02:00:00 PDT (-0700)' |
| 303 | >>> ploc_dt2.strftime(fmt) |
| 304 | '2008-03-09 02:00:00 PST (-0800)' |
| 305 | >>> str(ploc_dt2 - ploc_dt1) |
| 306 | '1:00:00' |
| 307 | |
| 308 | Use is_dst=None to raise a NonExistentTimeError for these skipped |
| 309 | times. |
| 310 | |
| 311 | >>> try: |
| 312 | ... loc_dt1 = pacific.localize(dt, is_dst=None) |
| 313 | ... except NonExistentTimeError: |
| 314 | ... print('Non-existent') |
| 315 | Non-existent |
no test coverage detected