This PEP proposes the implementation of concrete time zone support in thePython standard library, and also improvements to the time zone API to dealwith ambiguous time specifications during DST changes.
After lengthy discussion it has turned out that the things I thought wasproblem in datetime’s implementation are intentional. Those includecompletely ignoring DST transitions when making date time arithmetic.That makes the is_dst flags part of this PEP pointless, as they wouldhave no useful function.datetime by design does not separate betweenambiguous datetimes and will never do so.
I therefore withdraw this PEP.
UPDATE: ThePEP 615 “Support for the IANA Time Zone Database in theStandard Library” added thezoneinfo module to Python 3.9 andsuperseded this PEP.
The time zone support in Python has no concrete implementation in thestandard library outside of a tzinfo baseclass that supports fixed offsets.To properly support time zones you need to include a database over all timezones, both current and historical, including daylight saving changes.But such information changes frequently, so even if we include the lastinformation in a Python release, that information would be outdated just afew months later.
Time zone support has therefore only been available through two third-partymodules,pytz anddateutil, both who include and wrap the “zoneinfo”database. This database, also called “tz” or “The Olsen database”, is thede facto standard time zone database over time zones, and it is included inmost Unix and Unix-like operating systems, including OS X.
This gives us the opportunity to include the code that supports the zoneinfodata in the standard library, but by default use the operating system’s copyof the data, which typically will be kept updated by the updating mechanismof the operating system or distribution.
For those who have an operating system that does not include the zoneinfodatabase, for example Windows, the Python source distribution will include acopy of the zoneinfo database, and a distribution containing the latestzoneinfo database will also be available at the Python Package Index, so itcan be easily installed with the Python packaging tools such aseasy_install orpip. This could also be done on Unices that are nolonger receiving updates and therefore have an outdated database.
With such a mechanism Python would have full-time zone support in thestandard library on any platform, and a simple package installation wouldprovide an updated time zone database on those platforms where the zoneinfodatabase isn’t included, such as Windows, or on platforms where OS updatesare no longer provided.
The time zone support will be implemented by making thedatetime moduleinto a package, and adding time zone support todatetime based on StuartBishop’spytz module.
On Unix there is no standard way of finding the name of the time zone that isbeing used. All the information that is available is the time zoneabbreviations, such asEST andPDT, but many of those abbreviationsare ambiguous and therefore you can’t rely on them to figure out which timezone you are located in.
There is however a standard for finding the compiled time zone informationsince it’s located in/etc/localtime. Therefore, it is possible to createa local time zone object with the correct time zone information even thoughyou don’t know the name of the time zone. A function indatetime shouldbe provided to return the local time zone.
The support for this will be made by integrating Lennart Regebro’stzlocal module into the newdatetime module.
For Windows it will look up the local Windows time zone name, and use amapping between Windows time zone names and zoneinfo time zone names providedby the Unicode consortium to convert that to a zoneinfo time zone.
The mapping should be updated before each major or bugfix release, scriptsfor doing so will be provided in theTools/ directory.
When changing over from daylight savings time (DST) the clock is turned backone hour. This means that the times during that hour happens twice, oncewith DST and then once without DST. Similarly, when changing to daylightsavings time, one hour goes missing.
The current time zone API can not differentiate between the two ambiguoustimes during a change from DST. For example, in Stockholm the time of2012-11-28 02:00:00 happens twice, both at UTC 2012-11-28 00:00:00 and alsoat 2012-11-28 01:00:00.
The current time zone API can not disambiguate this and therefore it’sunclear which time should be returned:
# This could be either 00:00 or 01:00 UTC:>>>dt=datetime(2012,10,28,2,0,tzinfo=zoneinfo('Europe/Stockholm'))# But we can not specify which:>>>dt.astimezone(zoneinfo('UTC'))datetime.datetime(2012,10,28,1,0,tzinfo=<UTC>)
pytz solved this problem by addingis_dst parameters to severalmethods of the tzinfo objects to make it possible to disambiguate times whenthis is desired.
This PEP proposes to add theseis_dst parameters to the relevant methodsof thedatetime API, and therefore add this functionality directly todatetime. This is likely the hardest part of this PEP as this involvesupdating the C version of thedatetime library with this functionality,as this involved writing new code, and not just reorganizing existingexternal libraries.
The latest version of the zoneinfo database should exist in theLib/tzdata directory of the Python source control system. This copy ofthe database should be updated before every Python feature and bug-fixrelease, but not for releases of Python versions that are insecurity-fix-only-mode.
Scripts to update the database will be provided inTools/, and therelease instructions will be updated to include this update.
New configure options--enable-internal-timezone-database and--disable-internal-timezone-database will be implemented to enable anddisable the installation of this database when installing from source. Asource install will default to installing them.
Binary installers for systems that have a system-provided zoneinfo databasemay skip installing the included database since it would never be used forthese platforms. For other platforms, for example Windows, binary installersmust install the included database.
datetime-moduleThe public API of the new time zone support contains one new class, one newfunction, one new exception and four new collections. In addition to this, severalmethods on the datetime object gets a newis_dst parameter.
dsttimezoneThis class provides a concrete implementation of thetzinfo baseclass that implements DST support.
zoneinfo(name=None,db_path=None)This function takes a name string that must be a string specifying avalid zoneinfo time zone, i.e. “US/Eastern”, “Europe/Warsaw” or “Etc/GMT”.If not given, the local time zone will be looked up. If an invalid zone nameis given, or the local time zone can not be retrieved, the function raisesUnknownTimeZoneError.
The function also takes an optional path to the location of the zoneinfodatabase which should be used. If not specified, the function will look fordatabases in the following order:
tzdata-update module is installed, and then use thatdatabase./usr/share/zoneinfo, if it exists.Lib/tzdata.If no database is found anUnknownTimeZoneError or subclass thereof willbe raised with a message explaining that no zoneinfo database can be found,but that you can install one with thetzdata-update package.
is_dstA newis_dst parameter is added to several methods to handle timeambiguity during DST changeovers.
tzinfo.utcoffset(dt,is_dst=False)tzinfo.dst(dt,is_dst=False)tzinfo.tzname(dt,is_dst=False)datetime.astimezone(tz,is_dst=False)Theis_dst parameter can beFalse (default),True, orNone.
False will specify that the given datetime should be interpreted as nothappening during daylight savings time, i.e. that the time specified is afterthe change from DST. This is default to preserve existing behavior.
True will specify that the given datetime should be interpreted as happeningduring daylight savings time, i.e. that the time specified is before the changefrom DST.
None will raise anAmbiguousTimeError exception if the time specifiedwas during a DST change over. It will also raise aNonExistentTimeErrorif a time is specified during the “missing time” in a change to DST.
UnknownTimeZoneErrorThis exception is a subclass of KeyError and raised when giving a timezone specification that can’t be found:
>>>datetime.zoneinfo('Europe/New_York')Traceback (most recent call last):...UnknownTimeZoneError:There is no time zone called 'Europe/New_York'
InvalidTimeErrorThis exception serves as a base forAmbiguousTimeError andNonExistentTimeError, to enable you to trap these two separately. Itwill subclass from ValueError, so that you can catch these errors togetherwith inputs like the 29th of February 2011.
AmbiguousTimeErrorThis exception is raised when giving a datetime specification that is ambiguouswhile settingis_dst to None:
>>>datetime(2012,11,28,2,0,tzinfo=zoneinfo('Europe/Stockholm'),is_dst=None)>>>Traceback (most recent call last):...AmbiguousTimeError:2012-10-28 02:00:00 is ambiguous in time zone Europe/Stockholm
NonExistentTimeErrorThis exception is raised when giving a datetime specification for a time that due todaylight saving does not exist, while settingis_dst to None:
>>>datetime(2012,3,25,2,0,tzinfo=zoneinfo('Europe/Stockholm'),is_dst=None)>>>Traceback (most recent call last):...NonExistentTimeError:2012-03-25 02:00:00 does not exist in time zone Europe/Stockholm
all_timezones is the exhaustive list of the time zone names that canbe used, listed alphabetically.common_timezones is a list of useful, current time zones, listedalphabetically.tzdata-update-packageThe zoneinfo database will be packaged for easy installation witheasy_install/pip/buildout. This package will not install anyPython code, and will not contain any Python code except that which is neededfor installation.
It will be kept updated with the same tools as the internal database, butreleased whenever thezoneinfo-database is updated, and use the sameversion schema.
pytz APIpytz has the functionslocalize() andnormalize() to workaround thattzinfo doesn’t have is_dst. Whenis_dst isimplemented directly indatetime.tzinfo they are no longer needed.timezone() function is calledzoneinfo() to avoid clashing withthetimezone class introduced in Python 3.2.zoneinfo() will return the local time zone if called without arguments.pytz.StaticTzInfo is there to provide theis_dst support for statictime zones. Whenis_dst support is included indatetime.tzinfo it is no longer needed.InvalidTimeError subclasses fromValueError.This document has been placed in the public domain.
Source:https://github.com/python/peps/blob/main/peps/pep-0431.rst
Last modified:2025-02-01 08:59:27 GMT