mirror of
https://github.com/rembo10/headphones.git
synced 2026-05-19 01:55:31 +01:00
Update pytz lib
This commit is contained in:
@@ -1,19 +0,0 @@
|
||||
Copyright (c) 2003-2009 Stuart Bishop <stuart@stuartbishop.net>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of this software and associated documentation files (the "Software"),
|
||||
to deal in the Software without restriction, including without limitation
|
||||
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
and/or sell copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
@@ -1,575 +0,0 @@
|
||||
pytz - World Timezone Definitions for Python
|
||||
============================================
|
||||
|
||||
:Author: Stuart Bishop <stuart@stuartbishop.net>
|
||||
|
||||
Introduction
|
||||
~~~~~~~~~~~~
|
||||
|
||||
pytz brings the Olson tz database into Python. This library allows
|
||||
accurate and cross platform timezone calculations using Python 2.4
|
||||
or higher. It also solves the issue of ambiguous times at the end
|
||||
of daylight saving time, which you can read more about in the Python
|
||||
Library Reference (``datetime.tzinfo``).
|
||||
|
||||
Almost all of the Olson timezones are supported.
|
||||
|
||||
.. note::
|
||||
|
||||
This library differs from the documented Python API for
|
||||
tzinfo implementations; if you want to create local wallclock
|
||||
times you need to use the ``localize()`` method documented in this
|
||||
document. In addition, if you perform date arithmetic on local
|
||||
times that cross DST boundaries, the result may be in an incorrect
|
||||
timezone (ie. subtract 1 minute from 2002-10-27 1:00 EST and you get
|
||||
2002-10-27 0:59 EST instead of the correct 2002-10-27 1:59 EDT). A
|
||||
``normalize()`` method is provided to correct this. Unfortunately these
|
||||
issues cannot be resolved without modifying the Python datetime
|
||||
implementation (see PEP-431).
|
||||
|
||||
|
||||
Installation
|
||||
~~~~~~~~~~~~
|
||||
|
||||
This package can either be installed from a .egg file using setuptools,
|
||||
or from the tarball using the standard Python distutils.
|
||||
|
||||
If you are installing from a tarball, run the following command as an
|
||||
administrative user::
|
||||
|
||||
python setup.py install
|
||||
|
||||
If you are installing using setuptools, you don't even need to download
|
||||
anything as the latest version will be downloaded for you
|
||||
from the Python package index::
|
||||
|
||||
easy_install --upgrade pytz
|
||||
|
||||
If you already have the .egg file, you can use that too::
|
||||
|
||||
easy_install pytz-2008g-py2.6.egg
|
||||
|
||||
|
||||
Example & Usage
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
Localized times and date arithmetic
|
||||
-----------------------------------
|
||||
|
||||
>>> from datetime import datetime, timedelta
|
||||
>>> from pytz import timezone
|
||||
>>> import pytz
|
||||
>>> utc = pytz.utc
|
||||
>>> utc.zone
|
||||
'UTC'
|
||||
>>> eastern = timezone('US/Eastern')
|
||||
>>> eastern.zone
|
||||
'US/Eastern'
|
||||
>>> amsterdam = timezone('Europe/Amsterdam')
|
||||
>>> fmt = '%Y-%m-%d %H:%M:%S %Z%z'
|
||||
|
||||
This library only supports two ways of building a localized time. The
|
||||
first is to use the ``localize()`` method provided by the pytz library.
|
||||
This is used to localize a naive datetime (datetime with no timezone
|
||||
information):
|
||||
|
||||
>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0))
|
||||
>>> print(loc_dt.strftime(fmt))
|
||||
2002-10-27 06:00:00 EST-0500
|
||||
|
||||
The second way of building a localized time is by converting an existing
|
||||
localized time using the standard ``astimezone()`` method:
|
||||
|
||||
>>> ams_dt = loc_dt.astimezone(amsterdam)
|
||||
>>> ams_dt.strftime(fmt)
|
||||
'2002-10-27 12:00:00 CET+0100'
|
||||
|
||||
Unfortunately using the tzinfo argument of the standard datetime
|
||||
constructors ''does not work'' with pytz for many timezones.
|
||||
|
||||
>>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=amsterdam).strftime(fmt)
|
||||
'2002-10-27 12:00:00 LMT+0020'
|
||||
|
||||
It is safe for timezones without daylight saving transitions though, such
|
||||
as UTC:
|
||||
|
||||
>>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=pytz.utc).strftime(fmt)
|
||||
'2002-10-27 12:00:00 UTC+0000'
|
||||
|
||||
The preferred way of dealing with times is to always work in UTC,
|
||||
converting to localtime only when generating output to be read
|
||||
by humans.
|
||||
|
||||
>>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)
|
||||
>>> loc_dt = utc_dt.astimezone(eastern)
|
||||
>>> loc_dt.strftime(fmt)
|
||||
'2002-10-27 01:00:00 EST-0500'
|
||||
|
||||
This library also allows you to do date arithmetic using local
|
||||
times, although it is more complicated than working in UTC as you
|
||||
need to use the ``normalize()`` method to handle daylight saving time
|
||||
and other timezone transitions. In this example, ``loc_dt`` is set
|
||||
to the instant when daylight saving time ends in the US/Eastern
|
||||
timezone.
|
||||
|
||||
>>> before = loc_dt - timedelta(minutes=10)
|
||||
>>> before.strftime(fmt)
|
||||
'2002-10-27 00:50:00 EST-0500'
|
||||
>>> eastern.normalize(before).strftime(fmt)
|
||||
'2002-10-27 01:50:00 EDT-0400'
|
||||
>>> after = eastern.normalize(before + timedelta(minutes=20))
|
||||
>>> after.strftime(fmt)
|
||||
'2002-10-27 01:10:00 EST-0500'
|
||||
|
||||
Creating local times is also tricky, and the reason why working with
|
||||
local times is not recommended. Unfortunately, you cannot just pass
|
||||
a ``tzinfo`` argument when constructing a datetime (see the next
|
||||
section for more details)
|
||||
|
||||
>>> dt = datetime(2002, 10, 27, 1, 30, 0)
|
||||
>>> dt1 = eastern.localize(dt, is_dst=True)
|
||||
>>> dt1.strftime(fmt)
|
||||
'2002-10-27 01:30:00 EDT-0400'
|
||||
>>> dt2 = eastern.localize(dt, is_dst=False)
|
||||
>>> dt2.strftime(fmt)
|
||||
'2002-10-27 01:30:00 EST-0500'
|
||||
|
||||
Converting between timezones also needs special attention. We also need
|
||||
to use the ``normalize()`` method to ensure the conversion is correct.
|
||||
|
||||
>>> utc_dt = utc.localize(datetime.utcfromtimestamp(1143408899))
|
||||
>>> utc_dt.strftime(fmt)
|
||||
'2006-03-26 21:34:59 UTC+0000'
|
||||
>>> au_tz = timezone('Australia/Sydney')
|
||||
>>> au_dt = au_tz.normalize(utc_dt.astimezone(au_tz))
|
||||
>>> au_dt.strftime(fmt)
|
||||
'2006-03-27 08:34:59 AEDT+1100'
|
||||
>>> utc_dt2 = utc.normalize(au_dt.astimezone(utc))
|
||||
>>> utc_dt2.strftime(fmt)
|
||||
'2006-03-26 21:34:59 UTC+0000'
|
||||
|
||||
You can take shortcuts when dealing with the UTC side of timezone
|
||||
conversions. ``normalize()`` and ``localize()`` are not really
|
||||
necessary when there are no daylight saving time transitions to
|
||||
deal with.
|
||||
|
||||
>>> utc_dt = datetime.utcfromtimestamp(1143408899).replace(tzinfo=utc)
|
||||
>>> utc_dt.strftime(fmt)
|
||||
'2006-03-26 21:34:59 UTC+0000'
|
||||
>>> au_tz = timezone('Australia/Sydney')
|
||||
>>> au_dt = au_tz.normalize(utc_dt.astimezone(au_tz))
|
||||
>>> au_dt.strftime(fmt)
|
||||
'2006-03-27 08:34:59 AEDT+1100'
|
||||
>>> utc_dt2 = au_dt.astimezone(utc)
|
||||
>>> utc_dt2.strftime(fmt)
|
||||
'2006-03-26 21:34:59 UTC+0000'
|
||||
|
||||
|
||||
``tzinfo`` API
|
||||
--------------
|
||||
|
||||
The ``tzinfo`` instances returned by the ``timezone()`` function have
|
||||
been extended to cope with ambiguous times by adding an ``is_dst``
|
||||
parameter to the ``utcoffset()``, ``dst()`` && ``tzname()`` methods.
|
||||
|
||||
>>> tz = timezone('America/St_Johns')
|
||||
|
||||
>>> normal = datetime(2009, 9, 1)
|
||||
>>> ambiguous = datetime(2009, 10, 31, 23, 30)
|
||||
|
||||
The ``is_dst`` parameter is ignored for most timestamps. It is only used
|
||||
during DST transition ambiguous periods to resulve that ambiguity.
|
||||
|
||||
>>> tz.utcoffset(normal, is_dst=True)
|
||||
datetime.timedelta(-1, 77400)
|
||||
>>> tz.dst(normal, is_dst=True)
|
||||
datetime.timedelta(0, 3600)
|
||||
>>> tz.tzname(normal, is_dst=True)
|
||||
'NDT'
|
||||
|
||||
>>> tz.utcoffset(ambiguous, is_dst=True)
|
||||
datetime.timedelta(-1, 77400)
|
||||
>>> tz.dst(ambiguous, is_dst=True)
|
||||
datetime.timedelta(0, 3600)
|
||||
>>> tz.tzname(ambiguous, is_dst=True)
|
||||
'NDT'
|
||||
|
||||
>>> tz.utcoffset(normal, is_dst=False)
|
||||
datetime.timedelta(-1, 77400)
|
||||
>>> tz.dst(normal, is_dst=False)
|
||||
datetime.timedelta(0, 3600)
|
||||
>>> tz.tzname(normal, is_dst=False)
|
||||
'NDT'
|
||||
|
||||
>>> tz.utcoffset(ambiguous, is_dst=False)
|
||||
datetime.timedelta(-1, 73800)
|
||||
>>> tz.dst(ambiguous, is_dst=False)
|
||||
datetime.timedelta(0)
|
||||
>>> tz.tzname(ambiguous, is_dst=False)
|
||||
'NST'
|
||||
|
||||
If ``is_dst`` is not specified, ambiguous timestamps will raise
|
||||
an ``pytz.exceptions.AmbiguousTimeError`` exception.
|
||||
|
||||
>>> tz.utcoffset(normal)
|
||||
datetime.timedelta(-1, 77400)
|
||||
>>> tz.dst(normal)
|
||||
datetime.timedelta(0, 3600)
|
||||
>>> tz.tzname(normal)
|
||||
'NDT'
|
||||
|
||||
>>> import pytz.exceptions
|
||||
>>> try:
|
||||
... tz.utcoffset(ambiguous)
|
||||
... except pytz.exceptions.AmbiguousTimeError:
|
||||
... print('pytz.exceptions.AmbiguousTimeError: %s' % ambiguous)
|
||||
pytz.exceptions.AmbiguousTimeError: 2009-10-31 23:30:00
|
||||
>>> try:
|
||||
... tz.dst(ambiguous)
|
||||
... except pytz.exceptions.AmbiguousTimeError:
|
||||
... print('pytz.exceptions.AmbiguousTimeError: %s' % ambiguous)
|
||||
pytz.exceptions.AmbiguousTimeError: 2009-10-31 23:30:00
|
||||
>>> try:
|
||||
... tz.tzname(ambiguous)
|
||||
... except pytz.exceptions.AmbiguousTimeError:
|
||||
... print('pytz.exceptions.AmbiguousTimeError: %s' % ambiguous)
|
||||
pytz.exceptions.AmbiguousTimeError: 2009-10-31 23:30:00
|
||||
|
||||
|
||||
Problems with Localtime
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The major problem we have to deal with is that certain datetimes
|
||||
may occur twice in a year. For example, in the US/Eastern timezone
|
||||
on the last Sunday morning in October, the following sequence
|
||||
happens:
|
||||
|
||||
- 01:00 EDT occurs
|
||||
- 1 hour later, instead of 2:00am the clock is turned back 1 hour
|
||||
and 01:00 happens again (this time 01:00 EST)
|
||||
|
||||
In fact, every instant between 01:00 and 02:00 occurs twice. This means
|
||||
that if you try and create a time in the 'US/Eastern' timezone
|
||||
the standard datetime syntax, there is no way to specify if you meant
|
||||
before of after the end-of-daylight-saving-time transition. Using the
|
||||
pytz custom syntax, the best you can do is make an educated guess:
|
||||
|
||||
>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 1, 30, 00))
|
||||
>>> loc_dt.strftime(fmt)
|
||||
'2002-10-27 01:30:00 EST-0500'
|
||||
|
||||
As you can see, the system has chosen one for you and there is a 50%
|
||||
chance of it being out by one hour. For some applications, this does
|
||||
not matter. However, if you are trying to schedule meetings with people
|
||||
in different timezones or analyze log files it is not acceptable.
|
||||
|
||||
The best and simplest solution is to stick with using UTC. The pytz
|
||||
package encourages using UTC for internal timezone representation by
|
||||
including a special UTC implementation based on the standard Python
|
||||
reference implementation in the Python documentation.
|
||||
|
||||
The UTC timezone unpickles to be the same instance, and pickles to a
|
||||
smaller size than other pytz tzinfo instances. The UTC implementation
|
||||
can be obtained as pytz.utc, pytz.UTC, or pytz.timezone('UTC').
|
||||
|
||||
>>> import pickle, pytz
|
||||
>>> dt = datetime(2005, 3, 1, 14, 13, 21, tzinfo=utc)
|
||||
>>> naive = dt.replace(tzinfo=None)
|
||||
>>> p = pickle.dumps(dt, 1)
|
||||
>>> naive_p = pickle.dumps(naive, 1)
|
||||
>>> len(p) - len(naive_p)
|
||||
17
|
||||
>>> new = pickle.loads(p)
|
||||
>>> new == dt
|
||||
True
|
||||
>>> new is dt
|
||||
False
|
||||
>>> new.tzinfo is dt.tzinfo
|
||||
True
|
||||
>>> pytz.utc is pytz.UTC is pytz.timezone('UTC')
|
||||
True
|
||||
|
||||
Note that some other timezones are commonly thought of as the same (GMT,
|
||||
Greenwich, Universal, etc.). The definition of UTC is distinct from these
|
||||
other timezones, and they are not equivalent. For this reason, they will
|
||||
not compare the same in Python.
|
||||
|
||||
>>> utc == pytz.timezone('GMT')
|
||||
False
|
||||
|
||||
See the section `What is UTC`_, below.
|
||||
|
||||
If you insist on working with local times, this library provides a
|
||||
facility for constructing them unambiguously:
|
||||
|
||||
>>> loc_dt = datetime(2002, 10, 27, 1, 30, 00)
|
||||
>>> est_dt = eastern.localize(loc_dt, is_dst=True)
|
||||
>>> edt_dt = eastern.localize(loc_dt, is_dst=False)
|
||||
>>> print(est_dt.strftime(fmt) + ' / ' + edt_dt.strftime(fmt))
|
||||
2002-10-27 01:30:00 EDT-0400 / 2002-10-27 01:30:00 EST-0500
|
||||
|
||||
If you pass None as the is_dst flag to localize(), pytz will refuse to
|
||||
guess and raise exceptions if you try to build ambiguous or non-existent
|
||||
times.
|
||||
|
||||
For example, 1:30am on 27th Oct 2002 happened twice in the US/Eastern
|
||||
timezone when the clocks where put back at the end of Daylight Saving
|
||||
Time:
|
||||
|
||||
>>> dt = datetime(2002, 10, 27, 1, 30, 00)
|
||||
>>> try:
|
||||
... eastern.localize(dt, is_dst=None)
|
||||
... except pytz.exceptions.AmbiguousTimeError:
|
||||
... print('pytz.exceptions.AmbiguousTimeError: %s' % dt)
|
||||
pytz.exceptions.AmbiguousTimeError: 2002-10-27 01:30:00
|
||||
|
||||
Similarly, 2:30am on 7th April 2002 never happened at all in the
|
||||
US/Eastern timezone, as the clocks where put forward at 2:00am skipping
|
||||
the entire hour:
|
||||
|
||||
>>> dt = datetime(2002, 4, 7, 2, 30, 00)
|
||||
>>> try:
|
||||
... eastern.localize(dt, is_dst=None)
|
||||
... except pytz.exceptions.NonExistentTimeError:
|
||||
... print('pytz.exceptions.NonExistentTimeError: %s' % dt)
|
||||
pytz.exceptions.NonExistentTimeError: 2002-04-07 02:30:00
|
||||
|
||||
Both of these exceptions share a common base class to make error handling
|
||||
easier:
|
||||
|
||||
>>> isinstance(pytz.AmbiguousTimeError(), pytz.InvalidTimeError)
|
||||
True
|
||||
>>> isinstance(pytz.NonExistentTimeError(), pytz.InvalidTimeError)
|
||||
True
|
||||
|
||||
|
||||
A special case is where countries change their timezone definitions
|
||||
with no daylight savings time switch. For example, in 1915 Warsaw
|
||||
switched from Warsaw time to Central European time with no daylight savings
|
||||
transition. So at the stroke of midnight on August 5th 1915 the clocks
|
||||
were wound back 24 minutes creating an ambiguous time period that cannot
|
||||
be specified without referring to the timezone abbreviation or the
|
||||
actual UTC offset. In this case midnight happened twice, neither time
|
||||
during a daylight saving time period. pytz handles this transition by
|
||||
treating the ambiguous period before the switch as daylight savings
|
||||
time, and the ambiguous period after as standard time.
|
||||
|
||||
|
||||
>>> warsaw = pytz.timezone('Europe/Warsaw')
|
||||
>>> amb_dt1 = warsaw.localize(datetime(1915, 8, 4, 23, 59, 59), is_dst=True)
|
||||
>>> amb_dt1.strftime(fmt)
|
||||
'1915-08-04 23:59:59 WMT+0124'
|
||||
>>> amb_dt2 = warsaw.localize(datetime(1915, 8, 4, 23, 59, 59), is_dst=False)
|
||||
>>> amb_dt2.strftime(fmt)
|
||||
'1915-08-04 23:59:59 CET+0100'
|
||||
>>> switch_dt = warsaw.localize(datetime(1915, 8, 5, 00, 00, 00), is_dst=False)
|
||||
>>> switch_dt.strftime(fmt)
|
||||
'1915-08-05 00:00:00 CET+0100'
|
||||
>>> str(switch_dt - amb_dt1)
|
||||
'0:24:01'
|
||||
>>> str(switch_dt - amb_dt2)
|
||||
'0:00:01'
|
||||
|
||||
The best way of creating a time during an ambiguous time period is
|
||||
by converting from another timezone such as UTC:
|
||||
|
||||
>>> utc_dt = datetime(1915, 8, 4, 22, 36, tzinfo=pytz.utc)
|
||||
>>> utc_dt.astimezone(warsaw).strftime(fmt)
|
||||
'1915-08-04 23:36:00 CET+0100'
|
||||
|
||||
The standard Python way of handling all these ambiguities is not to
|
||||
handle them, such as demonstrated in this example using the US/Eastern
|
||||
timezone definition from the Python documentation (Note that this
|
||||
implementation only works for dates between 1987 and 2006 - it is
|
||||
included for tests only!):
|
||||
|
||||
>>> from pytz.reference import Eastern # pytz.reference only for tests
|
||||
>>> dt = datetime(2002, 10, 27, 0, 30, tzinfo=Eastern)
|
||||
>>> str(dt)
|
||||
'2002-10-27 00:30:00-04:00'
|
||||
>>> str(dt + timedelta(hours=1))
|
||||
'2002-10-27 01:30:00-05:00'
|
||||
>>> str(dt + timedelta(hours=2))
|
||||
'2002-10-27 02:30:00-05:00'
|
||||
>>> str(dt + timedelta(hours=3))
|
||||
'2002-10-27 03:30:00-05:00'
|
||||
|
||||
Notice the first two results? At first glance you might think they are
|
||||
correct, but taking the UTC offset into account you find that they are
|
||||
actually two hours appart instead of the 1 hour we asked for.
|
||||
|
||||
>>> from pytz.reference import UTC # pytz.reference only for tests
|
||||
>>> str(dt.astimezone(UTC))
|
||||
'2002-10-27 04:30:00+00:00'
|
||||
>>> str((dt + timedelta(hours=1)).astimezone(UTC))
|
||||
'2002-10-27 06:30:00+00:00'
|
||||
|
||||
|
||||
Country Information
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
A mechanism is provided to access the timezones commonly in use
|
||||
for a particular country, looked up using the ISO 3166 country code.
|
||||
It returns a list of strings that can be used to retrieve the relevant
|
||||
tzinfo instance using ``pytz.timezone()``:
|
||||
|
||||
>>> print(' '.join(pytz.country_timezones['nz']))
|
||||
Pacific/Auckland Pacific/Chatham
|
||||
|
||||
The Olson database comes with a ISO 3166 country code to English country
|
||||
name mapping that pytz exposes as a dictionary:
|
||||
|
||||
>>> print(pytz.country_names['nz'])
|
||||
New Zealand
|
||||
|
||||
|
||||
What is UTC
|
||||
~~~~~~~~~~~
|
||||
|
||||
'UTC' is `Coordinated Universal Time`_. It is a successor to, but distinct
|
||||
from, Greenwich Mean Time (GMT) and the various definitions of Universal
|
||||
Time. UTC is now the worldwide standard for regulating clocks and time
|
||||
measurement.
|
||||
|
||||
All other timezones are defined relative to UTC, and include offsets like
|
||||
UTC+0800 - hours to add or subtract from UTC to derive the local time. No
|
||||
daylight saving time occurs in UTC, making it a useful timezone to perform
|
||||
date arithmetic without worrying about the confusion and ambiguities caused
|
||||
by daylight saving time transitions, your country changing its timezone, or
|
||||
mobile computers that roam through multiple timezones.
|
||||
|
||||
.. _Coordinated Universal Time: https://en.wikipedia.org/wiki/Coordinated_Universal_Time
|
||||
|
||||
|
||||
Helpers
|
||||
~~~~~~~
|
||||
|
||||
There are two lists of timezones provided.
|
||||
|
||||
``all_timezones`` is the exhaustive list of the timezone names that can
|
||||
be used.
|
||||
|
||||
>>> from pytz import all_timezones
|
||||
>>> len(all_timezones) >= 500
|
||||
True
|
||||
>>> 'Etc/Greenwich' in all_timezones
|
||||
True
|
||||
|
||||
``common_timezones`` is a list of useful, current timezones. It doesn't
|
||||
contain deprecated zones or historical zones, except for a few I've
|
||||
deemed in common usage, such as US/Eastern (open a bug report if you
|
||||
think other timezones are deserving of being included here). It is also
|
||||
a sequence of strings.
|
||||
|
||||
>>> from pytz import common_timezones
|
||||
>>> len(common_timezones) < len(all_timezones)
|
||||
True
|
||||
>>> 'Etc/Greenwich' in common_timezones
|
||||
False
|
||||
>>> 'Australia/Melbourne' in common_timezones
|
||||
True
|
||||
>>> 'US/Eastern' in common_timezones
|
||||
True
|
||||
>>> 'Canada/Eastern' in common_timezones
|
||||
True
|
||||
>>> 'US/Pacific-New' in all_timezones
|
||||
True
|
||||
>>> 'US/Pacific-New' in common_timezones
|
||||
False
|
||||
|
||||
Both ``common_timezones`` and ``all_timezones`` are alphabetically
|
||||
sorted:
|
||||
|
||||
>>> common_timezones_dupe = common_timezones[:]
|
||||
>>> common_timezones_dupe.sort()
|
||||
>>> common_timezones == common_timezones_dupe
|
||||
True
|
||||
>>> all_timezones_dupe = all_timezones[:]
|
||||
>>> all_timezones_dupe.sort()
|
||||
>>> all_timezones == all_timezones_dupe
|
||||
True
|
||||
|
||||
``all_timezones`` and ``common_timezones`` are also available as sets.
|
||||
|
||||
>>> from pytz import all_timezones_set, common_timezones_set
|
||||
>>> 'US/Eastern' in all_timezones_set
|
||||
True
|
||||
>>> 'US/Eastern' in common_timezones_set
|
||||
True
|
||||
>>> 'Australia/Victoria' in common_timezones_set
|
||||
False
|
||||
|
||||
You can also retrieve lists of timezones used by particular countries
|
||||
using the ``country_timezones()`` function. It requires an ISO-3166
|
||||
two letter country code.
|
||||
|
||||
>>> from pytz import country_timezones
|
||||
>>> print(' '.join(country_timezones('ch')))
|
||||
Europe/Zurich
|
||||
>>> print(' '.join(country_timezones('CH')))
|
||||
Europe/Zurich
|
||||
|
||||
|
||||
License
|
||||
~~~~~~~
|
||||
|
||||
MIT license.
|
||||
|
||||
This code is also available as part of Zope 3 under the Zope Public
|
||||
License, Version 2.1 (ZPL).
|
||||
|
||||
I'm happy to relicense this code if necessary for inclusion in other
|
||||
open source projects.
|
||||
|
||||
|
||||
Latest Versions
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
This package will be updated after releases of the Olson timezone
|
||||
database. The latest version can be downloaded from the `Python Package
|
||||
Index <http://pypi.python.org/pypi/pytz/>`_. The code that is used
|
||||
to generate this distribution is hosted on launchpad.net and available
|
||||
using the `Bazaar version control system <http://bazaar-vcs.org>`_
|
||||
using::
|
||||
|
||||
bzr branch lp:pytz
|
||||
|
||||
Announcements of new releases are made on
|
||||
`Launchpad <https://launchpad.net/pytz>`_, and the
|
||||
`Atom feed <http://feeds.launchpad.net/pytz/announcements.atom>`_
|
||||
hosted there.
|
||||
|
||||
|
||||
Bugs, Feature Requests & Patches
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Bugs can be reported using `Launchpad <https://bugs.launchpad.net/pytz>`_.
|
||||
|
||||
|
||||
Issues & Limitations
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
- Offsets from UTC are rounded to the nearest whole minute, so timezones
|
||||
such as Europe/Amsterdam pre 1937 will be up to 30 seconds out. This
|
||||
is a limitation of the Python datetime library.
|
||||
|
||||
- If you think a timezone definition is incorrect, I probably can't fix
|
||||
it. pytz is a direct translation of the Olson timezone database, and
|
||||
changes to the timezone definitions need to be made to this source.
|
||||
If you find errors they should be reported to the time zone mailing
|
||||
list, linked from http://www.iana.org/time-zones.
|
||||
|
||||
|
||||
Further Reading
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
More info than you want to know about timezones:
|
||||
http://www.twinsun.com/tz/tz-link.htm
|
||||
|
||||
|
||||
Contact
|
||||
~~~~~~~
|
||||
|
||||
Stuart Bishop <stuart@stuartbishop.net>
|
||||
|
||||
|
||||
@@ -8,12 +8,25 @@ See the datetime section of the Python Library Reference for information
|
||||
on how to use these modules.
|
||||
'''
|
||||
|
||||
# The Olson database is updated several times a year.
|
||||
OLSON_VERSION = '2014j'
|
||||
VERSION = '2014.10' # Switching to pip compatible version numbering.
|
||||
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.
|
||||
OLSON_VERSION = '2021c'
|
||||
VERSION = '2021.3' # pip compatible version number.
|
||||
__version__ = VERSION
|
||||
|
||||
OLSEN_VERSION = OLSON_VERSION # Old releases had this misspelling
|
||||
OLSEN_VERSION = OLSON_VERSION # Old releases had this misspelling
|
||||
|
||||
__all__ = [
|
||||
'timezone', 'utc', 'country_timezones', 'country_names',
|
||||
@@ -21,32 +34,15 @@ __all__ = [
|
||||
'NonExistentTimeError', 'UnknownTimeZoneError',
|
||||
'all_timezones', 'all_timezones_set',
|
||||
'common_timezones', 'common_timezones_set',
|
||||
]
|
||||
|
||||
import sys, datetime, os.path, gettext
|
||||
|
||||
try:
|
||||
from pkg_resources import resource_stream
|
||||
except ImportError:
|
||||
resource_stream = None
|
||||
|
||||
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
|
||||
'BaseTzInfo', 'FixedOffset',
|
||||
]
|
||||
|
||||
|
||||
try:
|
||||
str
|
||||
|
||||
except NameError: # Python 3.x
|
||||
if sys.version_info[0] > 2: # Python 3.x
|
||||
|
||||
# Python 3.x doesn't have unicode(), making writing code
|
||||
# for Python 2.3 and Python 3.x a pain.
|
||||
str = str
|
||||
unicode = str
|
||||
|
||||
def ascii(s):
|
||||
r"""
|
||||
@@ -57,10 +53,13 @@ except NameError: # Python 3.x
|
||||
...
|
||||
UnicodeEncodeError: ...
|
||||
"""
|
||||
s.encode('US-ASCII') # Raise an exception if not ASCII
|
||||
return s # But return the original string - not a byte string.
|
||||
if type(s) == bytes:
|
||||
s = s.decode('ASCII')
|
||||
else:
|
||||
s.encode('ASCII') # Raise an exception if not ASCII
|
||||
return s # But the string - not a byte string.
|
||||
|
||||
else: # Python 2.x
|
||||
else: # Python 2.x
|
||||
|
||||
def ascii(s):
|
||||
r"""
|
||||
@@ -73,7 +72,7 @@ else: # Python 2.x
|
||||
...
|
||||
UnicodeEncodeError: ...
|
||||
"""
|
||||
return s.encode('US-ASCII')
|
||||
return s.encode('ASCII')
|
||||
|
||||
|
||||
def open_resource(name):
|
||||
@@ -81,49 +80,55 @@ def open_resource(name):
|
||||
|
||||
Uses the pkg_resources module if available and no standard file
|
||||
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('/')
|
||||
for part in name_parts:
|
||||
if part == os.path.pardir or os.path.sep in part:
|
||||
raise ValueError('Bad path segment: %r' % part)
|
||||
filename = os.path.join(os.path.dirname(__file__),
|
||||
'zoneinfo', *name_parts)
|
||||
if not os.path.exists(filename) and resource_stream is not None:
|
||||
# http://bugs.launchpad.net/bugs/383171 - we avoid using this
|
||||
# unless absolutely necessary to help when a broken version of
|
||||
# pkg_resources is installed.
|
||||
return resource_stream(__name__, 'zoneinfo/' + name)
|
||||
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__),
|
||||
'zoneinfo', *name_parts)
|
||||
if not os.path.exists(filename):
|
||||
# http://bugs.launchpad.net/bugs/383171 - we avoid using this
|
||||
# unless absolutely necessary to help when a broken version of
|
||||
# pkg_resources is installed.
|
||||
try:
|
||||
from pkg_resources import resource_stream
|
||||
except ImportError:
|
||||
resource_stream = None
|
||||
|
||||
if resource_stream is not None:
|
||||
return resource_stream(__name__, 'zoneinfo/' + name)
|
||||
return open(filename, 'rb')
|
||||
|
||||
|
||||
def resource_exists(name):
|
||||
"""Return true if the given resource exists"""
|
||||
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()
|
||||
return True
|
||||
except IOError:
|
||||
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 = {}
|
||||
|
||||
|
||||
def timezone(zone):
|
||||
r''' Return a datetime.tzinfo implementation for the given timezone
|
||||
r''' Return a datetime.tzinfo implementation for the given timezone
|
||||
|
||||
>>> from datetime import datetime, timedelta
|
||||
>>> utc = timezone('UTC')
|
||||
@@ -159,6 +164,9 @@ def timezone(zone):
|
||||
Unknown
|
||||
|
||||
'''
|
||||
if zone is None:
|
||||
raise UnknownTimeZoneError(None)
|
||||
|
||||
if zone.upper() == 'UTC':
|
||||
return utc
|
||||
|
||||
@@ -168,9 +176,9 @@ def timezone(zone):
|
||||
# All valid timezones are ASCII
|
||||
raise UnknownTimeZoneError(zone)
|
||||
|
||||
zone = _unmunge_zone(zone)
|
||||
zone = _case_insensitive_zone_lookup(_unmunge_zone(zone))
|
||||
if zone not in _tzinfo_cache:
|
||||
if zone in all_timezones_set:
|
||||
if zone in all_timezones_set: # noqa
|
||||
fp = open_resource(zone)
|
||||
try:
|
||||
_tzinfo_cache[zone] = build_tzinfo(zone, fp)
|
||||
@@ -187,11 +195,22 @@ def _unmunge_zone(zone):
|
||||
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) # noqa
|
||||
return _all_timezones_lower_to_standard.get(zone.lower()) or zone # noqa
|
||||
|
||||
|
||||
ZERO = datetime.timedelta(0)
|
||||
HOUR = datetime.timedelta(hours=1)
|
||||
|
||||
|
||||
class UTC(datetime.tzinfo):
|
||||
class UTC(BaseTzInfo):
|
||||
"""UTC
|
||||
|
||||
Optimized UTC implementation. It unpickles using the single module global
|
||||
@@ -241,18 +260,18 @@ class UTC(datetime.tzinfo):
|
||||
return "UTC"
|
||||
|
||||
|
||||
UTC = utc = UTC() # UTC is a singleton
|
||||
UTC = utc = UTC() # UTC is a singleton
|
||||
|
||||
|
||||
def _UTC():
|
||||
"""Factory function for utc unpickling.
|
||||
|
||||
Makes sure that unpickling a utc instance always returns the same
|
||||
Makes sure that unpickling a utc instance always returns the same
|
||||
module global.
|
||||
|
||||
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.txt examples with the unit tests is not trivial.
|
||||
the README.rst, but we are not depending on Python 2.4 so integrating
|
||||
the README.rst examples with the unit tests is not trivial.
|
||||
|
||||
>>> import datetime, pickle
|
||||
>>> dt = datetime.datetime(2005, 3, 1, 14, 13, 21, tzinfo=utc)
|
||||
@@ -274,6 +293,8 @@ def _UTC():
|
||||
False
|
||||
"""
|
||||
return utc
|
||||
|
||||
|
||||
_UTC.__safe_for_unpickling__ = True
|
||||
|
||||
|
||||
@@ -284,9 +305,10 @@ def _p(*args):
|
||||
by shortening the path.
|
||||
"""
|
||||
return unpickler(*args)
|
||||
_p.__safe_for_unpickling__ = True
|
||||
|
||||
|
||||
_p.__safe_for_unpickling__ = True
|
||||
|
||||
|
||||
class _CountryTimezoneDict(LazyDict):
|
||||
"""Map ISO 3166 country code to a list of timezone names commonly used
|
||||
@@ -329,11 +351,11 @@ class _CountryTimezoneDict(LazyDict):
|
||||
zone_tab = open_resource('zone.tab')
|
||||
try:
|
||||
for line in zone_tab:
|
||||
line = line.decode('US-ASCII')
|
||||
line = line.decode('UTF-8')
|
||||
if line.startswith('#'):
|
||||
continue
|
||||
code, coordinates, zone = line.split(None, 4)[:3]
|
||||
if zone not in all_timezones_set:
|
||||
if zone not in all_timezones_set: # noqa
|
||||
continue
|
||||
try:
|
||||
data[code].append(zone)
|
||||
@@ -343,6 +365,7 @@ class _CountryTimezoneDict(LazyDict):
|
||||
finally:
|
||||
zone_tab.close()
|
||||
|
||||
|
||||
country_timezones = _CountryTimezoneDict()
|
||||
|
||||
|
||||
@@ -357,7 +380,7 @@ class _CountryNameDict(LazyDict):
|
||||
zone_tab = open_resource('iso3166.tab')
|
||||
try:
|
||||
for line in zone_tab.readlines():
|
||||
line = line.decode('US-ASCII')
|
||||
line = line.decode('UTF-8')
|
||||
if line.startswith('#'):
|
||||
continue
|
||||
code, name = line.split(None, 1)
|
||||
@@ -366,6 +389,7 @@ class _CountryNameDict(LazyDict):
|
||||
finally:
|
||||
zone_tab.close()
|
||||
|
||||
|
||||
country_names = _CountryNameDict()
|
||||
|
||||
|
||||
@@ -373,7 +397,7 @@ country_names = _CountryNameDict()
|
||||
|
||||
class _FixedOffset(datetime.tzinfo):
|
||||
|
||||
zone = None # to match the standard pytz API
|
||||
zone = None # to match the standard pytz API
|
||||
|
||||
def __init__(self, minutes):
|
||||
if abs(minutes) >= 1440:
|
||||
@@ -404,29 +428,31 @@ class _FixedOffset(datetime.tzinfo):
|
||||
|
||||
def normalize(self, dt, is_dst=False):
|
||||
'''Correct the timezone information on the given datetime'''
|
||||
if dt.tzinfo is self:
|
||||
return dt
|
||||
if dt.tzinfo is None:
|
||||
raise ValueError('Naive time - no tzinfo set')
|
||||
return dt.replace(tzinfo=self)
|
||||
return dt.astimezone(self)
|
||||
|
||||
|
||||
def FixedOffset(offset, _tzinfos = {}):
|
||||
def FixedOffset(offset, _tzinfos={}):
|
||||
"""return a fixed-offset timezone based off a number of minutes.
|
||||
|
||||
>>> one = FixedOffset(-330)
|
||||
>>> one
|
||||
pytz.FixedOffset(-330)
|
||||
>>> one.utcoffset(datetime.datetime.now())
|
||||
datetime.timedelta(-1, 66600)
|
||||
>>> one.dst(datetime.datetime.now())
|
||||
datetime.timedelta(0)
|
||||
>>> str(one.utcoffset(datetime.datetime.now()))
|
||||
'-1 day, 18:30:00'
|
||||
>>> str(one.dst(datetime.datetime.now()))
|
||||
'0:00:00'
|
||||
|
||||
>>> two = FixedOffset(1380)
|
||||
>>> two
|
||||
pytz.FixedOffset(1380)
|
||||
>>> two.utcoffset(datetime.datetime.now())
|
||||
datetime.timedelta(0, 82800)
|
||||
>>> two.dst(datetime.datetime.now())
|
||||
datetime.timedelta(0)
|
||||
>>> str(two.utcoffset(datetime.datetime.now()))
|
||||
'23:00:00'
|
||||
>>> str(two.dst(datetime.datetime.now()))
|
||||
'0:00:00'
|
||||
|
||||
The datetime.timedelta must be between the range of -1 and 1 day,
|
||||
non-inclusive.
|
||||
@@ -475,18 +501,19 @@ def FixedOffset(offset, _tzinfos = {}):
|
||||
|
||||
return info
|
||||
|
||||
|
||||
FixedOffset.__safe_for_unpickling__ = True
|
||||
|
||||
|
||||
def _test():
|
||||
import doctest, os, sys
|
||||
import doctest
|
||||
sys.path.insert(0, os.pardir)
|
||||
import pytz
|
||||
return doctest.testmod(pytz)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
_test()
|
||||
|
||||
all_timezones = \
|
||||
['Africa/Abidjan',
|
||||
'Africa/Accra',
|
||||
@@ -599,6 +626,7 @@ all_timezones = \
|
||||
'America/Eirunepe',
|
||||
'America/El_Salvador',
|
||||
'America/Ensenada',
|
||||
'America/Fort_Nelson',
|
||||
'America/Fort_Wayne',
|
||||
'America/Fortaleza',
|
||||
'America/Glace_Bay',
|
||||
@@ -662,6 +690,7 @@ all_timezones = \
|
||||
'America/North_Dakota/Beulah',
|
||||
'America/North_Dakota/Center',
|
||||
'America/North_Dakota/New_Salem',
|
||||
'America/Nuuk',
|
||||
'America/Ojinaga',
|
||||
'America/Panama',
|
||||
'America/Pangnirtung',
|
||||
@@ -672,6 +701,7 @@ all_timezones = \
|
||||
'America/Porto_Acre',
|
||||
'America/Porto_Velho',
|
||||
'America/Puerto_Rico',
|
||||
'America/Punta_Arenas',
|
||||
'America/Rainy_River',
|
||||
'America/Rankin_Inlet',
|
||||
'America/Recife',
|
||||
@@ -727,10 +757,12 @@ all_timezones = \
|
||||
'Asia/Aqtobe',
|
||||
'Asia/Ashgabat',
|
||||
'Asia/Ashkhabad',
|
||||
'Asia/Atyrau',
|
||||
'Asia/Baghdad',
|
||||
'Asia/Bahrain',
|
||||
'Asia/Baku',
|
||||
'Asia/Bangkok',
|
||||
'Asia/Barnaul',
|
||||
'Asia/Beirut',
|
||||
'Asia/Bishkek',
|
||||
'Asia/Brunei',
|
||||
@@ -746,6 +778,7 @@ all_timezones = \
|
||||
'Asia/Dili',
|
||||
'Asia/Dubai',
|
||||
'Asia/Dushanbe',
|
||||
'Asia/Famagusta',
|
||||
'Asia/Gaza',
|
||||
'Asia/Harbin',
|
||||
'Asia/Hebron',
|
||||
@@ -784,6 +817,7 @@ all_timezones = \
|
||||
'Asia/Pontianak',
|
||||
'Asia/Pyongyang',
|
||||
'Asia/Qatar',
|
||||
'Asia/Qostanay',
|
||||
'Asia/Qyzylorda',
|
||||
'Asia/Rangoon',
|
||||
'Asia/Riyadh',
|
||||
@@ -802,6 +836,7 @@ all_timezones = \
|
||||
'Asia/Thimbu',
|
||||
'Asia/Thimphu',
|
||||
'Asia/Tokyo',
|
||||
'Asia/Tomsk',
|
||||
'Asia/Ujung_Pandang',
|
||||
'Asia/Ulaanbaatar',
|
||||
'Asia/Ulan_Bator',
|
||||
@@ -810,6 +845,7 @@ all_timezones = \
|
||||
'Asia/Vientiane',
|
||||
'Asia/Vladivostok',
|
||||
'Asia/Yakutsk',
|
||||
'Asia/Yangon',
|
||||
'Asia/Yekaterinburg',
|
||||
'Asia/Yerevan',
|
||||
'Atlantic/Azores',
|
||||
@@ -855,7 +891,6 @@ all_timezones = \
|
||||
'CST6CDT',
|
||||
'Canada/Atlantic',
|
||||
'Canada/Central',
|
||||
'Canada/East-Saskatchewan',
|
||||
'Canada/Eastern',
|
||||
'Canada/Mountain',
|
||||
'Canada/Newfoundland',
|
||||
@@ -907,6 +942,7 @@ all_timezones = \
|
||||
'Etc/Zulu',
|
||||
'Europe/Amsterdam',
|
||||
'Europe/Andorra',
|
||||
'Europe/Astrakhan',
|
||||
'Europe/Athens',
|
||||
'Europe/Belfast',
|
||||
'Europe/Belgrade',
|
||||
@@ -927,6 +963,7 @@ all_timezones = \
|
||||
'Europe/Jersey',
|
||||
'Europe/Kaliningrad',
|
||||
'Europe/Kiev',
|
||||
'Europe/Kirov',
|
||||
'Europe/Lisbon',
|
||||
'Europe/Ljubljana',
|
||||
'Europe/London',
|
||||
@@ -947,6 +984,7 @@ all_timezones = \
|
||||
'Europe/Samara',
|
||||
'Europe/San_Marino',
|
||||
'Europe/Sarajevo',
|
||||
'Europe/Saratov',
|
||||
'Europe/Simferopol',
|
||||
'Europe/Skopje',
|
||||
'Europe/Sofia',
|
||||
@@ -954,6 +992,7 @@ all_timezones = \
|
||||
'Europe/Tallinn',
|
||||
'Europe/Tirane',
|
||||
'Europe/Tiraspol',
|
||||
'Europe/Ulyanovsk',
|
||||
'Europe/Uzhgorod',
|
||||
'Europe/Vaduz',
|
||||
'Europe/Vatican',
|
||||
@@ -1019,6 +1058,7 @@ all_timezones = \
|
||||
'Pacific/Guam',
|
||||
'Pacific/Honolulu',
|
||||
'Pacific/Johnston',
|
||||
'Pacific/Kanton',
|
||||
'Pacific/Kiritimati',
|
||||
'Pacific/Kosrae',
|
||||
'Pacific/Kwajalein',
|
||||
@@ -1063,7 +1103,6 @@ all_timezones = \
|
||||
'US/Michigan',
|
||||
'US/Mountain',
|
||||
'US/Pacific',
|
||||
'US/Pacific-New',
|
||||
'US/Samoa',
|
||||
'UTC',
|
||||
'Universal',
|
||||
@@ -1177,9 +1216,9 @@ common_timezones = \
|
||||
'America/Edmonton',
|
||||
'America/Eirunepe',
|
||||
'America/El_Salvador',
|
||||
'America/Fort_Nelson',
|
||||
'America/Fortaleza',
|
||||
'America/Glace_Bay',
|
||||
'America/Godthab',
|
||||
'America/Goose_Bay',
|
||||
'America/Grand_Turk',
|
||||
'America/Grenada',
|
||||
@@ -1224,7 +1263,6 @@ common_timezones = \
|
||||
'America/Moncton',
|
||||
'America/Monterrey',
|
||||
'America/Montevideo',
|
||||
'America/Montreal',
|
||||
'America/Montserrat',
|
||||
'America/Nassau',
|
||||
'America/New_York',
|
||||
@@ -1234,6 +1272,7 @@ common_timezones = \
|
||||
'America/North_Dakota/Beulah',
|
||||
'America/North_Dakota/Center',
|
||||
'America/North_Dakota/New_Salem',
|
||||
'America/Nuuk',
|
||||
'America/Ojinaga',
|
||||
'America/Panama',
|
||||
'America/Pangnirtung',
|
||||
@@ -1243,13 +1282,13 @@ common_timezones = \
|
||||
'America/Port_of_Spain',
|
||||
'America/Porto_Velho',
|
||||
'America/Puerto_Rico',
|
||||
'America/Punta_Arenas',
|
||||
'America/Rainy_River',
|
||||
'America/Rankin_Inlet',
|
||||
'America/Recife',
|
||||
'America/Regina',
|
||||
'America/Resolute',
|
||||
'America/Rio_Branco',
|
||||
'America/Santa_Isabel',
|
||||
'America/Santarem',
|
||||
'America/Santiago',
|
||||
'America/Santo_Domingo',
|
||||
@@ -1293,10 +1332,12 @@ common_timezones = \
|
||||
'Asia/Aqtau',
|
||||
'Asia/Aqtobe',
|
||||
'Asia/Ashgabat',
|
||||
'Asia/Atyrau',
|
||||
'Asia/Baghdad',
|
||||
'Asia/Bahrain',
|
||||
'Asia/Baku',
|
||||
'Asia/Bangkok',
|
||||
'Asia/Barnaul',
|
||||
'Asia/Beirut',
|
||||
'Asia/Bishkek',
|
||||
'Asia/Brunei',
|
||||
@@ -1308,6 +1349,7 @@ common_timezones = \
|
||||
'Asia/Dili',
|
||||
'Asia/Dubai',
|
||||
'Asia/Dushanbe',
|
||||
'Asia/Famagusta',
|
||||
'Asia/Gaza',
|
||||
'Asia/Hebron',
|
||||
'Asia/Ho_Chi_Minh',
|
||||
@@ -1341,8 +1383,8 @@ common_timezones = \
|
||||
'Asia/Pontianak',
|
||||
'Asia/Pyongyang',
|
||||
'Asia/Qatar',
|
||||
'Asia/Qostanay',
|
||||
'Asia/Qyzylorda',
|
||||
'Asia/Rangoon',
|
||||
'Asia/Riyadh',
|
||||
'Asia/Sakhalin',
|
||||
'Asia/Samarkand',
|
||||
@@ -1356,12 +1398,14 @@ common_timezones = \
|
||||
'Asia/Tehran',
|
||||
'Asia/Thimphu',
|
||||
'Asia/Tokyo',
|
||||
'Asia/Tomsk',
|
||||
'Asia/Ulaanbaatar',
|
||||
'Asia/Urumqi',
|
||||
'Asia/Ust-Nera',
|
||||
'Asia/Vientiane',
|
||||
'Asia/Vladivostok',
|
||||
'Asia/Yakutsk',
|
||||
'Asia/Yangon',
|
||||
'Asia/Yekaterinburg',
|
||||
'Asia/Yerevan',
|
||||
'Atlantic/Azores',
|
||||
@@ -1377,7 +1421,6 @@ common_timezones = \
|
||||
'Australia/Adelaide',
|
||||
'Australia/Brisbane',
|
||||
'Australia/Broken_Hill',
|
||||
'Australia/Currie',
|
||||
'Australia/Darwin',
|
||||
'Australia/Eucla',
|
||||
'Australia/Hobart',
|
||||
@@ -1394,6 +1437,7 @@ common_timezones = \
|
||||
'Canada/Pacific',
|
||||
'Europe/Amsterdam',
|
||||
'Europe/Andorra',
|
||||
'Europe/Astrakhan',
|
||||
'Europe/Athens',
|
||||
'Europe/Belgrade',
|
||||
'Europe/Berlin',
|
||||
@@ -1413,6 +1457,7 @@ common_timezones = \
|
||||
'Europe/Jersey',
|
||||
'Europe/Kaliningrad',
|
||||
'Europe/Kiev',
|
||||
'Europe/Kirov',
|
||||
'Europe/Lisbon',
|
||||
'Europe/Ljubljana',
|
||||
'Europe/London',
|
||||
@@ -1432,12 +1477,14 @@ common_timezones = \
|
||||
'Europe/Samara',
|
||||
'Europe/San_Marino',
|
||||
'Europe/Sarajevo',
|
||||
'Europe/Saratov',
|
||||
'Europe/Simferopol',
|
||||
'Europe/Skopje',
|
||||
'Europe/Sofia',
|
||||
'Europe/Stockholm',
|
||||
'Europe/Tallinn',
|
||||
'Europe/Tirane',
|
||||
'Europe/Ulyanovsk',
|
||||
'Europe/Uzhgorod',
|
||||
'Europe/Vaduz',
|
||||
'Europe/Vatican',
|
||||
@@ -1467,7 +1514,6 @@ common_timezones = \
|
||||
'Pacific/Chuuk',
|
||||
'Pacific/Easter',
|
||||
'Pacific/Efate',
|
||||
'Pacific/Enderbury',
|
||||
'Pacific/Fakaofo',
|
||||
'Pacific/Fiji',
|
||||
'Pacific/Funafuti',
|
||||
@@ -1476,7 +1522,7 @@ common_timezones = \
|
||||
'Pacific/Guadalcanal',
|
||||
'Pacific/Guam',
|
||||
'Pacific/Honolulu',
|
||||
'Pacific/Johnston',
|
||||
'Pacific/Kanton',
|
||||
'Pacific/Kiritimati',
|
||||
'Pacific/Kosrae',
|
||||
'Pacific/Kwajalein',
|
||||
|
||||
@@ -5,10 +5,14 @@ Custom exceptions raised by pytz.
|
||||
__all__ = [
|
||||
'UnknownTimeZoneError', 'InvalidTimeError', 'AmbiguousTimeError',
|
||||
'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.
|
||||
|
||||
>>> isinstance(UnknownTimeZoneError(), LookupError)
|
||||
@@ -20,11 +24,18 @@ class UnknownTimeZoneError(KeyError):
|
||||
|
||||
>>> isinstance(UnknownTimeZoneError(), KeyError)
|
||||
True
|
||||
|
||||
And also a subclass of pytz.exceptions.Error, as are other pytz
|
||||
exceptions.
|
||||
|
||||
>>> isinstance(UnknownTimeZoneError(), Error)
|
||||
True
|
||||
|
||||
'''
|
||||
pass
|
||||
|
||||
|
||||
class InvalidTimeError(Exception):
|
||||
class InvalidTimeError(Error):
|
||||
'''Base class for invalid time exceptions.'''
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
from threading import RLock
|
||||
try:
|
||||
from UserDict import DictMixin
|
||||
except ImportError:
|
||||
from collections 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
|
||||
@@ -13,6 +16,7 @@ _fill_lock = RLock()
|
||||
class LazyDict(DictMixin):
|
||||
"""Dictionary populated on first use."""
|
||||
data = None
|
||||
|
||||
def __getitem__(self, key):
|
||||
if self.data is None:
|
||||
_fill_lock.acquire()
|
||||
@@ -61,7 +65,7 @@ class LazyDict(DictMixin):
|
||||
self._fill()
|
||||
finally:
|
||||
_fill_lock.release()
|
||||
return list(self.data.keys())
|
||||
return self.data.keys()
|
||||
|
||||
|
||||
class LazyList(list):
|
||||
|
||||
@@ -5,17 +5,28 @@ Used for testing against as they are only correct for the years
|
||||
'''
|
||||
|
||||
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.
|
||||
# Note that FixedOffset(0, "UTC") is a different way to build a
|
||||
# UTC tzinfo object.
|
||||
|
||||
class FixedOffset(tzinfo):
|
||||
"""Fixed offset in minutes east from UTC."""
|
||||
|
||||
def __init__(self, offset, name):
|
||||
self.__offset = timedelta(minutes = offset)
|
||||
self.__offset = timedelta(minutes=offset)
|
||||
self.__name = name
|
||||
|
||||
def utcoffset(self, dt):
|
||||
@@ -27,18 +38,19 @@ class FixedOffset(tzinfo):
|
||||
def dst(self, dt):
|
||||
return ZERO
|
||||
|
||||
# A class capturing the platform's idea of local time.
|
||||
|
||||
import time as _time
|
||||
|
||||
STDOFFSET = timedelta(seconds = -_time.timezone)
|
||||
STDOFFSET = timedelta(seconds=-_time.timezone)
|
||||
if _time.daylight:
|
||||
DSTOFFSET = timedelta(seconds = -_time.altzone)
|
||||
DSTOFFSET = timedelta(seconds=-_time.altzone)
|
||||
else:
|
||||
DSTOFFSET = STDOFFSET
|
||||
|
||||
DSTDIFF = DSTOFFSET - STDOFFSET
|
||||
|
||||
|
||||
# A class capturing the platform's idea of local time.
|
||||
class LocalTimezone(tzinfo):
|
||||
|
||||
def utcoffset(self, dt):
|
||||
@@ -66,7 +78,6 @@ class LocalTimezone(tzinfo):
|
||||
|
||||
Local = LocalTimezone()
|
||||
|
||||
# A complete implementation of current DST rules for major US time zones.
|
||||
|
||||
def first_sunday_on_or_after(dt):
|
||||
days_to_go = 6 - dt.weekday()
|
||||
@@ -74,12 +85,15 @@ def first_sunday_on_or_after(dt):
|
||||
dt += timedelta(days_to_go)
|
||||
return dt
|
||||
|
||||
|
||||
# In the US, DST starts at 2am (standard time) on the first Sunday in April.
|
||||
DSTSTART = datetime(1, 4, 1, 2)
|
||||
# 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.
|
||||
DSTEND = datetime(1, 10, 25, 1)
|
||||
|
||||
|
||||
# A complete implementation of current DST rules for major US time zones.
|
||||
class USTimeZone(tzinfo):
|
||||
|
||||
def __init__(self, hours, reprname, stdname, dstname):
|
||||
@@ -120,8 +134,7 @@ class USTimeZone(tzinfo):
|
||||
else:
|
||||
return ZERO
|
||||
|
||||
Eastern = USTimeZone(-5, "Eastern", "EST", "EDT")
|
||||
Central = USTimeZone(-6, "Central", "CST", "CDT")
|
||||
Eastern = USTimeZone(-5, "Eastern", "EST", "EDT")
|
||||
Central = USTimeZone(-6, "Central", "CST", "CDT")
|
||||
Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
|
||||
Pacific = USTimeZone(-8, "Pacific", "PST", "PDT")
|
||||
|
||||
Pacific = USTimeZone(-8, "Pacific", "PST", "PDT")
|
||||
|
||||
@@ -1,40 +1,38 @@
|
||||
#!/usr/bin/env python
|
||||
'''
|
||||
$Id: tzfile.py,v 1.8 2004/06/03 00:15:24 zenzen Exp $
|
||||
'''
|
||||
|
||||
try:
|
||||
from io import StringIO
|
||||
except ImportError:
|
||||
from io import StringIO
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime
|
||||
from struct import unpack, calcsize
|
||||
|
||||
from pytz.tzinfo import StaticTzInfo, DstTzInfo, memorized_ttinfo
|
||||
from pytz.tzinfo import memorized_datetime, memorized_timedelta
|
||||
|
||||
|
||||
def _byte_string(s):
|
||||
"""Cast a string or byte string to an ASCII byte string."""
|
||||
return s.encode('US-ASCII')
|
||||
return s.encode('ASCII')
|
||||
|
||||
_NULL = _byte_string('\0')
|
||||
|
||||
|
||||
def _std_string(s):
|
||||
"""Cast a string or byte string to an ASCII string."""
|
||||
return str(s.decode('US-ASCII'))
|
||||
return str(s.decode('ASCII'))
|
||||
|
||||
|
||||
def build_tzinfo(zone, fp):
|
||||
head_fmt = '>4s c 15x 6l'
|
||||
head_size = calcsize(head_fmt)
|
||||
(magic, format, ttisgmtcnt, ttisstdcnt,leapcnt, timecnt,
|
||||
typecnt, charcnt) = unpack(head_fmt, fp.read(head_size))
|
||||
(magic, format, ttisgmtcnt, ttisstdcnt, leapcnt, timecnt,
|
||||
typecnt, charcnt) = unpack(head_fmt, fp.read(head_size))
|
||||
|
||||
# Make sure it is a tzfile(5) file
|
||||
assert magic == _byte_string('TZif'), 'Got magic %s' % repr(magic)
|
||||
|
||||
# Read out the transition times, localtime indices and ttinfo structures.
|
||||
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 = unpack(data_fmt, fp.read(data_size))
|
||||
|
||||
@@ -53,7 +51,7 @@ def build_tzinfo(zone, fp):
|
||||
i = 0
|
||||
while i < len(ttinfo_raw):
|
||||
# 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:
|
||||
nul = tznames_raw.find(_NULL, tzname_offset)
|
||||
if nul < 0:
|
||||
@@ -61,12 +59,12 @@ def build_tzinfo(zone, fp):
|
||||
tznames[tzname_offset] = _std_string(
|
||||
tznames_raw[tzname_offset:nul])
|
||||
ttinfo.append((ttinfo_raw[i],
|
||||
bool(ttinfo_raw[i+1]),
|
||||
bool(ttinfo_raw[i + 1]),
|
||||
tznames[tzname_offset]))
|
||||
i += 3
|
||||
|
||||
# Now build the timezone object
|
||||
if len(transitions) == 0:
|
||||
if len(ttinfo) == 1 or len(transitions) == 0:
|
||||
ttinfo[0][0], ttinfo[0][2]
|
||||
cls = type(zone, (StaticTzInfo,), dict(
|
||||
zone=zone,
|
||||
@@ -91,21 +89,21 @@ def build_tzinfo(zone, fp):
|
||||
if not inf[1]:
|
||||
dst = 0
|
||||
else:
|
||||
for j in range(i-1, -1, -1):
|
||||
for j in range(i - 1, -1, -1):
|
||||
prev_inf = ttinfo[lindexes[j]]
|
||||
if not prev_inf[1]:
|
||||
break
|
||||
dst = inf[0] - prev_inf[0] # dst offset
|
||||
dst = inf[0] - prev_inf[0] # dst offset
|
||||
|
||||
# Bad dst? Look further. DST > 24 hours happens when
|
||||
# a timzone has moved across the international dateline.
|
||||
if dst <= 0 or dst > 3600*3:
|
||||
for j in range(i+1, len(transitions)):
|
||||
if dst <= 0 or dst > 3600 * 3:
|
||||
for j in range(i + 1, len(transitions)):
|
||||
stdinf = ttinfo[lindexes[j]]
|
||||
if not stdinf[1]:
|
||||
dst = inf[0] - stdinf[0]
|
||||
if dst > 0:
|
||||
break # Found a useful std time.
|
||||
break # Found a useful std time.
|
||||
|
||||
tzname = inf[2]
|
||||
|
||||
@@ -129,9 +127,7 @@ if __name__ == '__main__':
|
||||
from pprint import pprint
|
||||
base = os.path.join(os.path.dirname(__file__), 'zoneinfo')
|
||||
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',
|
||||
open(os.path.join(base,'US','Eastern'), 'rb'))
|
||||
open(os.path.join(base, 'US', 'Eastern'), 'rb'))
|
||||
pprint(tz._utc_transition_times)
|
||||
#print tz.asPython(4)
|
||||
#print tz.transitions_mapping
|
||||
|
||||
@@ -13,6 +13,8 @@ from pytz.exceptions import AmbiguousTimeError, NonExistentTimeError
|
||||
__all__ = []
|
||||
|
||||
_timedelta_cache = {}
|
||||
|
||||
|
||||
def memorized_timedelta(seconds):
|
||||
'''Create only one instance of each distinct timedelta'''
|
||||
try:
|
||||
@@ -24,6 +26,8 @@ def memorized_timedelta(seconds):
|
||||
|
||||
_epoch = datetime.utcfromtimestamp(0)
|
||||
_datetime_cache = {0: _epoch}
|
||||
|
||||
|
||||
def memorized_datetime(seconds):
|
||||
'''Create only one instance of each distinct datetime'''
|
||||
try:
|
||||
@@ -36,21 +40,24 @@ def memorized_datetime(seconds):
|
||||
return dt
|
||||
|
||||
_ttinfo_cache = {}
|
||||
|
||||
|
||||
def memorized_ttinfo(*args):
|
||||
'''Create only one instance of each distinct tuple'''
|
||||
try:
|
||||
return _ttinfo_cache[args]
|
||||
except KeyError:
|
||||
ttinfo = (
|
||||
memorized_timedelta(args[0]),
|
||||
memorized_timedelta(args[1]),
|
||||
args[2]
|
||||
)
|
||||
memorized_timedelta(args[0]),
|
||||
memorized_timedelta(args[1]),
|
||||
args[2]
|
||||
)
|
||||
_ttinfo_cache[args] = ttinfo
|
||||
return ttinfo
|
||||
|
||||
_notime = memorized_timedelta(0)
|
||||
|
||||
|
||||
def _to_seconds(td):
|
||||
'''Convert a timedelta to seconds'''
|
||||
return td.seconds + td.days * 24 * 60 * 60
|
||||
@@ -154,14 +161,20 @@ class DstTzInfo(BaseTzInfo):
|
||||
timezone definition.
|
||||
'''
|
||||
# Overridden in subclass
|
||||
_utc_transition_times = None # Sorted list of DST transition times in UTC
|
||||
_transition_info = None # [(utcoffset, dstoffset, tzname)] corresponding
|
||||
# to _utc_transition_times entries
|
||||
|
||||
# Sorted list of DST transition times, UTC
|
||||
_utc_transition_times = None
|
||||
|
||||
# [(utcoffset, dstoffset, tzname)] corresponding to
|
||||
# _utc_transition_times entries
|
||||
_transition_info = None
|
||||
|
||||
zone = None
|
||||
|
||||
# Set in __init__
|
||||
|
||||
_tzinfos = None
|
||||
_dst = None # DST offset
|
||||
_dst = None # DST offset
|
||||
|
||||
def __init__(self, _inf=None, _tzinfos=None):
|
||||
if _inf:
|
||||
@@ -170,7 +183,8 @@ class DstTzInfo(BaseTzInfo):
|
||||
else:
|
||||
_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
|
||||
for inf in self._transition_info[1:]:
|
||||
if inf not in _tzinfos:
|
||||
@@ -178,8 +192,8 @@ class DstTzInfo(BaseTzInfo):
|
||||
|
||||
def fromutc(self, dt):
|
||||
'''See datetime.tzinfo.fromutc'''
|
||||
if (dt.tzinfo is not None
|
||||
and getattr(dt.tzinfo, '_tzinfos', None) is not self._tzinfos):
|
||||
if (dt.tzinfo is not None and
|
||||
getattr(dt.tzinfo, '_tzinfos', None) is not self._tzinfos):
|
||||
raise ValueError('fromutc: dt.tzinfo is not self')
|
||||
dt = dt.replace(tzinfo=None)
|
||||
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.
|
||||
else:
|
||||
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
|
||||
# is an ambiguous case occuring during the end-of-DST transition.
|
||||
@@ -351,9 +365,8 @@ class DstTzInfo(BaseTzInfo):
|
||||
# Filter out the possiblilities that don't match the requested
|
||||
# is_dst
|
||||
filtered_possible_loc_dt = [
|
||||
p for p in possible_loc_dt
|
||||
if bool(p.tzinfo._dst) == is_dst
|
||||
]
|
||||
p for p in possible_loc_dt if bool(p.tzinfo._dst) == is_dst
|
||||
]
|
||||
|
||||
# Hopefully we only have one possibility left. Return it.
|
||||
if len(filtered_possible_loc_dt) == 1:
|
||||
@@ -372,9 +385,10 @@ class DstTzInfo(BaseTzInfo):
|
||||
# Choose the earliest (by UTC) applicable timezone if is_dst=True
|
||||
# Choose the latest (by UTC) applicable timezone if is_dst=False
|
||||
# i.e., behave like end-of-DST transition
|
||||
dates = {} # utc -> local
|
||||
dates = {} # utc -> local
|
||||
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
|
||||
dates[utc_time] = local_dt
|
||||
return dates[[min, max][not is_dst](dates)]
|
||||
@@ -389,11 +403,11 @@ class DstTzInfo(BaseTzInfo):
|
||||
>>> tz = timezone('America/St_Johns')
|
||||
>>> ambiguous = datetime(2009, 10, 31, 23, 30)
|
||||
|
||||
>>> tz.utcoffset(ambiguous, is_dst=False)
|
||||
datetime.timedelta(-1, 73800)
|
||||
>>> str(tz.utcoffset(ambiguous, is_dst=False))
|
||||
'-1 day, 20:30:00'
|
||||
|
||||
>>> tz.utcoffset(ambiguous, is_dst=True)
|
||||
datetime.timedelta(-1, 77400)
|
||||
>>> str(tz.utcoffset(ambiguous, is_dst=True))
|
||||
'-1 day, 21:30:00'
|
||||
|
||||
>>> try:
|
||||
... tz.utcoffset(ambiguous)
|
||||
@@ -421,19 +435,19 @@ class DstTzInfo(BaseTzInfo):
|
||||
|
||||
>>> normal = datetime(2009, 9, 1)
|
||||
|
||||
>>> tz.dst(normal)
|
||||
datetime.timedelta(0, 3600)
|
||||
>>> tz.dst(normal, is_dst=False)
|
||||
datetime.timedelta(0, 3600)
|
||||
>>> tz.dst(normal, is_dst=True)
|
||||
datetime.timedelta(0, 3600)
|
||||
>>> str(tz.dst(normal))
|
||||
'1:00:00'
|
||||
>>> str(tz.dst(normal, is_dst=False))
|
||||
'1:00:00'
|
||||
>>> str(tz.dst(normal, is_dst=True))
|
||||
'1:00:00'
|
||||
|
||||
>>> ambiguous = datetime(2009, 10, 31, 23, 30)
|
||||
|
||||
>>> tz.dst(ambiguous, is_dst=False)
|
||||
datetime.timedelta(0)
|
||||
>>> tz.dst(ambiguous, is_dst=True)
|
||||
datetime.timedelta(0, 3600)
|
||||
>>> str(tz.dst(ambiguous, is_dst=False))
|
||||
'0:00:00'
|
||||
>>> str(tz.dst(ambiguous, is_dst=True))
|
||||
'1:00:00'
|
||||
>>> try:
|
||||
... tz.dst(ambiguous)
|
||||
... except AmbiguousTimeError:
|
||||
@@ -494,23 +508,22 @@ class DstTzInfo(BaseTzInfo):
|
||||
dst = 'STD'
|
||||
if self._utcoffset > _notime:
|
||||
return '<DstTzInfo %r %s+%s %s>' % (
|
||||
self.zone, self._tzname, self._utcoffset, dst
|
||||
)
|
||||
self.zone, self._tzname, self._utcoffset, dst
|
||||
)
|
||||
else:
|
||||
return '<DstTzInfo %r %s%s %s>' % (
|
||||
self.zone, self._tzname, self._utcoffset, dst
|
||||
)
|
||||
self.zone, self._tzname, self._utcoffset, dst
|
||||
)
|
||||
|
||||
def __reduce__(self):
|
||||
# Special pickle to zone remains a singleton and to cope with
|
||||
# database changes.
|
||||
return pytz._p, (
|
||||
self.zone,
|
||||
_to_seconds(self._utcoffset),
|
||||
_to_seconds(self._dst),
|
||||
self._tzname
|
||||
)
|
||||
|
||||
self.zone,
|
||||
_to_seconds(self._utcoffset),
|
||||
_to_seconds(self._dst),
|
||||
self._tzname
|
||||
)
|
||||
|
||||
|
||||
def unpickler(zone, utcoffset=None, dstoffset=None, tzname=None):
|
||||
@@ -548,9 +561,9 @@ def unpickler(zone, utcoffset=None, dstoffset=None, tzname=None):
|
||||
# See if we can find an entry differing only by tzname. Abbreviations
|
||||
# get changed from the initial guess by the database maintainers to
|
||||
# match reality when this information is discovered.
|
||||
for localized_tz in list(tz._tzinfos.values()):
|
||||
if (localized_tz._utcoffset == utcoffset
|
||||
and localized_tz._dst == dstoffset):
|
||||
for localized_tz in tz._tzinfos.values():
|
||||
if (localized_tz._utcoffset == utcoffset and
|
||||
localized_tz._dst == dstoffset):
|
||||
return localized_tz
|
||||
|
||||
# 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.
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
Reference in New Issue
Block a user