Update pytz 2016.6.1/2016f → 2022.7.1/2022g (d38ff47).

This commit is contained in:
JackDandy 2023-01-14 12:45:33 +00:00
parent 1b2869c610
commit 75136bc08e
616 changed files with 4677 additions and 1516 deletions

View file

@ -17,6 +17,7 @@
* Update package resource API 49.6.0 (3d404fd) to 63.2.0 (3ae44cd) * Update package resource API 49.6.0 (3d404fd) to 63.2.0 (3ae44cd)
* Update pyjsparser 2.7.1 (5465d03) to 2.7.1 (cbd1e05) * Update pyjsparser 2.7.1 (5465d03) to 2.7.1 (cbd1e05)
* Update profilehooks module 1.12.0 (3ee1f60) to 1.12.1 (c3fc078) * Update profilehooks module 1.12.0 (3ee1f60) to 1.12.1 (c3fc078)
* Update pytz 2016.6.1/2016f to 2022.7.1/2022g (d38ff47)
* Update Rarfile 4.0 (55fe778) to 4.1a1 (8a72967) * Update Rarfile 4.0 (55fe778) to 4.1a1 (8a72967)
* Update UnRar x64 for Windows 6.11 to 6.20 * Update UnRar x64 for Windows 6.11 to 6.20
* Update Send2Trash 1.5.0 (66afce7) to 1.8.1b0 (0ef9b32) * Update Send2Trash 1.5.0 (66afce7) to 1.8.1b0 (0ef9b32)

View file

