pytz 2025.2
pip install pytz
Released:
World timezone definitions, modern and historical
Navigation
Unverified details
These details havenot been verified by PyPIProject links
Meta
- License: MIT License (MIT)
- Author:Stuart Bishop
- Maintainer:Stuart Bishop
- Tags timezone, tzinfo, datetime, olson, time
Classifiers
- Development Status
- Intended Audience
- License
- Natural Language
- Operating System
- Programming Language
- Topic
Project description
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 supportnow included as part of the standard library, and third partypackages work with it such astzdata.pytz offers no advantages beyond backwards compatibility withcode written for earlier versions of Python.
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
pytz 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..
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+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 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 = 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_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.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
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).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'
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:
01:00 EDT occurs
1 hour later, instead of 2:00am the clock is turned back 1 hourand 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')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. Python packages such asBabeland Thomas Khyn’sl18n 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 thePython PackageIndex. The code that is usedto generate this distribution is hosted on Github and availableusing git:
git clone https://github.com/stub42/pytz.git
Announcements of new releases are made onLaunchpad, and theAtom feedhosted there.
Bugs, Feature Requests & Patches
Bugs should be reported onGithub.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 viaTidelift.
Issues & Limitations
This project is in maintenance mode. Projects using Python 3.9 or laterare best served by using the timezone functionaly now included in corePython and packages that work with it such astzdata.
Offsets from UTC are rounded to the nearest whole minute, so timezonessuch as Europe/Amsterdam pre 1937 will be up to 30 seconds out. Thiswas 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:https://data.iana.org/time-zones/tz-link.html
Contact
Stuart Bishop <stuart@stuartbishop.net>
Project details
Unverified details
These details havenot been verified by PyPIProject links
Meta
- License: MIT License (MIT)
- Author:Stuart Bishop
- Maintainer:Stuart Bishop
- Tags timezone, tzinfo, datetime, olson, time
Classifiers
- Development Status
- Intended Audience
- License
- Natural Language
- Operating System
- Programming Language
- Topic
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
Built Distribution
File details
Details for the filepytz-2025.2.tar.gz
.
File metadata
- Download URL: pytz-2025.2.tar.gz
- Upload date:
- Size: 320.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 360b9e3dbb49a209c21ad61809c7fb453643e048b38924c765813546746e81c3 | |
MD5 | 6a7760c71e38b6c75577b34b18b89d5b | |
BLAKE2b-256 | f8bfabbd3cdfb8fbc7fb3d4d38d320f2441b1e7cbe29be4f23797b4a2b5d8aac |
Provenance
The following attestation bundles were made forpytz-2025.2.tar.gz
:
Publisher:publish.yml
on stub42/pytz
- Statement:
- Statement type:
https://in-toto.io/Statement/v1
- Predicate type:
https://docs.pypi.org/attestations/publish/v1
- Subject name:
pytz-2025.2.tar.gz
- Subject digest:
360b9e3dbb49a209c21ad61809c7fb453643e048b38924c765813546746e81c3
- Sigstore transparency entry:187526004
- Sigstore integration time:
- Permalink:
stub42/pytz@82e0891730a38fdcf8c9c680af34712d45a97fde
- Branch / Tag:
refs/tags/release_2025.2
- Owner:https://github.com/stub42
- Access:
public
- Token Issuer:
https://token.actions.githubusercontent.com
- Runner Environment:
github-hosted
- Publication workflow:
publish.yml@82e0891730a38fdcf8c9c680af34712d45a97fde
- Trigger Event:
push
- Statement type:
File details
Details for the filepytz-2025.2-py2.py3-none-any.whl
.
File metadata
- Download URL: pytz-2025.2-py2.py3-none-any.whl
- Upload date:
- Size: 509.2 kB
- Tags: Python 2, Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 5ddf76296dd8c44c26eb8f4b6f35488f3ccbf6fbbd7adee0b7262d43f0ec2f00 | |
MD5 | 51ad498990b93bab1efdb6ecce983474 | |
BLAKE2b-256 | 81c434e93fe5f5429d7570ec1fa436f1986fb1f00c3e0f43a589fe2bbcd22c3f |
Provenance
The following attestation bundles were made forpytz-2025.2-py2.py3-none-any.whl
:
Publisher:publish.yml
on stub42/pytz
- Statement:
- Statement type:
https://in-toto.io/Statement/v1
- Predicate type:
https://docs.pypi.org/attestations/publish/v1
- Subject name:
pytz-2025.2-py2.py3-none-any.whl
- Subject digest:
5ddf76296dd8c44c26eb8f4b6f35488f3ccbf6fbbd7adee0b7262d43f0ec2f00
- Sigstore transparency entry:187526005
- Sigstore integration time:
- Permalink:
stub42/pytz@82e0891730a38fdcf8c9c680af34712d45a97fde
- Branch / Tag:
refs/tags/release_2025.2
- Owner:https://github.com/stub42
- Access:
public
- Token Issuer:
https://token.actions.githubusercontent.com
- Runner Environment:
github-hosted
- Publication workflow:
publish.yml@82e0891730a38fdcf8c9c680af34712d45a97fde
- Trigger Event:
push
- Statement type: