[Datetime-SIG] PEP 495 (Local Time Disambiguation) is ready for pronouncement

Akira Li 4kir4.1i at gmail.com
Wed Aug 19 08:51:12 CEST 2015

Tim Peters <tim.peters at gmail.com> writes:

> Related:  would people have been happier with the obvious "first" if
> it had been named "_first" instead?  For the most part it's an
> attribute intended to be set "by magic" by various timezone
> operations, not something most users need to know anything about
> (indeed, for most users it would qualify as an "attractive nuisance").

If you need to parse logs that use local time instead of utc
(unfortunately) then you have to use an analog of the "first" flag

Assuming the timestamps are monotonous (if expressed as UTC time) [1]
then to convert local time to utc:

  tz = tzlocal.get_localzone() # get local timezone as pytz tzinfo object
  for time_string in local_times_from_the_log:
      naive = datetime.strptime(time_string, "%Y/%m/%d %H:%M:%S") # no timezone
          local = tz.localize(naive, is_dst=None) # attach timezone info
      except pytz.AmbiguousTimeError:
          # first, try dst flag that is the same as the previous timestamp
          local = tz.localize(naive, is_dst=previous.dst())
          if previous >= local: # wrong order
              local = tz.localize(naive, is_dst=not local.dst()) # flip is_dst
          assert previous < local # timestamps must be increasing
      previous = local
      utc_time = local.astimezone(pytz.utc)

pytz uses *is_dst* name with the same meaning _for ambiguous times_ as
pep-495's *first* flag.

[1]: http://stackoverflow.com/questions/26217427/parsing-of-ordered-timestamps-in-local-time-to-utc-while-observing-daylight-sa

More information about the Datetime-SIG mailing list