Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
PyPI

pytz 2019.3

pip install pytz==2019.3

Newer version available (2025.2)

Released:

World timezone definitions, modern and historical

Verified details

These details have beenverified by PyPI
Maintainers
Avatar for stub from gravatar.com stub

Unverified details

These details havenot been verified by PyPI
Project links
Meta

Project description

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

This library differs from the documented Python API fortzinfo implementations; if you want to create local wallclocktimes you need to use thelocalize() method documented in thisdocument. In addition, if you perform date arithmetic on localtimes that cross DST boundaries, the result may be in an incorrecttimezone (ie. subtract 1 minute from 2002-10-27 1:00 EST and you get2002-10-27 0:59 EST instead of the correct 2002-10-27 1:59 EDT). Anormalize() method is provided to correct this. Unfortunately theseissues cannot be resolved without modifying the Python datetimeimplementation (see PEP-431).

Installation

This package can either be installed usingpip or from a tarball using thestandard Python distutils.

If you are installing usingpip, you don’t need to download anything as thelatest version will be downloaded for you from PyPI:

pip install pytz

If you are installing from a tarball, run the following command as anadministrative user:

python setup.py install

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 thelocalize() 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-0500

The second way of building a localized time is by converting an existinglocalized time using the standardastimezone() 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+0020'

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 thenormalize() 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 passatzinfo 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 = utc.localize(datetime.utcfromtimestamp(1143408899))>>> 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_dt2True

You can take shortcuts when dealing with the UTC side of timezoneconversions.normalize() andlocalize() are not reallynecessary when there are no daylight saving time transitions todeal 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

Thetzinfo instances returned by thetimezone() function havebeen extended to cope with ambiguous times by adding anis_dstparameter to theutcoffset(),dst() &&tzname() methods.

>>> tz = timezone('America/St_Johns')
>>> normal = datetime(2009, 9, 1)>>> ambiguous = datetime(2009, 10, 31, 23, 30)

Theis_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)datetime.timedelta(0, 3600)>>> 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'

Ifis_dst is not specified, ambiguous timestamps will raiseanpytz.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:00

Problems 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:

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')True

Note 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')False

See the sectionWhat 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-0500

If 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:00

Similarly, 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:00

Both of these exceptions share a common base class to make error handlingeasier:

>>> isinstance(pytz.AmbiguousTimeError(), pytz.InvalidTimeError)True>>> isinstance(pytz.NonExistentTimeError(), pytz.InvalidTimeError)True

A 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 usingpytz.timezone():

>>> print(' '.join(pytz.country_timezones['nz']))Pacific/Auckland Pacific/Chatham

The 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 Zealand

What is UTC

‘UTC’ isCoordinated 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.

Helpers

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_timezonesFalse

Bothcommon_timezones andall_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 andcommon_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_setFalse

You can also retrieve lists of timezones used by particular countriesusing thecountry_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/Zurich

Internationalization - i18n/l10n

Pytz is an interface to the IANA database, which uses ASCII names. TheUnicode Consortium’s Unicode Locales (CLDR)project provides translations. Thomas Khyn’sl18n package can be used to accessthese 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 thePython PackageIndex. The code that is usedto generate this distribution is hosted on launchpad.net and availableusing git:

git clone https://git.launchpad.net/pytz

A mirror on github is also available athttps://github.com/stub42/pytz

Announcements of new releases are made onLaunchpad, and theAtom feedhosted there.

Bugs, Feature Requests & Patches

Bugs can be reported usingLaunchpad.

Issues & Limitations

  • Offsets from UTC are rounded to the nearest whole minute, so timezonessuch as Europe/Amsterdam pre 1937 will be up to 30 seconds out. Thisis a limitation of the Python datetime library.

  • If you think a timezone definition is incorrect, I probably can’t fixit. pytz is a direct translation of the Olson timezone database, andchanges to the timezone definitions need to be made to this source.If you find errors they should be reported to the time zone mailinglist, linked fromhttp://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>

Project details

Verified details

These details have beenverified by PyPI
Maintainers
Avatar for stub from gravatar.com stub

Unverified details

These details havenot been verified by PyPI
Project links
Meta

Release historyRelease notifications |RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more aboutinstalling packages.

Source Distribution

pytz-2019.3.tar.gz (312.3 kBview details)

UploadedSource

Built Distribution

pytz-2019.3-py2.py3-none-any.whl (509.2 kBview details)

UploadedPython 2Python 3

File details

Details for the filepytz-2019.3.tar.gz.

File metadata

  • Download URL: pytz-2019.3.tar.gz
  • Upload date:
  • Size: 312.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.18.4 setuptools/39.0.1 requests-toolbelt/0.8.0 tqdm/4.21.0 CPython/3.6.8

File hashes

Hashes for pytz-2019.3.tar.gz
AlgorithmHash digest
SHA256b02c06db6cf09c12dd25137e563b31700d3b80fcc4ad23abb7a315f2789819be
MD5c3d84a465fc56a4edd52cca8873ac0df
BLAKE2b-25682c3534ddba230bd4fbbd3b7a3d35f3341d014cca213f369a9940925e7e5f691

See more details on using hashes here.

File details

Details for the filepytz-2019.3-py2.py3-none-any.whl.

File metadata

  • Download URL: pytz-2019.3-py2.py3-none-any.whl
  • Upload date:
  • Size: 509.2 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.18.4 setuptools/39.0.1 requests-toolbelt/0.8.0 tqdm/4.21.0 CPython/3.6.8

File hashes

Hashes for pytz-2019.3-py2.py3-none-any.whl
AlgorithmHash digest
SHA2561c557d7d0e871de1f5ccd5833f60fb2550652da6be2693c1e02300743d21500d
MD5cb3da4cc0427d718d2478350e0b4b169
BLAKE2b-256e7f9f0b53f88060247251bf481fa6ea62cd0d25bf1b11a87888e53ce5b7c8ad2

See more details on using hashes here.

Supported by

AWSAWS Cloud computing and Security SponsorDatadogDatadog MonitoringFastlyFastly CDNGoogleGoogle Download AnalyticsPingdomPingdom MonitoringSentrySentry Error loggingStatusPageStatusPage Status page

[8]ページ先頭

©2009-2025 Movatter.jp