@ -8,9 +8,22 @@ See the datetime section of the Python Library Reference for information
on how to use these modules. on how to use these modules.
''' '''
import sys
import datetime
import os.path
from pytz.exceptions import AmbiguousTimeError
from pytz.exceptions import InvalidTimeError
from pytz.exceptions import NonExistentTimeError
from pytz.exceptions import UnknownTimeZoneError
from pytz.lazy import LazyDict, LazyList, LazySet # noqa
from pytz.tzinfo import unpickler, BaseTzInfo
from pytz.tzfile import build_tzinfo
# The IANA (nee Olson) database is updated several times a year. # The IANA (nee Olson) database is updated several times a year.
OLSON_VERSION = '2016f' OLSON_VERSION = '2022g'
VERSION = '2016.6.1' # Switching to pip compatible version numbering. VERSION = '2022.7.1' # pip compatible version number.
__version__ = VERSION __version__ = VERSION
OLSEN_VERSION = OLSON_VERSION # Old releases had this misspelling OLSEN_VERSION = OLSON_VERSION # Old releases had this misspelling
@ -21,23 +34,11 @@ __all__ = [
'NonExistentTimeError', 'UnknownTimeZoneError', 'NonExistentTimeError', 'UnknownTimeZoneError',
'all_timezones', 'all_timezones_set', 'all_timezones', 'all_timezones_set',
'common_timezones', 'common_timezones_set', 'common_timezones', 'common_timezones_set',
] 'BaseTzInfo', 'FixedOffset',
]
import sys, datetime, os.path, gettext
from pytz.exceptions import AmbiguousTimeError
from pytz.exceptions import InvalidTimeError
from pytz.exceptions import NonExistentTimeError
from pytz.exceptions import UnknownTimeZoneError
from pytz.lazy import LazyDict, LazyList, LazySet
from pytz.tzinfo import unpickler
from pytz.tzfile import build_tzinfo, _byte_string
try: if sys.version_info[0] > 2: # Python 3.x
unicode
except NameError: # Python 3.x
# Python 3.x doesn't have unicode(), making writing code # Python 3.x doesn't have unicode(), making writing code
# for Python 2.3 and Python 3.x a pain. # for Python 2.3 and Python 3.x a pain.
@ -52,8 +53,11 @@ except NameError: # Python 3.x
... ...
UnicodeEncodeError: ... UnicodeEncodeError: ...
""" """
if type(s) == bytes:
s = s.decode('ASCII')
else:
s.encode('ASCII') # Raise an exception if not ASCII s.encode('ASCII') # Raise an exception if not ASCII
return s # But return the original string - not a byte string. return s # But the string - not a byte string.
else: # Python 2.x else: # Python 2.x
@ -76,11 +80,18 @@ def open_resource(name):
Uses the pkg_resources module if available and no standard file Uses the pkg_resources module if available and no standard file
found at the calculated location. found at the calculated location.
It is possible to specify different location for zoneinfo
subdir by using the PYTZ_TZDATADIR environment variable.
""" """
name_parts = name.lstrip('/').split('/') name_parts = name.lstrip('/').split('/')
for part in name_parts: for part in name_parts:
if part == os.path.pardir or os.path.sep in part: if part == os.path.pardir or os.sep in part:
raise ValueError('Bad path segment: %r' % part) raise ValueError('Bad path segment: %r' % part)
zoneinfo_dir = os.environ.get('PYTZ_TZDATADIR', None)
if zoneinfo_dir is not None:
filename = os.path.join(zoneinfo_dir, *name_parts)
else:
filename = os.path.join(os.path.dirname(__file__), filename = os.path.join(os.path.dirname(__file__),
'zoneinfo', *name_parts) 'zoneinfo', *name_parts)
if not os.path.exists(filename): if not os.path.exists(filename):
@ -100,29 +111,22 @@ def open_resource(name):
def resource_exists(name): def resource_exists(name):
"""Return true if the given resource exists""" """Return true if the given resource exists"""
try: try:
if os.environ.get('PYTZ_SKIPEXISTSCHECK', ''):
# In "standard" distributions, we can assume that
# all the listed timezones are present. As an
# import-speed optimization, you can set the
# PYTZ_SKIPEXISTSCHECK flag to skip checking
# for the presence of the resource file on disk.
return True
open_resource(name).close() open_resource(name).close()
return True return True
except IOError: except IOError:
return False return False
# Enable this when we get some translations?
# We want an i18n API that is useful to programs using Python's gettext
# module, as well as the Zope3 i18n package. Perhaps we should just provide
# the POT file and translations, and leave it up to callers to make use
# of them.
#
# t = gettext.translation(
# 'pytz', os.path.join(os.path.dirname(__file__), 'locales'),
# fallback=True
# )
# def _(timezone_name):
# """Translate a timezone name using the current locale, returning Unicode"""
# return t.ugettext(timezone_name)
_tzinfo_cache = {} _tzinfo_cache = {}
def timezone(zone): def timezone(zone):
r''' Return a datetime.tzinfo implementation for the given timezone r''' Return a datetime.tzinfo implementation for the given timezone
@ -160,6 +164,9 @@ def timezone(zone):
Unknown Unknown
''' '''
if zone is None:
raise UnknownTimeZoneError(None)
if zone.upper() == 'UTC': if zone.upper() == 'UTC':
return utc return utc
@ -169,9 +176,9 @@ def timezone(zone):
# All valid timezones are ASCII # All valid timezones are ASCII
raise UnknownTimeZoneError(zone) raise UnknownTimeZoneError(zone)
zone = _unmunge_zone(zone) zone = _case_insensitive_zone_lookup(_unmunge_zone(zone))
if zone not in _tzinfo_cache: if zone not in _tzinfo_cache:
if zone in all_timezones_set: if zone in all_timezones_set: # noqa
fp = open_resource(zone) fp = open_resource(zone)
try: try:
_tzinfo_cache[zone] = build_tzinfo(zone, fp) _tzinfo_cache[zone] = build_tzinfo(zone, fp)
@ -188,11 +195,22 @@ def _unmunge_zone(zone):
return zone.replace('_plus_', '+').replace('_minus_', '-') return zone.replace('_plus_', '+').replace('_minus_', '-')
_all_timezones_lower_to_standard = None
def _case_insensitive_zone_lookup(zone):
"""case-insensitively matching timezone, else return zone unchanged"""
global _all_timezones_lower_to_standard
if _all_timezones_lower_to_standard is None:
_all_timezones_lower_to_standard = dict((tz.lower(), tz) for tz in _all_timezones_unchecked) # noqa
return _all_timezones_lower_to_standard.get(zone.lower()) or zone # noqa
ZERO = datetime.timedelta(0) ZERO = datetime.timedelta(0)
HOUR = datetime.timedelta(hours=1) HOUR = datetime.timedelta(hours=1)
class UTC(datetime.tzinfo): class UTC(BaseTzInfo):
"""UTC """UTC
Optimized UTC implementation. It unpickles using the single module global Optimized UTC implementation. It unpickles using the single module global
@ -252,8 +270,8 @@ def _UTC():
module global. module global.
These examples belong in the UTC class above, but it is obscured; or in These examples belong in the UTC class above, but it is obscured; or in
the README.txt, but we are not depending on Python 2.4 so integrating the README.rst, but we are not depending on Python 2.4 so integrating
the README.txt examples with the unit tests is not trivial. the README.rst examples with the unit tests is not trivial.
>>> import datetime, pickle >>> import datetime, pickle
>>> dt = datetime.datetime(2005, 3, 1, 14, 13, 21, tzinfo=utc) >>> dt = datetime.datetime(2005, 3, 1, 14, 13, 21, tzinfo=utc)
@ -275,6 +293,8 @@ def _UTC():
False False
""" """
return utc return utc
_UTC.__safe_for_unpickling__ = True _UTC.__safe_for_unpickling__ = True
@ -285,9 +305,10 @@ def _p(*args):
by shortening the path. by shortening the path.
""" """
return unpickler(*args) return unpickler(*args)
_p.__safe_for_unpickling__ = True
_p.__safe_for_unpickling__ = True
class _CountryTimezoneDict(LazyDict): class _CountryTimezoneDict(LazyDict):
"""Map ISO 3166 country code to a list of timezone names commonly used """Map ISO 3166 country code to a list of timezone names commonly used
@ -334,7 +355,7 @@ class _CountryTimezoneDict(LazyDict):
if line.startswith('#'): if line.startswith('#'):
continue continue
code, coordinates, zone = line.split(None, 4)[:3] code, coordinates, zone = line.split(None, 4)[:3]
if zone not in all_timezones_set: if zone not in all_timezones_set: # noqa
continue continue
try: try:
data[code].append(zone) data[code].append(zone)
@ -344,6 +365,7 @@ class _CountryTimezoneDict(LazyDict):
finally: finally:
zone_tab.close() zone_tab.close()
country_timezones = _CountryTimezoneDict() country_timezones = _CountryTimezoneDict()
@ -367,6 +389,7 @@ class _CountryNameDict(LazyDict):
finally: finally:
zone_tab.close() zone_tab.close()
country_names = _CountryNameDict() country_names = _CountryNameDict()
@ -412,24 +435,24 @@ class _FixedOffset(datetime.tzinfo):
return dt.astimezone(self) return dt.astimezone(self)
def FixedOffset(offset, _tzinfos = {}): def FixedOffset(offset, _tzinfos={}):
"""return a fixed-offset timezone based off a number of minutes. """return a fixed-offset timezone based off a number of minutes.
>>> one = FixedOffset(-330) >>> one = FixedOffset(-330)
>>> one >>> one
pytz.FixedOffset(-330) pytz.FixedOffset(-330)
>>> one.utcoffset(datetime.datetime.now()) >>> str(one.utcoffset(datetime.datetime.now()))
datetime.timedelta(-1, 66600) '-1 day, 18:30:00'
>>> one.dst(datetime.datetime.now()) >>> str(one.dst(datetime.datetime.now()))
datetime.timedelta(0) '0:00:00'
>>> two = FixedOffset(1380) >>> two = FixedOffset(1380)
>>> two >>> two
pytz.FixedOffset(1380) pytz.FixedOffset(1380)
>>> two.utcoffset(datetime.datetime.now()) >>> str(two.utcoffset(datetime.datetime.now()))
datetime.timedelta(0, 82800) '23:00:00'
>>> two.dst(datetime.datetime.now()) >>> str(two.dst(datetime.datetime.now()))
datetime.timedelta(0) '0:00:00'
The datetime.timedelta must be between the range of -1 and 1 day, The datetime.timedelta must be between the range of -1 and 1 day,
non-inclusive. non-inclusive.
@ -478,19 +501,20 @@ def FixedOffset(offset, _tzinfos = {}):
return info return info
FixedOffset.__safe_for_unpickling__ = True FixedOffset.__safe_for_unpickling__ = True
def _test(): def _test():
import doctest, os, sys import doctest
sys.path.insert(0, os.pardir) sys.path.insert(0, os.pardir)
import pytz import pytz
return doctest.testmod(pytz) return doctest.testmod(pytz)
if __name__ == '__main__': if __name__ == '__main__':
_test() _test()
_all_timezones_unchecked = \
all_timezones = \
['Africa/Abidjan', ['Africa/Abidjan',
'Africa/Accra', 'Africa/Accra',
'Africa/Addis_Ababa', 'Africa/Addis_Ababa',
@ -586,6 +610,7 @@ all_timezones = \
'America/Cayman', 'America/Cayman',
'America/Chicago', 'America/Chicago',
'America/Chihuahua', 'America/Chihuahua',
'America/Ciudad_Juarez',
'America/Coral_Harbour', 'America/Coral_Harbour',
'America/Cordoba', 'America/Cordoba',
'America/Costa_Rica', 'America/Costa_Rica',
@ -666,6 +691,7 @@ all_timezones = \
'America/North_Dakota/Beulah', 'America/North_Dakota/Beulah',
'America/North_Dakota/Center', 'America/North_Dakota/Center',
'America/North_Dakota/New_Salem', 'America/North_Dakota/New_Salem',
'America/Nuuk',
'America/Ojinaga', 'America/Ojinaga',
'America/Panama', 'America/Panama',
'America/Pangnirtung', 'America/Pangnirtung',
@ -676,6 +702,7 @@ all_timezones = \
'America/Porto_Acre', 'America/Porto_Acre',
'America/Porto_Velho', 'America/Porto_Velho',
'America/Puerto_Rico', 'America/Puerto_Rico',
'America/Punta_Arenas',
'America/Rainy_River', 'America/Rainy_River',
'America/Rankin_Inlet', 'America/Rankin_Inlet',
'America/Recife', 'America/Recife',
@ -731,6 +758,7 @@ all_timezones = \
'Asia/Aqtobe', 'Asia/Aqtobe',
'Asia/Ashgabat', 'Asia/Ashgabat',
'Asia/Ashkhabad', 'Asia/Ashkhabad',
'Asia/Atyrau',
'Asia/Baghdad', 'Asia/Baghdad',
'Asia/Bahrain', 'Asia/Bahrain',
'Asia/Baku', 'Asia/Baku',
@ -751,6 +779,7 @@ all_timezones = \
'Asia/Dili', 'Asia/Dili',
'Asia/Dubai', 'Asia/Dubai',
'Asia/Dushanbe', 'Asia/Dushanbe',
'Asia/Famagusta',
'Asia/Gaza', 'Asia/Gaza',
'Asia/Harbin', 'Asia/Harbin',
'Asia/Hebron', 'Asia/Hebron',
@ -789,6 +818,7 @@ all_timezones = \
'Asia/Pontianak', 'Asia/Pontianak',
'Asia/Pyongyang', 'Asia/Pyongyang',
'Asia/Qatar', 'Asia/Qatar',
'Asia/Qostanay',
'Asia/Qyzylorda', 'Asia/Qyzylorda',
'Asia/Rangoon', 'Asia/Rangoon',
'Asia/Riyadh', 'Asia/Riyadh',
@ -816,6 +846,7 @@ all_timezones = \
'Asia/Vientiane', 'Asia/Vientiane',
'Asia/Vladivostok', 'Asia/Vladivostok',
'Asia/Yakutsk', 'Asia/Yakutsk',
'Asia/Yangon',
'Asia/Yekaterinburg', 'Asia/Yekaterinburg',
'Asia/Yerevan', 'Asia/Yerevan',
'Atlantic/Azores', 'Atlantic/Azores',
@ -861,7 +892,6 @@ all_timezones = \
'CST6CDT', 'CST6CDT',
'Canada/Atlantic', 'Canada/Atlantic',
'Canada/Central', 'Canada/Central',
'Canada/East-Saskatchewan',
'Canada/Eastern', 'Canada/Eastern',
'Canada/Mountain', 'Canada/Mountain',
'Canada/Newfoundland', 'Canada/Newfoundland',
@ -935,6 +965,7 @@ all_timezones = \
'Europe/Kaliningrad', 'Europe/Kaliningrad',
'Europe/Kiev', 'Europe/Kiev',
'Europe/Kirov', 'Europe/Kirov',
'Europe/Kyiv',
'Europe/Lisbon', 'Europe/Lisbon',
'Europe/Ljubljana', 'Europe/Ljubljana',
'Europe/London', 'Europe/London',
@ -955,6 +986,7 @@ all_timezones = \
'Europe/Samara', 'Europe/Samara',
'Europe/San_Marino', 'Europe/San_Marino',
'Europe/Sarajevo', 'Europe/Sarajevo',
'Europe/Saratov',
'Europe/Simferopol', 'Europe/Simferopol',
'Europe/Skopje', 'Europe/Skopje',
'Europe/Sofia', 'Europe/Sofia',
@ -1028,6 +1060,7 @@ all_timezones = \
'Pacific/Guam', 'Pacific/Guam',
'Pacific/Honolulu', 'Pacific/Honolulu',
'Pacific/Johnston', 'Pacific/Johnston',
'Pacific/Kanton',
'Pacific/Kiritimati', 'Pacific/Kiritimati',
'Pacific/Kosrae', 'Pacific/Kosrae',
'Pacific/Kwajalein', 'Pacific/Kwajalein',
@ -1072,7 +1105,6 @@ all_timezones = \
'US/Michigan', 'US/Michigan',
'US/Mountain', 'US/Mountain',
'US/Pacific', 'US/Pacific',
'US/Pacific-New',
'US/Samoa', 'US/Samoa',
'UTC', 'UTC',
'Universal', 'Universal',
@ -1080,7 +1112,7 @@ all_timezones = \
'WET', 'WET',
'Zulu'] 'Zulu']
all_timezones = LazyList( all_timezones = LazyList(
tz for tz in all_timezones if resource_exists(tz)) tz for tz in _all_timezones_unchecked if resource_exists(tz))
all_timezones_set = LazySet(all_timezones) all_timezones_set = LazySet(all_timezones)
common_timezones = \ common_timezones = \
@ -1173,6 +1205,7 @@ common_timezones = \
'America/Cayman', 'America/Cayman',
'America/Chicago', 'America/Chicago',
'America/Chihuahua', 'America/Chihuahua',
'America/Ciudad_Juarez',
'America/Costa_Rica', 'America/Costa_Rica',
'America/Creston', 'America/Creston',
'America/Cuiaba', 'America/Cuiaba',
@ -1189,7 +1222,6 @@ common_timezones = \
'America/Fort_Nelson', 'America/Fort_Nelson',
'America/Fortaleza', 'America/Fortaleza',
'America/Glace_Bay', 'America/Glace_Bay',
'America/Godthab',
'America/Goose_Bay', 'America/Goose_Bay',
'America/Grand_Turk', 'America/Grand_Turk',
'America/Grenada', 'America/Grenada',
@ -1237,22 +1269,21 @@ common_timezones = \
'America/Montserrat', 'America/Montserrat',
'America/Nassau', 'America/Nassau',
'America/New_York', 'America/New_York',
'America/Nipigon',
'America/Nome', 'America/Nome',
'America/Noronha', 'America/Noronha',
'America/North_Dakota/Beulah', 'America/North_Dakota/Beulah',
'America/North_Dakota/Center', 'America/North_Dakota/Center',
'America/North_Dakota/New_Salem', 'America/North_Dakota/New_Salem',
'America/Nuuk',
'America/Ojinaga', 'America/Ojinaga',
'America/Panama', 'America/Panama',
'America/Pangnirtung',
'America/Paramaribo', 'America/Paramaribo',
'America/Phoenix', 'America/Phoenix',
'America/Port-au-Prince', 'America/Port-au-Prince',
'America/Port_of_Spain', 'America/Port_of_Spain',
'America/Porto_Velho', 'America/Porto_Velho',
'America/Puerto_Rico', 'America/Puerto_Rico',
'America/Rainy_River', 'America/Punta_Arenas',
'America/Rankin_Inlet', 'America/Rankin_Inlet',
'America/Recife', 'America/Recife',
'America/Regina', 'America/Regina',
@ -1273,7 +1304,6 @@ common_timezones = \
'America/Swift_Current', 'America/Swift_Current',
'America/Tegucigalpa', 'America/Tegucigalpa',
'America/Thule', 'America/Thule',
'America/Thunder_Bay',
'America/Tijuana', 'America/Tijuana',
'America/Toronto', 'America/Toronto',
'America/Tortola', 'America/Tortola',
@ -1301,6 +1331,7 @@ common_timezones = \
'Asia/Aqtau', 'Asia/Aqtau',
'Asia/Aqtobe', 'Asia/Aqtobe',
'Asia/Ashgabat', 'Asia/Ashgabat',
'Asia/Atyrau',
'Asia/Baghdad', 'Asia/Baghdad',
'Asia/Bahrain', 'Asia/Bahrain',
'Asia/Baku', 'Asia/Baku',
@ -1317,6 +1348,7 @@ common_timezones = \
'Asia/Dili', 'Asia/Dili',
'Asia/Dubai', 'Asia/Dubai',
'Asia/Dushanbe', 'Asia/Dushanbe',
'Asia/Famagusta',
'Asia/Gaza', 'Asia/Gaza',
'Asia/Hebron', 'Asia/Hebron',
'Asia/Ho_Chi_Minh', 'Asia/Ho_Chi_Minh',
@ -1350,8 +1382,8 @@ common_timezones = \
'Asia/Pontianak', 'Asia/Pontianak',
'Asia/Pyongyang', 'Asia/Pyongyang',
'Asia/Qatar', 'Asia/Qatar',
'Asia/Qostanay',
'Asia/Qyzylorda', 'Asia/Qyzylorda',
'Asia/Rangoon',
'Asia/Riyadh', 'Asia/Riyadh',
'Asia/Sakhalin', 'Asia/Sakhalin',
'Asia/Samarkand', 'Asia/Samarkand',
@ -1372,6 +1404,7 @@ common_timezones = \
'Asia/Vientiane', 'Asia/Vientiane',
'Asia/Vladivostok', 'Asia/Vladivostok',
'Asia/Yakutsk', 'Asia/Yakutsk',
'Asia/Yangon',
'Asia/Yekaterinburg', 'Asia/Yekaterinburg',
'Asia/Yerevan', 'Asia/Yerevan',
'Atlantic/Azores', 'Atlantic/Azores',
@ -1387,7 +1420,6 @@ common_timezones = \
'Australia/Adelaide', 'Australia/Adelaide',
'Australia/Brisbane', 'Australia/Brisbane',
'Australia/Broken_Hill', 'Australia/Broken_Hill',
'Australia/Currie',
'Australia/Darwin', 'Australia/Darwin',
'Australia/Eucla', 'Australia/Eucla',
'Australia/Hobart', 'Australia/Hobart',
@ -1423,8 +1455,8 @@ common_timezones = \
'Europe/Istanbul', 'Europe/Istanbul',
'Europe/Jersey', 'Europe/Jersey',
'Europe/Kaliningrad', 'Europe/Kaliningrad',
'Europe/Kiev',
'Europe/Kirov', 'Europe/Kirov',
'Europe/Kyiv',
'Europe/Lisbon', 'Europe/Lisbon',
'Europe/Ljubljana', 'Europe/Ljubljana',
'Europe/London', 'Europe/London',
@ -1444,6 +1476,7 @@ common_timezones = \
'Europe/Samara', 'Europe/Samara',
'Europe/San_Marino', 'Europe/San_Marino',
'Europe/Sarajevo', 'Europe/Sarajevo',
'Europe/Saratov',
'Europe/Simferopol', 'Europe/Simferopol',
'Europe/Skopje', 'Europe/Skopje',
'Europe/Sofia', 'Europe/Sofia',
@ -1451,7 +1484,6 @@ common_timezones = \
'Europe/Tallinn', 'Europe/Tallinn',
'Europe/Tirane', 'Europe/Tirane',
'Europe/Ulyanovsk', 'Europe/Ulyanovsk',
'Europe/Uzhgorod',
'Europe/Vaduz', 'Europe/Vaduz',
'Europe/Vatican', 'Europe/Vatican',
'Europe/Vienna', 'Europe/Vienna',
@ -1459,7 +1491,6 @@ common_timezones = \
'Europe/Volgograd', 'Europe/Volgograd',
'Europe/Warsaw', 'Europe/Warsaw',
'Europe/Zagreb', 'Europe/Zagreb',
'Europe/Zaporozhye',
'Europe/Zurich', 'Europe/Zurich',
'GMT', 'GMT',
'Indian/Antananarivo', 'Indian/Antananarivo',
@ -1480,7 +1511,6 @@ common_timezones = \
'Pacific/Chuuk', 'Pacific/Chuuk',
'Pacific/Easter', 'Pacific/Easter',
'Pacific/Efate', 'Pacific/Efate',
'Pacific/Enderbury',
'Pacific/Fakaofo', 'Pacific/Fakaofo',
'Pacific/Fiji', 'Pacific/Fiji',
'Pacific/Funafuti', 'Pacific/Funafuti',
@ -1489,7 +1519,7 @@ common_timezones = \
'Pacific/Guadalcanal', 'Pacific/Guadalcanal',
'Pacific/Guam', 'Pacific/Guam',
'Pacific/Honolulu', 'Pacific/Honolulu',
'Pacific/Johnston', 'Pacific/Kanton',
'Pacific/Kiritimati', 'Pacific/Kiritimati',
'Pacific/Kosrae', 'Pacific/Kosrae',
'Pacific/Kwajalein', 'Pacific/Kwajalein',

View file

@ -5,10 +5,14 @@ Custom exceptions raised by pytz.
__all__ = [ __all__ = [
'UnknownTimeZoneError', 'InvalidTimeError', 'AmbiguousTimeError', 'UnknownTimeZoneError', 'InvalidTimeError', 'AmbiguousTimeError',
'NonExistentTimeError', 'NonExistentTimeError',
] ]
class UnknownTimeZoneError(KeyError): class Error(Exception):
'''Base class for all exceptions raised by the pytz library'''
class UnknownTimeZoneError(KeyError, Error):
'''Exception raised when pytz is passed an unknown timezone. '''Exception raised when pytz is passed an unknown timezone.
>>> isinstance(UnknownTimeZoneError(), LookupError) >>> isinstance(UnknownTimeZoneError(), LookupError)
@ -20,11 +24,18 @@ class UnknownTimeZoneError(KeyError):
>>> isinstance(UnknownTimeZoneError(), KeyError) >>> isinstance(UnknownTimeZoneError(), KeyError)
True True
And also a subclass of pytz.exceptions.Error, as are other pytz
exceptions.
>>> isinstance(UnknownTimeZoneError(), Error)
True
''' '''
pass pass
class InvalidTimeError(Exception): class InvalidTimeError(Error):
'''Base class for invalid time exceptions.''' '''Base class for invalid time exceptions.'''

View file

@ -1,14 +1,11 @@
from threading import RLock from threading import RLock
from six import PY2
try: try:
from UserDict import DictMixin
except ImportError:
if PY2:
from collections import Mapping as DictMixin
else:
# noinspection PyCompatibility
from collections.abc import Mapping as DictMixin from collections.abc import Mapping as DictMixin
except ImportError: # Python < 3.3
try:
from UserDict import DictMixin # Python 2
except ImportError: # Python 3.0-3.3
from collections import Mapping as DictMixin
# With lazy loading, we might end up with multiple threads triggering # With lazy loading, we might end up with multiple threads triggering
@ -19,6 +16,7 @@ _fill_lock = RLock()
class LazyDict(DictMixin): class LazyDict(DictMixin):
"""Dictionary populated on first use.""" """Dictionary populated on first use."""
data = None data = None
def __getitem__(self, key): def __getitem__(self, key):
if self.data is None: if self.data is None:
_fill_lock.acquire() _fill_lock.acquire()

View file

@ -5,17 +5,28 @@ Used for testing against as they are only correct for the years
''' '''
from datetime import tzinfo, timedelta, datetime from datetime import tzinfo, timedelta, datetime
from pytz import utc, UTC, HOUR, ZERO from pytz import HOUR, ZERO, UTC
__all__ = [
'FixedOffset',
'LocalTimezone',
'USTimeZone',
'Eastern',
'Central',
'Mountain',
'Pacific',
'UTC'
]
# A class building tzinfo objects for fixed-offset time zones. # A class building tzinfo objects for fixed-offset time zones.
# Note that FixedOffset(0, "UTC") is a different way to build a # Note that FixedOffset(0, "UTC") is a different way to build a
# UTC tzinfo object. # UTC tzinfo object.
class FixedOffset(tzinfo): class FixedOffset(tzinfo):
"""Fixed offset in minutes east from UTC.""" """Fixed offset in minutes east from UTC."""
def __init__(self, offset, name): def __init__(self, offset, name):
self.__offset = timedelta(minutes = offset) self.__offset = timedelta(minutes=offset)
self.__name = name self.__name = name
def utcoffset(self, dt): def utcoffset(self, dt):
@ -27,18 +38,19 @@ class FixedOffset(tzinfo):
def dst(self, dt): def dst(self, dt):
return ZERO return ZERO
# A class capturing the platform's idea of local time.
import time as _time import time as _time
STDOFFSET = timedelta(seconds = -_time.timezone) STDOFFSET = timedelta(seconds=-_time.timezone)
if _time.daylight: if _time.daylight:
DSTOFFSET = timedelta(seconds = -_time.altzone) DSTOFFSET = timedelta(seconds=-_time.altzone)
else: else:
DSTOFFSET = STDOFFSET DSTOFFSET = STDOFFSET
DSTDIFF = DSTOFFSET - STDOFFSET DSTDIFF = DSTOFFSET - STDOFFSET
# A class capturing the platform's idea of local time.
class LocalTimezone(tzinfo): class LocalTimezone(tzinfo):
def utcoffset(self, dt): def utcoffset(self, dt):
@ -66,7 +78,6 @@ class LocalTimezone(tzinfo):
Local = LocalTimezone() Local = LocalTimezone()
# A complete implementation of current DST rules for major US time zones.
def first_sunday_on_or_after(dt): def first_sunday_on_or_after(dt):
days_to_go = 6 - dt.weekday() days_to_go = 6 - dt.weekday()
@ -74,12 +85,15 @@ def first_sunday_on_or_after(dt):
dt += timedelta(days_to_go) dt += timedelta(days_to_go)
return dt return dt
# In the US, DST starts at 2am (standard time) on the first Sunday in April. # In the US, DST starts at 2am (standard time) on the first Sunday in April.
DSTSTART = datetime(1, 4, 1, 2) DSTSTART = datetime(1, 4, 1, 2)
# and ends at 2am (DST time; 1am standard time) on the last Sunday of Oct. # and ends at 2am (DST time; 1am standard time) on the last Sunday of Oct.
# which is the first Sunday on or after Oct 25. # which is the first Sunday on or after Oct 25.
DSTEND = datetime(1, 10, 25, 1) DSTEND = datetime(1, 10, 25, 1)
# A complete implementation of current DST rules for major US time zones.
class USTimeZone(tzinfo): class USTimeZone(tzinfo):
def __init__(self, hours, reprname, stdname, dstname): def __init__(self, hours, reprname, stdname, dstname):
@ -124,4 +138,3 @@ Eastern = USTimeZone(-5, "Eastern", "EST", "EDT")
Central = USTimeZone(-6, "Central", "CST", "CDT") Central = USTimeZone(-6, "Central", "CST", "CDT")
Mountain = USTimeZone(-7, "Mountain", "MST", "MDT") Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
Pacific = USTimeZone(-8, "Pacific", "PST", "PDT") Pacific = USTimeZone(-8, "Pacific", "PST", "PDT")

View file

@ -1,34 +0,0 @@
# -*- coding: ascii -*-
from doctest import DocFileSuite
import unittest, os.path, sys
THIS_DIR = os.path.dirname(__file__)
README = os.path.join(THIS_DIR, os.pardir, os.pardir, 'README.txt')
class DocumentationTestCase(unittest.TestCase):
def test_readme_encoding(self):
'''Confirm the README.txt is pure ASCII.'''
f = open(README, 'rb')
try:
f.read().decode('ASCII')
finally:
f.close()
def test_suite():
"For the Z3 test runner"
return unittest.TestSuite((
DocumentationTestCase('test_readme_encoding'),
DocFileSuite(os.path.join(os.pardir, os.pardir, 'README.txt'))))
if __name__ == '__main__':
sys.path.insert(0, os.path.abspath(os.path.join(
THIS_DIR, os.pardir, os.pardir
)))
unittest.main(defaultTest='test_suite')

View file

@ -1,313 +0,0 @@
from operator import *
import os.path
import sys
import unittest
import warnings
if __name__ == '__main__':
# Only munge path if invoked as a script. Testrunners should have setup
# the paths already
sys.path.insert(0, os.path.abspath(os.path.join(os.pardir, os.pardir)))
from pytz.lazy import LazyList, LazySet
class LazyListTestCase(unittest.TestCase):
initial_data = [3,2,1]
def setUp(self):
self.base = [3, 2, 1]
self.lesser = [2, 1, 0]
self.greater = [4, 3, 2]
self.lazy = LazyList(iter(list(self.base)))
def test_unary_ops(self):
unary_ops = [str, repr, len, bool, not_]
try:
unary_ops.append(unicode)
except NameError:
pass # unicode no longer exists in Python 3.
for op in unary_ops:
self.assertEqual(
op(self.lazy),
op(self.base), str(op))
def test_binary_ops(self):
binary_ops = [eq, ge, gt, le, lt, ne, add, concat]
try:
binary_ops.append(cmp)
except NameError:
pass # cmp no longer exists in Python 3.
for op in binary_ops:
self.assertEqual(
op(self.lazy, self.lazy),
op(self.base, self.base), str(op))
for other in [self.base, self.lesser, self.greater]:
self.assertEqual(
op(self.lazy, other),
op(self.base, other), '%s %s' % (op, other))
self.assertEqual(
op(other, self.lazy),
op(other, self.base), '%s %s' % (op, other))
# Multiplication
self.assertEqual(self.lazy * 3, self.base * 3)
self.assertEqual(3 * self.lazy, 3 * self.base)
# Contains
self.assertTrue(2 in self.lazy)
self.assertFalse(42 in self.lazy)
def test_iadd(self):
self.lazy += [1]
self.base += [1]
self.assertEqual(self.lazy, self.base)
def test_bool(self):
self.assertTrue(bool(self.lazy))
self.assertFalse(bool(LazyList()))
self.assertFalse(bool(LazyList(iter([]))))
def test_hash(self):
self.assertRaises(TypeError, hash, self.lazy)
def test_isinstance(self):
self.assertTrue(isinstance(self.lazy, list))
self.assertFalse(isinstance(self.lazy, tuple))
def test_callable(self):
try:
callable
except NameError:
return # No longer exists with Python 3.
self.assertFalse(callable(self.lazy))
def test_append(self):
self.base.append('extra')
self.lazy.append('extra')
self.assertEqual(self.lazy, self.base)
def test_count(self):
self.assertEqual(self.lazy.count(2), 1)
def test_index(self):
self.assertEqual(self.lazy.index(2), 1)
def test_extend(self):
self.base.extend([6, 7])
self.lazy.extend([6, 7])
self.assertEqual(self.lazy, self.base)
def test_insert(self):
self.base.insert(0, 'ping')
self.lazy.insert(0, 'ping')
self.assertEqual(self.lazy, self.base)
def test_pop(self):
self.assertEqual(self.lazy.pop(), self.base.pop())
self.assertEqual(self.lazy, self.base)
def test_remove(self):
self.base.remove(2)
self.lazy.remove(2)
self.assertEqual(self.lazy, self.base)
def test_reverse(self):
self.base.reverse()
self.lazy.reverse()
self.assertEqual(self.lazy, self.base)
def test_reversed(self):
self.assertEqual(list(reversed(self.lazy)), list(reversed(self.base)))
def test_sort(self):
self.base.sort()
self.assertNotEqual(self.lazy, self.base, 'Test data already sorted')
self.lazy.sort()
self.assertEqual(self.lazy, self.base)
def test_sorted(self):
self.assertEqual(sorted(self.lazy), sorted(self.base))
def test_getitem(self):
for idx in range(-len(self.base), len(self.base)):
self.assertEqual(self.lazy[idx], self.base[idx])
def test_setitem(self):
for idx in range(-len(self.base), len(self.base)):
self.base[idx] = idx + 1000
self.assertNotEqual(self.lazy, self.base)
self.lazy[idx] = idx + 1000
self.assertEqual(self.lazy, self.base)
def test_delitem(self):
del self.base[0]
self.assertNotEqual(self.lazy, self.base)
del self.lazy[0]
self.assertEqual(self.lazy, self.base)
del self.base[-2]
self.assertNotEqual(self.lazy, self.base)
del self.lazy[-2]
self.assertEqual(self.lazy, self.base)
def test_iter(self):
self.assertEqual(list(iter(self.lazy)), list(iter(self.base)))
def test_getslice(self):
for i in range(-len(self.base), len(self.base)):
for j in range(-len(self.base), len(self.base)):
for step in [-1, 1]:
self.assertEqual(self.lazy[i:j:step], self.base[i:j:step])
def test_setslice(self):
for i in range(-len(self.base), len(self.base)):
for j in range(-len(self.base), len(self.base)):
for step in [-1, 1]:
replacement = range(0, len(self.base[i:j:step]))
self.base[i:j:step] = replacement
self.lazy[i:j:step] = replacement
self.assertEqual(self.lazy, self.base)
def test_delslice(self):
del self.base[0:1]
del self.lazy[0:1]
self.assertEqual(self.lazy, self.base)
del self.base[-1:1:-1]
del self.lazy[-1:1:-1]
self.assertEqual(self.lazy, self.base)
class LazySetTestCase(unittest.TestCase):
initial_data = set([3,2,1])
def setUp(self):
self.base = set([3, 2, 1])
self.lazy = LazySet(iter(set(self.base)))
def test_unary_ops(self):
# These ops just need to work.
unary_ops = [str, repr]
try:
unary_ops.append(unicode)
except NameError:
pass # unicode no longer exists in Python 3.
for op in unary_ops:
op(self.lazy) # These ops just need to work.
# These ops should return identical values as a real set.
unary_ops = [len, bool, not_]
for op in unary_ops:
self.assertEqual(
op(self.lazy),
op(self.base), '%s(lazy) == %r' % (op, op(self.lazy)))
def test_binary_ops(self):
binary_ops = [eq, ge, gt, le, lt, ne, sub, and_, or_, xor]
try:
binary_ops.append(cmp)
except NameError:
pass # cmp no longer exists in Python 3.
for op in binary_ops:
self.assertEqual(
op(self.lazy, self.lazy),
op(self.base, self.base), str(op))
self.assertEqual(
op(self.lazy, self.base),
op(self.base, self.base), str(op))
self.assertEqual(
op(self.base, self.lazy),
op(self.base, self.base), str(op))
# Contains
self.assertTrue(2 in self.lazy)
self.assertFalse(42 in self.lazy)
def test_iops(self):
try:
iops = [isub, iand, ior, ixor]
except NameError:
return # Don't exist in older Python versions.
for op in iops:
# Mutating operators, so make fresh copies.
lazy = LazySet(self.base)
base = self.base.copy()
op(lazy, set([1]))
op(base, set([1]))
self.assertEqual(lazy, base, str(op))
def test_bool(self):
self.assertTrue(bool(self.lazy))
self.assertFalse(bool(LazySet()))
self.assertFalse(bool(LazySet(iter([]))))
def test_hash(self):
self.assertRaises(TypeError, hash, self.lazy)
def test_isinstance(self):
self.assertTrue(isinstance(self.lazy, set))
def test_callable(self):
try:
callable
except NameError:
return # No longer exists with Python 3.
self.assertFalse(callable(self.lazy))
def test_add(self):
self.base.add('extra')
self.lazy.add('extra')
self.assertEqual(self.lazy, self.base)
def test_copy(self):
self.assertEqual(self.lazy.copy(), self.base)
def test_method_ops(self):
ops = [
'difference', 'intersection', 'isdisjoint',
'issubset', 'issuperset', 'symmetric_difference', 'union',
'difference_update', 'intersection_update',
'symmetric_difference_update', 'update']
for op in ops:
if not hasattr(set, op):
continue # Not in this version of Python.
# Make a copy, as some of the ops are mutating.
lazy = LazySet(set(self.base))
base = set(self.base)
self.assertEqual(
getattr(self.lazy, op)(set([1])),
getattr(self.base, op)(set([1])), op)
self.assertEqual(self.lazy, self.base, op)
def test_discard(self):
self.base.discard(1)
self.assertNotEqual(self.lazy, self.base)
self.lazy.discard(1)
self.assertEqual(self.lazy, self.base)
def test_pop(self):
self.assertEqual(self.lazy.pop(), self.base.pop())
self.assertEqual(self.lazy, self.base)
def test_remove(self):
self.base.remove(2)
self.lazy.remove(2)
self.assertEqual(self.lazy, self.base)
def test_clear(self):
self.lazy.clear()
self.assertEqual(self.lazy, set())
if __name__ == '__main__':
warnings.simplefilter("error") # Warnings should be fatal in tests.
unittest.main()

View file

@ -1,843 +0,0 @@
# -*- coding: ascii -*-
import sys, os, os.path
import unittest, doctest
try:
import cPickle as pickle
except ImportError:
import pickle
from datetime import datetime, time, timedelta, tzinfo
import warnings
if __name__ == '__main__':
# Only munge path if invoked as a script. Testrunners should have setup
# the paths already
sys.path.insert(0, os.path.abspath(os.path.join(os.pardir, os.pardir)))
import pytz
from pytz import reference
from pytz.tzfile import _byte_string
from pytz.tzinfo import DstTzInfo, StaticTzInfo
# I test for expected version to ensure the correct version of pytz is
# actually being tested.
EXPECTED_VERSION='2016.6.1'
EXPECTED_OLSON_VERSION='2016f'
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
NOTIME = timedelta(0)
# GMT is a tzinfo.StaticTzInfo--the class we primarily want to test--while
# UTC is reference implementation. They both have the same timezone meaning.
UTC = pytz.timezone('UTC')
GMT = pytz.timezone('GMT')
assert isinstance(GMT, StaticTzInfo), 'GMT is no longer a StaticTzInfo'
def prettydt(dt):
"""datetime as a string using a known format.
We don't use strftime as it doesn't handle years earlier than 1900
per http://bugs.python.org/issue1777412
"""
if dt.utcoffset() >= timedelta(0):
offset = '+%s' % (dt.utcoffset(),)
else:
offset = '-%s' % (-1 * dt.utcoffset(),)
return '%04d-%02d-%02d %02d:%02d:%02d %s %s' % (
dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second,
dt.tzname(), offset)
try:
unicode
except NameError:
# Python 3.x doesn't have unicode(), making writing code
# for Python 2.3 and Python 3.x a pain.
unicode = str
class BasicTest(unittest.TestCase):
def testVersion(self):
# Ensuring the correct version of pytz has been loaded
self.assertEqual(EXPECTED_VERSION, pytz.__version__,
'Incorrect pytz version loaded. Import path is stuffed '
'or this test needs updating. (Wanted %s, got %s)'
% (EXPECTED_VERSION, pytz.__version__))
self.assertEqual(EXPECTED_OLSON_VERSION, pytz.OLSON_VERSION,
'Incorrect pytz version loaded. Import path is stuffed '
'or this test needs updating. (Wanted %s, got %s)'
% (EXPECTED_OLSON_VERSION, pytz.OLSON_VERSION))
def testGMT(self):
now = datetime.now(tz=GMT)
self.assertTrue(now.utcoffset() == NOTIME)
self.assertTrue(now.dst() == NOTIME)
self.assertTrue(now.timetuple() == now.utctimetuple())
self.assertTrue(now==now.replace(tzinfo=UTC))
def testReferenceUTC(self):
now = datetime.now(tz=UTC)
self.assertTrue(now.utcoffset() == NOTIME)
self.assertTrue(now.dst() == NOTIME)
self.assertTrue(now.timetuple() == now.utctimetuple())
def testUnknownOffsets(self):
# This tzinfo behavior is required to make
# datetime.time.{utcoffset, dst, tzname} work as documented.
dst_tz = pytz.timezone('US/Eastern')
# This information is not known when we don't have a date,
# so return None per API.
self.assertTrue(dst_tz.utcoffset(None) is None)
self.assertTrue(dst_tz.dst(None) is None)
# We don't know the abbreviation, but this is still a valid
# tzname per the Python documentation.
self.assertEqual(dst_tz.tzname(None), 'US/Eastern')
def clearCache(self):
pytz._tzinfo_cache.clear()
def testUnicodeTimezone(self):
# We need to ensure that cold lookups work for both Unicode
# and traditional strings, and that the desired singleton is
# returned.
self.clearCache()
eastern = pytz.timezone(unicode('US/Eastern'))
self.assertTrue(eastern is pytz.timezone('US/Eastern'))
self.clearCache()
eastern = pytz.timezone('US/Eastern')
self.assertTrue(eastern is pytz.timezone(unicode('US/Eastern')))
def testStaticTzInfo(self):
# Ensure that static timezones are correctly detected,
# per lp:1602807
static = pytz.timezone('Etc/GMT-4')
self.assertTrue(isinstance(static, StaticTzInfo))
class PicklingTest(unittest.TestCase):
def _roundtrip_tzinfo(self, tz):
p = pickle.dumps(tz)
unpickled_tz = pickle.loads(p)
self.assertTrue(tz is unpickled_tz, '%s did not roundtrip' % tz.zone)
def _roundtrip_datetime(self, dt):
# Ensure that the tzinfo attached to a datetime instance
# is identical to the one returned. This is important for
# DST timezones, as some state is stored in the tzinfo.
tz = dt.tzinfo
p = pickle.dumps(dt)
unpickled_dt = pickle.loads(p)
unpickled_tz = unpickled_dt.tzinfo
self.assertTrue(tz is unpickled_tz, '%s did not roundtrip' % tz.zone)
def testDst(self):
tz = pytz.timezone('Europe/Amsterdam')
dt = datetime(2004, 2, 1, 0, 0, 0)
for localized_tz in tz._tzinfos.values():
self._roundtrip_tzinfo(localized_tz)
self._roundtrip_datetime(dt.replace(tzinfo=localized_tz))
def testRoundtrip(self):
dt = datetime(2004, 2, 1, 0, 0, 0)
for zone in pytz.all_timezones:
tz = pytz.timezone(zone)
self._roundtrip_tzinfo(tz)
def testDatabaseFixes(self):
# Hack the pickle to make it refer to a timezone abbreviation
# that does not match anything. The unpickler should be able
# to repair this case
tz = pytz.timezone('Australia/Melbourne')
p = pickle.dumps(tz)
tzname = tz._tzname
hacked_p = p.replace(_byte_string(tzname),
_byte_string('?'*len(tzname)))
self.assertNotEqual(p, hacked_p)
unpickled_tz = pickle.loads(hacked_p)
self.assertTrue(tz is unpickled_tz)
# Simulate a database correction. In this case, the incorrect
# data will continue to be used.
p = pickle.dumps(tz)
new_utcoffset = tz._utcoffset.seconds + 42
# Python 3 introduced a new pickle protocol where numbers are stored in
# hexadecimal representation. Here we extract the pickle
# representation of the number for the current Python version.
old_pickle_pattern = pickle.dumps(tz._utcoffset.seconds)[3:-1]
new_pickle_pattern = pickle.dumps(new_utcoffset)[3:-1]
hacked_p = p.replace(old_pickle_pattern, new_pickle_pattern)
self.assertNotEqual(p, hacked_p)
unpickled_tz = pickle.loads(hacked_p)
self.assertEqual(unpickled_tz._utcoffset.seconds, new_utcoffset)
self.assertTrue(tz is not unpickled_tz)
def testOldPickles(self):
# Ensure that applications serializing pytz instances as pickles
# have no troubles upgrading to a new pytz release. These pickles
# where created with pytz2006j
east1 = pickle.loads(_byte_string(
"cpytz\n_p\np1\n(S'US/Eastern'\np2\nI-18000\n"
"I0\nS'EST'\np3\ntRp4\n."
))
east2 = pytz.timezone('US/Eastern').localize(
datetime(2006, 1, 1)).tzinfo
self.assertTrue(east1 is east2)
# Confirm changes in name munging between 2006j and 2007c cause
# no problems.
pap1 = pickle.loads(_byte_string(
"cpytz\n_p\np1\n(S'America/Port_minus_au_minus_Prince'"
"\np2\nI-17340\nI0\nS'PPMT'\np3\ntRp4\n."))
pap2 = pytz.timezone('America/Port-au-Prince').localize(
datetime(1910, 1, 1)).tzinfo
self.assertTrue(pap1 is pap2)
gmt1 = pickle.loads(_byte_string(
"cpytz\n_p\np1\n(S'Etc/GMT_plus_10'\np2\ntRp3\n."))
gmt2 = pytz.timezone('Etc/GMT+10')
self.assertTrue(gmt1 is gmt2)
class USEasternDSTStartTestCase(unittest.TestCase):
tzinfo = pytz.timezone('US/Eastern')
# 24 hours before DST changeover
transition_time = datetime(2002, 4, 7, 7, 0, 0, tzinfo=UTC)
# Increase for 'flexible' DST transitions due to 1 minute granularity
# of Python's datetime library
instant = timedelta(seconds=1)
# before transition
before = {
'tzname': 'EST',
'utcoffset': timedelta(hours = -5),
'dst': timedelta(hours = 0),
}
# after transition
after = {
'tzname': 'EDT',
'utcoffset': timedelta(hours = -4),
'dst': timedelta(hours = 1),
}
def _test_tzname(self, utc_dt, wanted):
tzname = wanted['tzname']
dt = utc_dt.astimezone(self.tzinfo)
self.assertEqual(dt.tzname(), tzname,
'Expected %s as tzname for %s. Got %s' % (
tzname, str(utc_dt), dt.tzname()
)
)
def _test_utcoffset(self, utc_dt, wanted):
utcoffset = wanted['utcoffset']
dt = utc_dt.astimezone(self.tzinfo)
self.assertEqual(
dt.utcoffset(), wanted['utcoffset'],
'Expected %s as utcoffset for %s. Got %s' % (
utcoffset, utc_dt, dt.utcoffset()
)
)
def _test_dst(self, utc_dt, wanted):
dst = wanted['dst']
dt = utc_dt.astimezone(self.tzinfo)
self.assertEqual(dt.dst(),dst,
'Expected %s as dst for %s. Got %s' % (
dst, utc_dt, dt.dst()
)
)
def test_arithmetic(self):
utc_dt = self.transition_time
for days in range(-420, 720, 20):
delta = timedelta(days=days)
# Make sure we can get back where we started
dt = utc_dt.astimezone(self.tzinfo)
dt2 = dt + delta
dt2 = dt2 - delta
self.assertEqual(dt, dt2)
# Make sure arithmetic crossing DST boundaries ends
# up in the correct timezone after normalization
utc_plus_delta = (utc_dt + delta).astimezone(self.tzinfo)
local_plus_delta = self.tzinfo.normalize(dt + delta)
self.assertEqual(
prettydt(utc_plus_delta),
prettydt(local_plus_delta),
'Incorrect result for delta==%d days. Wanted %r. Got %r'%(
days,
prettydt(utc_plus_delta),
prettydt(local_plus_delta),
)
)
def _test_all(self, utc_dt, wanted):
self._test_utcoffset(utc_dt, wanted)
self._test_tzname(utc_dt, wanted)
self._test_dst(utc_dt, wanted)
def testDayBefore(self):
self._test_all(
self.transition_time - timedelta(days=1), self.before
)
def testTwoHoursBefore(self):
self._test_all(
self.transition_time - timedelta(hours=2), self.before
)
def testHourBefore(self):
self._test_all(
self.transition_time - timedelta(hours=1), self.before
)
def testInstantBefore(self):
self._test_all(
self.transition_time - self.instant, self.before
)
def testTransition(self):
self._test_all(
self.transition_time, self.after
)
def testInstantAfter(self):
self._test_all(
self.transition_time + self.instant, self.after
)
def testHourAfter(self):
self._test_all(
self.transition_time + timedelta(hours=1), self.after
)
def testTwoHoursAfter(self):
self._test_all(
self.transition_time + timedelta(hours=1), self.after
)
def testDayAfter(self):
self._test_all(
self.transition_time + timedelta(days=1), self.after
)
class USEasternDSTEndTestCase(USEasternDSTStartTestCase):
tzinfo = pytz.timezone('US/Eastern')
transition_time = datetime(2002, 10, 27, 6, 0, 0, tzinfo=UTC)
before = {
'tzname': 'EDT',
'utcoffset': timedelta(hours = -4),
'dst': timedelta(hours = 1),
}
after = {
'tzname': 'EST',
'utcoffset': timedelta(hours = -5),
'dst': timedelta(hours = 0),
}
class USEasternEPTStartTestCase(USEasternDSTStartTestCase):
transition_time = datetime(1945, 8, 14, 23, 0, 0, tzinfo=UTC)
before = {
'tzname': 'EWT',
'utcoffset': timedelta(hours = -4),
'dst': timedelta(hours = 1),
}
after = {
'tzname': 'EPT',
'utcoffset': timedelta(hours = -4),
'dst': timedelta(hours = 1),
}
class USEasternEPTEndTestCase(USEasternDSTStartTestCase):
transition_time = datetime(1945, 9, 30, 6, 0, 0, tzinfo=UTC)
before = {
'tzname': 'EPT',
'utcoffset': timedelta(hours = -4),
'dst': timedelta(hours = 1),
}
after = {
'tzname': 'EST',
'utcoffset': timedelta(hours = -5),
'dst': timedelta(hours = 0),
}
class WarsawWMTEndTestCase(USEasternDSTStartTestCase):
# In 1915, Warsaw changed from Warsaw to Central European time.
# This involved the clocks being set backwards, causing a end-of-DST
# like situation without DST being involved.
tzinfo = pytz.timezone('Europe/Warsaw')
transition_time = datetime(1915, 8, 4, 22, 36, 0, tzinfo=UTC)
before = {
'tzname': 'WMT',
'utcoffset': timedelta(hours=1, minutes=24),
'dst': timedelta(0),
}
after = {
'tzname': 'CET',
'utcoffset': timedelta(hours=1),
'dst': timedelta(0),
}
class VilniusWMTEndTestCase(USEasternDSTStartTestCase):
# At the end of 1916, Vilnius changed timezones putting its clock
# forward by 11 minutes 35 seconds. Neither timezone was in DST mode.
tzinfo = pytz.timezone('Europe/Vilnius')
instant = timedelta(seconds=31)
transition_time = datetime(1916, 12, 31, 22, 36, 00, tzinfo=UTC)
before = {
'tzname': 'WMT',
'utcoffset': timedelta(hours=1, minutes=24),
'dst': timedelta(0),
}
after = {
'tzname': 'KMT',
'utcoffset': timedelta(hours=1, minutes=36), # Really 1:35:36
'dst': timedelta(0),
}
class VilniusCESTStartTestCase(USEasternDSTStartTestCase):
# In 1941, Vilnius changed from MSG to CEST, switching to summer
# time while simultaneously reducing its UTC offset by two hours,
# causing the clocks to go backwards for this summer time
# switchover.
tzinfo = pytz.timezone('Europe/Vilnius')
transition_time = datetime(1941, 6, 23, 21, 00, 00, tzinfo=UTC)
before = {
'tzname': 'MSK',
'utcoffset': timedelta(hours=3),
'dst': timedelta(0),
}
after = {
'tzname': 'CEST',
'utcoffset': timedelta(hours=2),
'dst': timedelta(hours=1),
}
class LondonHistoryStartTestCase(USEasternDSTStartTestCase):
# The first known timezone transition in London was in 1847 when
# clocks where synchronized to GMT. However, we currently only
# understand v1 format tzfile(5) files which does handle years
# this far in the past, so our earliest known transition is in
# 1916.
tzinfo = pytz.timezone('Europe/London')
# transition_time = datetime(1847, 12, 1, 1, 15, 00, tzinfo=UTC)
# before = {
# 'tzname': 'LMT',
# 'utcoffset': timedelta(minutes=-75),
# 'dst': timedelta(0),
# }
# after = {
# 'tzname': 'GMT',
# 'utcoffset': timedelta(0),
# 'dst': timedelta(0),
# }
transition_time = datetime(1916, 5, 21, 2, 00, 00, tzinfo=UTC)
before = {
'tzname': 'GMT',
'utcoffset': timedelta(0),
'dst': timedelta(0),
}
after = {
'tzname': 'BST',
'utcoffset': timedelta(hours=1),
'dst': timedelta(hours=1),
}
class LondonHistoryEndTestCase(USEasternDSTStartTestCase):
# Timezone switchovers are projected into the future, even
# though no official statements exist or could be believed even
# if they did exist. We currently only check the last known
# transition in 2037, as we are still using v1 format tzfile(5)
# files.
tzinfo = pytz.timezone('Europe/London')
# transition_time = datetime(2499, 10, 25, 1, 0, 0, tzinfo=UTC)
transition_time = datetime(2037, 10, 25, 1, 0, 0, tzinfo=UTC)
before = {
'tzname': 'BST',
'utcoffset': timedelta(hours=1),
'dst': timedelta(hours=1),
}
after = {
'tzname': 'GMT',
'utcoffset': timedelta(0),
'dst': timedelta(0),
}
class NoumeaHistoryStartTestCase(USEasternDSTStartTestCase):
# Noumea adopted a whole hour offset in 1912. Previously
# it was 11 hours, 5 minutes and 48 seconds off UTC. However,
# due to limitations of the Python datetime library, we need
# to round that to 11 hours 6 minutes.
tzinfo = pytz.timezone('Pacific/Noumea')
transition_time = datetime(1912, 1, 12, 12, 54, 12, tzinfo=UTC)
before = {
'tzname': 'LMT',
'utcoffset': timedelta(hours=11, minutes=6),
'dst': timedelta(0),
}
after = {
'tzname': 'NCT',
'utcoffset': timedelta(hours=11),
'dst': timedelta(0),
}
class NoumeaDSTEndTestCase(USEasternDSTStartTestCase):
# Noumea dropped DST in 1997.
tzinfo = pytz.timezone('Pacific/Noumea')
transition_time = datetime(1997, 3, 1, 15, 00, 00, tzinfo=UTC)
before = {
'tzname': 'NCST',
'utcoffset': timedelta(hours=12),
'dst': timedelta(hours=1),
}
after = {
'tzname': 'NCT',
'utcoffset': timedelta(hours=11),
'dst': timedelta(0),
}
class NoumeaNoMoreDSTTestCase(NoumeaDSTEndTestCase):
# Noumea dropped DST in 1997. Here we test that it stops occuring.
transition_time = (
NoumeaDSTEndTestCase.transition_time + timedelta(days=365*10))
before = NoumeaDSTEndTestCase.after
after = NoumeaDSTEndTestCase.after
class TahitiTestCase(USEasternDSTStartTestCase):
# Tahiti has had a single transition in its history.
tzinfo = pytz.timezone('Pacific/Tahiti')
transition_time = datetime(1912, 10, 1, 9, 58, 16, tzinfo=UTC)
before = {
'tzname': 'LMT',
'utcoffset': timedelta(hours=-9, minutes=-58),
'dst': timedelta(0),
}
after = {
'tzname': 'TAHT',
'utcoffset': timedelta(hours=-10),
'dst': timedelta(0),
}
class SamoaInternationalDateLineChange(USEasternDSTStartTestCase):
# At the end of 2011, Samoa will switch from being east of the
# international dateline to the west. There will be no Dec 30th
# 2011 and it will switch from UTC-10 to UTC+14.
tzinfo = pytz.timezone('Pacific/Apia')
transition_time = datetime(2011, 12, 30, 10, 0, 0, tzinfo=UTC)
before = {
'tzname': 'SDT',
'utcoffset': timedelta(hours=-10),
'dst': timedelta(hours=1),
}
after = {
'tzname': 'WSDT',
'utcoffset': timedelta(hours=14),
'dst': timedelta(hours=1),
}
class ReferenceUSEasternDSTStartTestCase(USEasternDSTStartTestCase):
tzinfo = reference.Eastern
def test_arithmetic(self):
# Reference implementation cannot handle this
pass
class ReferenceUSEasternDSTEndTestCase(USEasternDSTEndTestCase):
tzinfo = reference.Eastern
def testHourBefore(self):
# Python's datetime library has a bug, where the hour before
# a daylight saving transition is one hour out. For example,
# at the end of US/Eastern daylight saving time, 01:00 EST
# occurs twice (once at 05:00 UTC and once at 06:00 UTC),
# whereas the first should actually be 01:00 EDT.
# Note that this bug is by design - by accepting this ambiguity
# for one hour one hour per year, an is_dst flag on datetime.time
# became unnecessary.
self._test_all(
self.transition_time - timedelta(hours=1), self.after
)
def testInstantBefore(self):
self._test_all(
self.transition_time - timedelta(seconds=1), self.after
)
def test_arithmetic(self):
# Reference implementation cannot handle this
pass
class LocalTestCase(unittest.TestCase):
def testLocalize(self):
loc_tz = pytz.timezone('Europe/Amsterdam')
loc_time = loc_tz.localize(datetime(1930, 5, 10, 0, 0, 0))
# Actually +00:19:32, but Python datetime rounds this
self.assertEqual(loc_time.strftime('%Z%z'), 'AMT+0020')
loc_time = loc_tz.localize(datetime(1930, 5, 20, 0, 0, 0))
# Actually +00:19:32, but Python datetime rounds this
self.assertEqual(loc_time.strftime('%Z%z'), 'NST+0120')
loc_time = loc_tz.localize(datetime(1940, 5, 10, 0, 0, 0))
self.assertEqual(loc_time.strftime('%Z%z'), 'NET+0020')
loc_time = loc_tz.localize(datetime(1940, 5, 20, 0, 0, 0))
self.assertEqual(loc_time.strftime('%Z%z'), 'CEST+0200')
loc_time = loc_tz.localize(datetime(2004, 2, 1, 0, 0, 0))
self.assertEqual(loc_time.strftime('%Z%z'), 'CET+0100')
loc_time = loc_tz.localize(datetime(2004, 4, 1, 0, 0, 0))
self.assertEqual(loc_time.strftime('%Z%z'), 'CEST+0200')
tz = pytz.timezone('Europe/Amsterdam')
loc_time = loc_tz.localize(datetime(1943, 3, 29, 1, 59, 59))
self.assertEqual(loc_time.strftime('%Z%z'), 'CET+0100')
# Switch to US
loc_tz = pytz.timezone('US/Eastern')
# End of DST ambiguity check
loc_time = loc_tz.localize(datetime(1918, 10, 27, 1, 59, 59), is_dst=1)
self.assertEqual(loc_time.strftime('%Z%z'), 'EDT-0400')
loc_time = loc_tz.localize(datetime(1918, 10, 27, 1, 59, 59), is_dst=0)
self.assertEqual(loc_time.strftime('%Z%z'), 'EST-0500')
self.assertRaises(pytz.AmbiguousTimeError,
loc_tz.localize, datetime(1918, 10, 27, 1, 59, 59), is_dst=None
)
# Start of DST non-existent times
loc_time = loc_tz.localize(datetime(1918, 3, 31, 2, 0, 0), is_dst=0)
self.assertEqual(loc_time.strftime('%Z%z'), 'EST-0500')
loc_time = loc_tz.localize(datetime(1918, 3, 31, 2, 0, 0), is_dst=1)
self.assertEqual(loc_time.strftime('%Z%z'), 'EDT-0400')
self.assertRaises(pytz.NonExistentTimeError,
loc_tz.localize, datetime(1918, 3, 31, 2, 0, 0), is_dst=None
)
# Weird changes - war time and peace time both is_dst==True
loc_time = loc_tz.localize(datetime(1942, 2, 9, 3, 0, 0))
self.assertEqual(loc_time.strftime('%Z%z'), 'EWT-0400')
loc_time = loc_tz.localize(datetime(1945, 8, 14, 19, 0, 0))
self.assertEqual(loc_time.strftime('%Z%z'), 'EPT-0400')
loc_time = loc_tz.localize(datetime(1945, 9, 30, 1, 0, 0), is_dst=1)
self.assertEqual(loc_time.strftime('%Z%z'), 'EPT-0400')
loc_time = loc_tz.localize(datetime(1945, 9, 30, 1, 0, 0), is_dst=0)
self.assertEqual(loc_time.strftime('%Z%z'), 'EST-0500')
# Weird changes - ambiguous time (end-of-DST like) but is_dst==False
for zonename, ambiguous_naive, expected in [
('Europe/Warsaw', datetime(1915, 8, 4, 23, 59, 59),
['1915-08-04 23:59:59 WMT+0124',
'1915-08-04 23:59:59 CET+0100']),
('Europe/Moscow', datetime(2014, 10, 26, 1, 30),
['2014-10-26 01:30:00 MSK+0400',
'2014-10-26 01:30:00 MSK+0300'])]:
loc_tz = pytz.timezone(zonename)
self.assertRaises(pytz.AmbiguousTimeError,
loc_tz.localize, ambiguous_naive, is_dst=None
)
# Also test non-boolean is_dst in the weird case
for dst in [True, timedelta(1), False, timedelta(0)]:
loc_time = loc_tz.localize(ambiguous_naive, is_dst=dst)
self.assertEqual(loc_time.strftime(fmt), expected[not dst])
def testNormalize(self):
tz = pytz.timezone('US/Eastern')
dt = datetime(2004, 4, 4, 7, 0, 0, tzinfo=UTC).astimezone(tz)
dt2 = dt - timedelta(minutes=10)
self.assertEqual(
dt2.strftime('%Y-%m-%d %H:%M:%S %Z%z'),
'2004-04-04 02:50:00 EDT-0400'
)
dt2 = tz.normalize(dt2)
self.assertEqual(
dt2.strftime('%Y-%m-%d %H:%M:%S %Z%z'),
'2004-04-04 01:50:00 EST-0500'
)
def testPartialMinuteOffsets(self):
# utcoffset in Amsterdam was not a whole minute until 1937
# However, we fudge this by rounding them, as the Python
# datetime library
tz = pytz.timezone('Europe/Amsterdam')
utc_dt = datetime(1914, 1, 1, 13, 40, 28, tzinfo=UTC) # correct
utc_dt = utc_dt.replace(second=0) # But we need to fudge it
loc_dt = utc_dt.astimezone(tz)
self.assertEqual(
loc_dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'),
'1914-01-01 14:00:00 AMT+0020'
)
# And get back...
utc_dt = loc_dt.astimezone(UTC)
self.assertEqual(
utc_dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'),
'1914-01-01 13:40:00 UTC+0000'
)
def no_testCreateLocaltime(self):
# It would be nice if this worked, but it doesn't.
tz = pytz.timezone('Europe/Amsterdam')
dt = datetime(2004, 10, 31, 2, 0, 0, tzinfo=tz)
self.assertEqual(
dt.strftime(fmt),
'2004-10-31 02:00:00 CET+0100'
)
class CommonTimezonesTestCase(unittest.TestCase):
def test_bratislava(self):
# Bratislava is the default timezone for Slovakia, but our
# heuristics where not adding it to common_timezones. Ideally,
# common_timezones should be populated from zone.tab at runtime,
# but I'm hesitant to pay the startup cost as loading the list
# on demand whilst remaining backwards compatible seems
# difficult.
self.assertTrue('Europe/Bratislava' in pytz.common_timezones)
self.assertTrue('Europe/Bratislava' in pytz.common_timezones_set)
def test_us_eastern(self):
self.assertTrue('US/Eastern' in pytz.common_timezones)
self.assertTrue('US/Eastern' in pytz.common_timezones_set)
def test_belfast(self):
# Belfast uses London time.
self.assertTrue('Europe/Belfast' in pytz.all_timezones_set)
self.assertFalse('Europe/Belfast' in pytz.common_timezones)
self.assertFalse('Europe/Belfast' in pytz.common_timezones_set)
class BaseTzInfoTestCase:
'''Ensure UTC, StaticTzInfo and DstTzInfo work consistently.
These tests are run for each type of tzinfo.
'''
tz = None # override
tz_class = None # override
def test_expectedclass(self):
self.assertTrue(isinstance(self.tz, self.tz_class))
def test_fromutc(self):
# naive datetime.
dt1 = datetime(2011, 10, 31)
# localized datetime, same timezone.
dt2 = self.tz.localize(dt1)
# Both should give the same results. Note that the standard
# Python tzinfo.fromutc() only supports the second.
for dt in [dt1, dt2]:
loc_dt = self.tz.fromutc(dt)
loc_dt2 = pytz.utc.localize(dt1).astimezone(self.tz)
self.assertEqual(loc_dt, loc_dt2)
# localized datetime, different timezone.
new_tz = pytz.timezone('Europe/Paris')
self.assertTrue(self.tz is not new_tz)
dt3 = new_tz.localize(dt1)
self.assertRaises(ValueError, self.tz.fromutc, dt3)
def test_normalize(self):
other_tz = pytz.timezone('Europe/Paris')
self.assertTrue(self.tz is not other_tz)
dt = datetime(2012, 3, 26, 12, 0)
other_dt = other_tz.localize(dt)
local_dt = self.tz.normalize(other_dt)
self.assertTrue(local_dt.tzinfo is not other_dt.tzinfo)
self.assertNotEqual(
local_dt.replace(tzinfo=None), other_dt.replace(tzinfo=None))
def test_astimezone(self):
other_tz = pytz.timezone('Europe/Paris')
self.assertTrue(self.tz is not other_tz)
dt = datetime(2012, 3, 26, 12, 0)
other_dt = other_tz.localize(dt)
local_dt = other_dt.astimezone(self.tz)
self.assertTrue(local_dt.tzinfo is not other_dt.tzinfo)
self.assertNotEqual(
local_dt.replace(tzinfo=None), other_dt.replace(tzinfo=None))
class OptimizedUTCTestCase(unittest.TestCase, BaseTzInfoTestCase):
tz = pytz.utc
tz_class = tz.__class__
class LegacyUTCTestCase(unittest.TestCase, BaseTzInfoTestCase):
# Deprecated timezone, but useful for comparison tests.
tz = pytz.timezone('Etc/UTC')
tz_class = StaticTzInfo
class StaticTzInfoTestCase(unittest.TestCase, BaseTzInfoTestCase):
tz = pytz.timezone('GMT')
tz_class = StaticTzInfo
class DstTzInfoTestCase(unittest.TestCase, BaseTzInfoTestCase):
tz = pytz.timezone('Australia/Melbourne')
tz_class = DstTzInfo
def test_suite():
suite = unittest.TestSuite()
suite.addTest(doctest.DocTestSuite('pytz'))
suite.addTest(doctest.DocTestSuite('pytz.tzinfo'))
import test_tzinfo
suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(test_tzinfo))
return suite
if __name__ == '__main__':
warnings.simplefilter("error") # Warnings should be fatal in tests.
unittest.main(defaultTest='test_suite')

