How to look up historical time zones by date and location

Ben Finney ben+python at benfinney.id.au
Tue Aug 19 21:53:45 EDT 2014


luofeiyu <elearn2014 at gmail.com> writes:

> >>> tz1
> <DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD>
> >>> repr(tz1)
> "<DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD>"

Yes. Remember that ‘repr’ is for the benefit of the programmer, and
there is no promise of what it contains.

> >>> x=repr(tz1)
> >>> x
> "<DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD>"
> >>> import re
> >>> re.search("LMT.+\s",x).group()
> 'LMT+8:06:00 '

This is wildly fragile. The ‘repr’ output depends on unpublished
attributes: implementation details not part of the API which therefore
can change without notice. You're then parsing a free-form string
assuming that it will contain a structure for the data you want.

All of those assumptions are subject to change without notification, and
the result would be a bug in your code, not the library.

At the least: Reduce the number of fragile links in that chain. If you
want access to unpublished attributes, then simply access them directly.

    >>> import pytz
    >>> tz1 = pytz.timezone("Asia/Shanghai")
    >>> (zone_name, tzname, utcoffset, is_dst) = (tz1.zone, tz1._tzname, tz1._utcoffset, tz1._dst)
    >>> zone_name, tzname, utcoffset, is_dst
    ('Asia/Shanghai', 'CST', datetime.timedelta(0, 28800), datetime.timedelta(0))

Then use those values however you like.

The values will still be subject to change without notice. But at least
you'll avoid parsing structured data from a string, and you'll avoid
whatever quirks go into the ‘repr’ output.

-- 
 \      “The difference between a moral man and a man of honor is that |
  `\   the latter regrets a discreditable act, even when it has worked |
_o__)                   and he has not been caught.” —Henry L. Mencken |
Ben Finney




More information about the Python-list mailing list