| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648 | Metadata-Version: 2.1Name: pytzVersion: 2025.2Summary: World timezone definitions, modern and historicalHome-page: http://pythonhosted.org/pytzDownload-URL: https://pypi.org/project/pytz/Author: Stuart BishopAuthor-email: stuart@stuartbishop.netMaintainer: Stuart BishopMaintainer-email: stuart@stuartbishop.netLicense: MITKeywords: timezone,tzinfo,datetime,olson,timePlatform: IndependentClassifier: Development Status :: 6 - MatureClassifier: Intended Audience :: DevelopersClassifier: License :: OSI Approved :: MIT LicenseClassifier: Natural Language :: EnglishClassifier: Operating System :: OS IndependentClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 2Classifier: Programming Language :: Python :: 2.4Classifier: Programming Language :: Python :: 2.5Classifier: Programming Language :: Python :: 2.6Classifier: Programming Language :: Python :: 2.7Classifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.1Classifier: Programming Language :: Python :: 3.2Classifier: Programming Language :: Python :: 3.3Classifier: Programming Language :: Python :: 3.4Classifier: Programming Language :: Python :: 3.5Classifier: Programming Language :: Python :: 3.6Classifier: Programming Language :: Python :: 3.7Classifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Topic :: Software Development :: Libraries :: Python ModulesLicense-File: LICENSE.txtpytz - World Timezone Definitions for Python============================================:Author: Stuart Bishop <stuart@stuartbishop.net>Introduction~~~~~~~~~~~~pytz brings the Olson tz database into Python. This library allowsaccurate and cross platform timezone calculations using Python 2.4or higher. It also solves the issue of ambiguous times at the endof daylight saving time, which you can read more about in the PythonLibrary Reference (``datetime.tzinfo``).Almost all of the Olson timezones are supported... note::    Projects using Python 3.9 or later should be using the support    now included as part of the standard library, and third party    packages work with it such as `tzdata <https://pypi.org/project/tzdata/>`_.    pytz offers no advantages beyond backwards compatibility with    code written for earlier versions of Python... 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 using ``pip`` or from a tarball using thestandard Python distutils.If you are installing using ``pip``, you don't need to download anything as thelatest version will be downloaded for you from PyPI::    pip install pytzIf you are installing from a tarball, run the following command as anadministrative user::    python setup.py installpytz for Enterprise~~~~~~~~~~~~~~~~~~~Available as part of the Tidelift Subscription.The maintainers of pytz and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. `Learn more. <https://tidelift.com/subscription/pkg/pypi-pytz?utm_source=pypi-pytz&utm_medium=referral&utm_campaign=enterprise&utm_term=repo>`_.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. Thefirst is to use the ``localize()`` method provided by the pytz library.This is used to localize a naive datetime (datetime with no timezoneinformation):>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0))>>> print(loc_dt.strftime(fmt))2002-10-27 06:00:00 EST-0500The second way of building a localized time is by converting an existinglocalized 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 datetimeconstructors ''does not work'' with pytz for many timezones.>>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=amsterdam).strftime(fmt)  # /!\ Does not work this way!'2002-10-27 12:00:00 LMT+0018'It is safe for timezones without daylight saving transitions though, suchas UTC:>>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=pytz.utc).strftime(fmt)  # /!\ Not recommended except for UTC'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 readby 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 localtimes, although it is more complicated than working in UTC as youneed to use the ``normalize()`` method to handle daylight saving timeand other timezone transitions. In this example, ``loc_dt`` is setto the instant when daylight saving time ends in the US/Easterntimezone.>>> 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 withlocal times is not recommended. Unfortunately, you cannot just passa ``tzinfo`` argument when constructing a datetime (see the nextsection 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 is more easily done, using thestandard astimezone method.>>> utc_dt = datetime.fromtimestamp(1143408899, tz=utc)>>> utc_dt.strftime(fmt)'2006-03-26 21:34:59 UTC+0000'>>> au_tz = timezone('Australia/Sydney')>>> au_dt = 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'>>> utc_dt == utc_dt2TrueYou can take shortcuts when dealing with the UTC side of timezoneconversions. ``normalize()`` and ``localize()`` are not reallynecessary when there are no daylight saving time transitions todeal with.>>> utc_dt = datetime.fromtimestamp(1143408899, tz=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 havebeen 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 usedduring DST transition ambiguous periods to resolve that ambiguity.>>> print(tz.utcoffset(normal, is_dst=True))-1 day, 21:30:00>>> print(tz.dst(normal, is_dst=True))1:00:00>>> tz.tzname(normal, is_dst=True)'NDT'>>> print(tz.utcoffset(ambiguous, is_dst=True))-1 day, 21:30:00>>> print(tz.dst(ambiguous, is_dst=True))1:00:00>>> tz.tzname(ambiguous, is_dst=True)'NDT'>>> print(tz.utcoffset(normal, is_dst=False))-1 day, 21:30:00>>> tz.dst(normal, is_dst=False).seconds3600>>> tz.tzname(normal, is_dst=False)'NDT'>>> print(tz.utcoffset(ambiguous, is_dst=False))-1 day, 20:30:00>>> 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 raisean ``pytz.exceptions.AmbiguousTimeError`` exception.>>> print(tz.utcoffset(normal))-1 day, 21:30:00>>> print(tz.dst(normal))1:00:00>>> 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:00Problems with Localtime~~~~~~~~~~~~~~~~~~~~~~~The major problem we have to deal with is that certain datetimesmay occur twice in a year. For example, in the US/Eastern timezoneon the last Sunday morning in October, the following sequencehappens:    - 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 meansthat if you try and create a time in the 'US/Eastern' timezonethe standard datetime syntax, there is no way to specify if you meantbefore of after the end-of-daylight-saving-time transition. Using thepytz 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 doesnot matter. However, if you are trying to schedule meetings with peoplein different timezones or analyze log files it is not acceptable.The best and simplest solution is to stick with using UTC.  The pytzpackage encourages using UTC for internal timezone representation byincluding a special UTC implementation based on the standard Pythonreference implementation in the Python documentation.The UTC timezone unpickles to be the same instance, and pickles to asmaller size than other pytz tzinfo instances.  The UTC implementationcan 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 == dtTrue>>> new is dtFalse>>> new.tzinfo is dt.tzinfoTrue>>> pytz.utc is pytz.UTC is pytz.timezone('UTC')TrueNote that some other timezones are commonly thought of as the same (GMT,Greenwich, Universal, etc.). The definition of UTC is distinct from theseother timezones, and they are not equivalent. For this reason, they willnot compare the same in Python.>>> utc == pytz.timezone('GMT')FalseSee the section `What is UTC`_, below.If you insist on working with local times, this library provides afacility 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-0500If you pass None as the is_dst flag to localize(), pytz will refuse toguess and raise exceptions if you try to build ambiguous or non-existenttimes.For example, 1:30am on 27th Oct 2002 happened twice in the US/Easterntimezone when the clocks where put back at the end of Daylight SavingTime:>>> 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:00Similarly, 2:30am on 7th April 2002 never happened at all in theUS/Eastern timezone, as the clocks where put forward at 2:00am skippingthe 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:00Both of these exceptions share a common base class to make error handlingeasier:>>> isinstance(pytz.AmbiguousTimeError(), pytz.InvalidTimeError)True>>> isinstance(pytz.NonExistentTimeError(), pytz.InvalidTimeError)TrueA special case is where countries change their timezone definitionswith no daylight savings time switch. For example, in 1915 Warsawswitched from Warsaw time to Central European time with no daylight savingstransition. So at the stroke of midnight on August 5th 1915 the clockswere wound back 24 minutes creating an ambiguous time period that cannotbe specified without referring to the timezone abbreviation or theactual UTC offset. In this case midnight happened twice, neither timeduring a daylight saving time period. pytz handles this transition bytreating the ambiguous period before the switch as daylight savingstime, 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 isby 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 tohandle them, such as demonstrated in this example using the US/Easterntimezone definition from the Python documentation (Note that thisimplementation only works for dates between 1987 and 2006 - it isincluded 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 arecorrect, but taking the UTC offset into account you find that they areactually 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 usefor a particular country, looked up using the ISO 3166 country code.It returns a list of strings that can be used to retrieve the relevanttzinfo instance using ``pytz.timezone()``:>>> print(' '.join(pytz.country_timezones['nz']))Pacific/Auckland Pacific/ChathamThe Olson database comes with a ISO 3166 country code to English countryname mapping that pytz exposes as a dictionary:>>> print(pytz.country_names['nz'])New ZealandWhat is UTC~~~~~~~~~~~'UTC' is `Coordinated Universal Time`_. It is a successor to, but distinctfrom, Greenwich Mean Time (GMT) and the various definitions of UniversalTime. UTC is now the worldwide standard for regulating clocks and timemeasurement.All other timezones are defined relative to UTC, and include offsets likeUTC+0800 - hours to add or subtract from UTC to derive the local time. Nodaylight saving time occurs in UTC, making it a useful timezone to performdate arithmetic without worrying about the confusion and ambiguities causedby daylight saving time transitions, your country changing its timezone, ormobile computers that roam through multiple timezones...  _Coordinated Universal Time: https://en.wikipedia.org/wiki/Coordinated_Universal_TimeHelpers~~~~~~~There are two lists of timezones provided.``all_timezones`` is the exhaustive list of the timezone names that canbe used.>>> from pytz import all_timezones>>> len(all_timezones) >= 500True>>> 'Etc/Greenwich' in all_timezonesTrue``common_timezones`` is a list of useful, current timezones. It doesn'tcontain deprecated zones or historical zones, except for a few I'vedeemed in common usage, such as US/Eastern (open a bug report if youthink other timezones are deserving of being included here). It is alsoa sequence of strings.>>> from pytz import common_timezones>>> len(common_timezones) < len(all_timezones)True>>> 'Etc/Greenwich' in common_timezonesFalse>>> 'Australia/Melbourne' in common_timezonesTrue>>> 'US/Eastern' in common_timezonesTrue>>> 'Canada/Eastern' in common_timezonesTrue>>> 'Australia/Yancowinna' in all_timezonesTrue>>> 'Australia/Yancowinna' in common_timezonesFalseBoth ``common_timezones`` and ``all_timezones`` are alphabeticallysorted:>>> common_timezones_dupe = common_timezones[:]>>> common_timezones_dupe.sort()>>> common_timezones == common_timezones_dupeTrue>>> all_timezones_dupe = all_timezones[:]>>> all_timezones_dupe.sort()>>> all_timezones == all_timezones_dupeTrue``all_timezones`` and ``common_timezones`` are also available as sets.>>> from pytz import all_timezones_set, common_timezones_set>>> 'US/Eastern' in all_timezones_setTrue>>> 'US/Eastern' in common_timezones_setTrue>>> 'Australia/Victoria' in common_timezones_setFalseYou can also retrieve lists of timezones used by particular countriesusing the ``country_timezones()`` function. It requires an ISO-3166two letter country code.>>> from pytz import country_timezones>>> print(' '.join(country_timezones('ch')))Europe/Zurich>>> print(' '.join(country_timezones('CH')))Europe/ZurichInternationalization - i18n/l10n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Pytz is an interface to the IANA database, which uses ASCII names. The `Unicode  Consortium's Unicode Locales (CLDR) <http://cldr.unicode.org>`_project provides translations. Python packages such as`Babel <https://babel.pocoo.org/en/latest/api/dates.html#timezone-functionality>`_and Thomas Khyn's `l18n <https://pypi.org/project/l18n/>`_ package can be usedto access these translations from Python.License~~~~~~~MIT license.This code is also available as part of Zope 3 under the Zope PublicLicense,  Version 2.1 (ZPL).I'm happy to relicense this code if necessary for inclusion in otheropen source projects.Latest Versions~~~~~~~~~~~~~~~This package will be updated after releases of the Olson timezonedatabase.  The latest version can be downloaded from the `Python PackageIndex <https://pypi.org/project/pytz/>`_.  The code that is usedto generate this distribution is hosted on Github and availableusing git::    git clone https://github.com/stub42/pytz.gitAnnouncements 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 should be reported on `Github <https://github.com/stub42/pytz/issues>`_.Feature requests are unlikely to be considered, and efforts instead directedto timezone support now built into Python or packages that work with it.Security Issues~~~~~~~~~~~~~~~Reports about security issues can be made via `Tidelift <https://tidelift.com/security>`_.Issues & Limitations~~~~~~~~~~~~~~~~~~~~- This project is in maintenance mode. Projects using Python 3.9 or later  are best served by using the timezone functionaly now included in core  Python and packages that work with it such as `tzdata <https://pypi.org/project/tzdata/>`_.- 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  was 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:https://data.iana.org/time-zones/tz-link.htmlContact~~~~~~~Stuart Bishop <stuart@stuartbishop.net>
 |