View file

@ -1,32 +1,30 @@
#!/usr/bin/env python
''' '''
$Id: tzfile.py,v 1.8 2004/06/03 00:15:24 zenzen Exp $ $Id: tzfile.py,v 1.8 2004/06/03 00:15:24 zenzen Exp $
''' '''
try: from datetime import datetime
from cStringIO import StringIO
except ImportError:
from io import StringIO
from datetime import datetime, timedelta
from struct import unpack, calcsize from struct import unpack, calcsize
from pytz.tzinfo import StaticTzInfo, DstTzInfo, memorized_ttinfo from pytz.tzinfo import StaticTzInfo, DstTzInfo, memorized_ttinfo
from pytz.tzinfo import memorized_datetime, memorized_timedelta from pytz.tzinfo import memorized_datetime, memorized_timedelta
def _byte_string(s): def _byte_string(s):
"""Cast a string or byte string to an ASCII byte string.""" """Cast a string or byte string to an ASCII byte string."""
return s.encode('ASCII') return s.encode('ASCII')
_NULL = _byte_string('\0') _NULL = _byte_string('\0')
def _std_string(s): def _std_string(s):
"""Cast a string or byte string to an ASCII string.""" """Cast a string or byte string to an ASCII string."""
return str(s.decode('ASCII')) return str(s.decode('ASCII'))
def build_tzinfo(zone, fp): def build_tzinfo(zone, fp):
head_fmt = '>4s c 15x 6l' head_fmt = '>4s c 15x 6l'
head_size = calcsize(head_fmt) head_size = calcsize(head_fmt)
(magic, format, ttisgmtcnt, ttisstdcnt,leapcnt, timecnt, (magic, format, ttisgmtcnt, ttisstdcnt, leapcnt, timecnt,
typecnt, charcnt) = unpack(head_fmt, fp.read(head_size)) typecnt, charcnt) = unpack(head_fmt, fp.read(head_size))
# Make sure it is a tzfile(5) file # Make sure it is a tzfile(5) file
@ -34,7 +32,7 @@ def build_tzinfo(zone, fp):
# Read out the transition times, localtime indices and ttinfo structures. # Read out the transition times, localtime indices and ttinfo structures.
data_fmt = '>%(timecnt)dl %(timecnt)dB %(ttinfo)s %(charcnt)ds' % dict( data_fmt = '>%(timecnt)dl %(timecnt)dB %(ttinfo)s %(charcnt)ds' % dict(
timecnt=timecnt, ttinfo='lBB'*typecnt, charcnt=charcnt) timecnt=timecnt, ttinfo='lBB' * typecnt, charcnt=charcnt)
data_size = calcsize(data_fmt) data_size = calcsize(data_fmt)
data = unpack(data_fmt, fp.read(data_size)) data = unpack(data_fmt, fp.read(data_size))
@ -53,7 +51,7 @@ def build_tzinfo(zone, fp):
i = 0 i = 0
while i < len(ttinfo_raw): while i < len(ttinfo_raw):
# have we looked up this timezone name yet? # have we looked up this timezone name yet?
tzname_offset = ttinfo_raw[i+2] tzname_offset = ttinfo_raw[i + 2]
if tzname_offset not in tznames: if tzname_offset not in tznames:
nul = tznames_raw.find(_NULL, tzname_offset) nul = tznames_raw.find(_NULL, tzname_offset)
if nul < 0: if nul < 0:
@ -61,12 +59,12 @@ def build_tzinfo(zone, fp):
tznames[tzname_offset] = _std_string( tznames[tzname_offset] = _std_string(
tznames_raw[tzname_offset:nul]) tznames_raw[tzname_offset:nul])
ttinfo.append((ttinfo_raw[i], ttinfo.append((ttinfo_raw[i],
bool(ttinfo_raw[i+1]), bool(ttinfo_raw[i + 1]),
tznames[tzname_offset])) tznames[tzname_offset]))
i += 3 i += 3
# Now build the timezone object # Now build the timezone object
if len(ttinfo) ==1 or len(transitions) == 0: if len(ttinfo) == 1 or len(transitions) == 0:
ttinfo[0][0], ttinfo[0][2] ttinfo[0][0], ttinfo[0][2]
cls = type(zone, (StaticTzInfo,), dict( cls = type(zone, (StaticTzInfo,), dict(
zone=zone, zone=zone,
@ -91,7 +89,7 @@ def build_tzinfo(zone, fp):
if not inf[1]: if not inf[1]:
dst = 0 dst = 0
else: else:
for j in range(i-1, -1, -1): for j in range(i - 1, -1, -1):
prev_inf = ttinfo[lindexes[j]] prev_inf = ttinfo[lindexes[j]]
if not prev_inf[1]: if not prev_inf[1]:
break break
@ -99,8 +97,8 @@ def build_tzinfo(zone, fp):
# Bad dst? Look further. DST > 24 hours happens when # Bad dst? Look further. DST > 24 hours happens when
# a timzone has moved across the international dateline. # a timzone has moved across the international dateline.
if dst <= 0 or dst > 3600*3: if dst <= 0 or dst > 3600 * 3:
for j in range(i+1, len(transitions)): for j in range(i + 1, len(transitions)):
stdinf = ttinfo[lindexes[j]] stdinf = ttinfo[lindexes[j]]
if not stdinf[1]: if not stdinf[1]:
dst = inf[0] - stdinf[0] dst = inf[0] - stdinf[0]
@ -129,9 +127,7 @@ if __name__ == '__main__':
from pprint import pprint from pprint import pprint
base = os.path.join(os.path.dirname(__file__), 'zoneinfo') base = os.path.join(os.path.dirname(__file__), 'zoneinfo')
tz = build_tzinfo('Australia/Melbourne', tz = build_tzinfo('Australia/Melbourne',
open(os.path.join(base,'Australia','Melbourne'), 'rb')) open(os.path.join(base, 'Australia', 'Melbourne'), 'rb'))
tz = build_tzinfo('US/Eastern', tz = build_tzinfo('US/Eastern',
open(os.path.join(base,'US','Eastern'), 'rb')) open(os.path.join(base, 'US', 'Eastern'), 'rb'))
pprint(tz._utc_transition_times) pprint(tz._utc_transition_times)
#print tz.asPython(4)
#print tz.transitions_mapping

View file

@ -13,6 +13,8 @@ from pytz.exceptions import AmbiguousTimeError, NonExistentTimeError
__all__ = [] __all__ = []
_timedelta_cache = {} _timedelta_cache = {}
def memorized_timedelta(seconds): def memorized_timedelta(seconds):
'''Create only one instance of each distinct timedelta''' '''Create only one instance of each distinct timedelta'''
try: try:
@ -24,6 +26,8 @@ def memorized_timedelta(seconds):
_epoch = datetime.utcfromtimestamp(0) _epoch = datetime.utcfromtimestamp(0)
_datetime_cache = {0: _epoch} _datetime_cache = {0: _epoch}
def memorized_datetime(seconds): def memorized_datetime(seconds):
'''Create only one instance of each distinct datetime''' '''Create only one instance of each distinct datetime'''
try: try:
@ -36,6 +40,8 @@ def memorized_datetime(seconds):
return dt return dt
_ttinfo_cache = {} _ttinfo_cache = {}
def memorized_ttinfo(*args): def memorized_ttinfo(*args):
'''Create only one instance of each distinct tuple''' '''Create only one instance of each distinct tuple'''
try: try:
@ -51,6 +57,7 @@ def memorized_ttinfo(*args):
_notime = memorized_timedelta(0) _notime = memorized_timedelta(0)
def _to_seconds(td): def _to_seconds(td):
'''Convert a timedelta to seconds''' '''Convert a timedelta to seconds'''
return td.seconds + td.days * 24 * 60 * 60 return td.seconds + td.days * 24 * 60 * 60
@ -154,12 +161,18 @@ class DstTzInfo(BaseTzInfo):
timezone definition. timezone definition.
''' '''
# Overridden in subclass # Overridden in subclass
_utc_transition_times = None # Sorted list of DST transition times in UTC
_transition_info = None # [(utcoffset, dstoffset, tzname)] corresponding # Sorted list of DST transition times, UTC
# to _utc_transition_times entries _utc_transition_times = None
# [(utcoffset, dstoffset, tzname)] corresponding to
# _utc_transition_times entries
_transition_info = None
zone = None zone = None
# Set in __init__ # Set in __init__
_tzinfos = None _tzinfos = None
_dst = None # DST offset _dst = None # DST offset
@ -170,7 +183,8 @@ class DstTzInfo(BaseTzInfo):
else: else:
_tzinfos = {} _tzinfos = {}
self._tzinfos = _tzinfos self._tzinfos = _tzinfos
self._utcoffset, self._dst, self._tzname = self._transition_info[0] self._utcoffset, self._dst, self._tzname = (
self._transition_info[0])
_tzinfos[self._transition_info[0]] = self _tzinfos[self._transition_info[0]] = self
for inf in self._transition_info[1:]: for inf in self._transition_info[1:]:
if inf not in _tzinfos: if inf not in _tzinfos:
@ -178,8 +192,8 @@ class DstTzInfo(BaseTzInfo):
def fromutc(self, dt): def fromutc(self, dt):
'''See datetime.tzinfo.fromutc''' '''See datetime.tzinfo.fromutc'''
if (dt.tzinfo is not None if (dt.tzinfo is not None and
and getattr(dt.tzinfo, '_tzinfos', None) is not self._tzinfos): getattr(dt.tzinfo, '_tzinfos', None) is not self._tzinfos):
raise ValueError('fromutc: dt.tzinfo is not self') raise ValueError('fromutc: dt.tzinfo is not self')
dt = dt.replace(tzinfo=None) dt = dt.replace(tzinfo=None)
idx = max(0, bisect_right(self._utc_transition_times, dt) - 1) idx = max(0, bisect_right(self._utc_transition_times, dt) - 1)
@ -337,8 +351,8 @@ class DstTzInfo(BaseTzInfo):
# obtain the correct timezone by winding the clock back. # obtain the correct timezone by winding the clock back.
else: else:
return self.localize( return self.localize(
dt - timedelta(hours=6), is_dst=False) + timedelta(hours=6) dt - timedelta(hours=6),
is_dst=False) + timedelta(hours=6)
# If we get this far, we have multiple possible timezones - this # If we get this far, we have multiple possible timezones - this
# is an ambiguous case occuring during the end-of-DST transition. # is an ambiguous case occuring during the end-of-DST transition.
@ -351,8 +365,7 @@ class DstTzInfo(BaseTzInfo):
# Filter out the possiblilities that don't match the requested # Filter out the possiblilities that don't match the requested
# is_dst # is_dst
filtered_possible_loc_dt = [ filtered_possible_loc_dt = [
p for p in possible_loc_dt p for p in possible_loc_dt if bool(p.tzinfo._dst) == is_dst
if bool(p.tzinfo._dst) == is_dst
] ]
# Hopefully we only have one possibility left. Return it. # Hopefully we only have one possibility left. Return it.
@ -374,7 +387,8 @@ class DstTzInfo(BaseTzInfo):
# i.e., behave like end-of-DST transition # i.e., behave like end-of-DST transition
dates = {} # utc -> local dates = {} # utc -> local
for local_dt in filtered_possible_loc_dt: for local_dt in filtered_possible_loc_dt:
utc_time = local_dt.replace(tzinfo=None) - local_dt.tzinfo._utcoffset utc_time = (
local_dt.replace(tzinfo=None) - local_dt.tzinfo._utcoffset)
assert utc_time not in dates assert utc_time not in dates
dates[utc_time] = local_dt dates[utc_time] = local_dt
return dates[[min, max][not is_dst](dates)] return dates[[min, max][not is_dst](dates)]
@ -389,11 +403,11 @@ class DstTzInfo(BaseTzInfo):
>>> tz = timezone('America/St_Johns') >>> tz = timezone('America/St_Johns')
>>> ambiguous = datetime(2009, 10, 31, 23, 30) >>> ambiguous = datetime(2009, 10, 31, 23, 30)
>>> tz.utcoffset(ambiguous, is_dst=False) >>> str(tz.utcoffset(ambiguous, is_dst=False))
datetime.timedelta(-1, 73800) '-1 day, 20:30:00'
>>> tz.utcoffset(ambiguous, is_dst=True) >>> str(tz.utcoffset(ambiguous, is_dst=True))
datetime.timedelta(-1, 77400) '-1 day, 21:30:00'
>>> try: >>> try:
... tz.utcoffset(ambiguous) ... tz.utcoffset(ambiguous)
@ -421,19 +435,19 @@ class DstTzInfo(BaseTzInfo):
>>> normal = datetime(2009, 9, 1) >>> normal = datetime(2009, 9, 1)
>>> tz.dst(normal) >>> str(tz.dst(normal))
datetime.timedelta(0, 3600) '1:00:00'
>>> tz.dst(normal, is_dst=False) >>> str(tz.dst(normal, is_dst=False))
datetime.timedelta(0, 3600) '1:00:00'
>>> tz.dst(normal, is_dst=True) >>> str(tz.dst(normal, is_dst=True))
datetime.timedelta(0, 3600) '1:00:00'
>>> ambiguous = datetime(2009, 10, 31, 23, 30) >>> ambiguous = datetime(2009, 10, 31, 23, 30)
>>> tz.dst(ambiguous, is_dst=False) >>> str(tz.dst(ambiguous, is_dst=False))
datetime.timedelta(0) '0:00:00'
>>> tz.dst(ambiguous, is_dst=True) >>> str(tz.dst(ambiguous, is_dst=True))
datetime.timedelta(0, 3600) '1:00:00'
>>> try: >>> try:
... tz.dst(ambiguous) ... tz.dst(ambiguous)
... except AmbiguousTimeError: ... except AmbiguousTimeError:
@ -512,7 +526,6 @@ class DstTzInfo(BaseTzInfo):
) )
def unpickler(zone, utcoffset=None, dstoffset=None, tzname=None): def unpickler(zone, utcoffset=None, dstoffset=None, tzname=None):
"""Factory function for unpickling pytz tzinfo instances. """Factory function for unpickling pytz tzinfo instances.
@ -549,8 +562,8 @@ def unpickler(zone, utcoffset=None, dstoffset=None, tzname=None):
# get changed from the initial guess by the database maintainers to # get changed from the initial guess by the database maintainers to
# match reality when this information is discovered. # match reality when this information is discovered.
for localized_tz in tz._tzinfos.values(): for localized_tz in tz._tzinfos.values():
if (localized_tz._utcoffset == utcoffset if (localized_tz._utcoffset == utcoffset and
and localized_tz._dst == dstoffset): localized_tz._dst == dstoffset):
return localized_tz return localized_tz
# This (utcoffset, dstoffset) information has been removed from the # This (utcoffset, dstoffset) information has been removed from the

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show more