Debian Codegraph @

Doc/library/zoneinfo.rst

raw
1 :mod:`!zoneinfo` --- IANA time zone support
2 ===========================================
3
4 .. module:: zoneinfo
5 :synopsis: IANA time zone support
6
7 .. versionadded:: 3.9
8
9 .. moduleauthor:: Paul Ganssle <[email protected]>
10 .. sectionauthor:: Paul Ganssle <[email protected]>
11
12 **Source code:** :source:`Lib/zoneinfo`
13
14 --------------
15
16 The :mod:`zoneinfo` module provides a concrete time zone implementation to
17 support the IANA time zone database as originally specified in :pep:`615`. By
18 default, :mod:`zoneinfo` uses the system's time zone data if available; if no
19 system time zone data is available, the library will fall back to using the
20 first-party :pypi:`tzdata` package available on PyPI.
21
22 .. seealso::
23
24 Module: :mod:`datetime`
25 Provides the :class:`~datetime.time` and :class:`~datetime.datetime`
26 types with which the :class:`ZoneInfo` class is designed to be used.
27
28 Package :pypi:`tzdata`
29 First-party package maintained by the CPython core developers to supply
30 time zone data via PyPI.
31
32 .. include:: ../includes/wasm-notavail.rst
33
34 Using ``ZoneInfo``
35 ------------------
36
37 :class:`ZoneInfo` is a concrete implementation of the :class:`datetime.tzinfo`
38 abstract base class, and is intended to be attached to ``tzinfo``, either via
39 the constructor, the :meth:`datetime.replace <datetime.datetime.replace>`
40 method or :meth:`datetime.astimezone <datetime.datetime.astimezone>`::
41
42 >>> from zoneinfo import ZoneInfo
43 >>> from datetime import datetime, timedelta
44
45 >>> dt = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles"))
46 >>> print(dt)
47 2020-10-31 12:00:00-07:00
48
49 >>> dt.tzname()
50 'PDT'
51
52 Datetimes constructed in this way are compatible with datetime arithmetic and
53 handle daylight saving time transitions with no further intervention::
54
55 >>> dt_add = dt + timedelta(days=1)
56
57 >>> print(dt_add)
58 2020-11-01 12:00:00-08:00
59
60 >>> dt_add.tzname()
61 'PST'
62
63 These time zones also support the :attr:`~datetime.datetime.fold` attribute
64 introduced in :pep:`495`. During offset transitions which induce ambiguous
65 times (such as a daylight saving time to standard time transition), the offset
66 from *before* the transition is used when ``fold=0``, and the offset *after*
67 the transition is used when ``fold=1``, for example::
68
69 >>> dt = datetime(2020, 11, 1, 1, tzinfo=ZoneInfo("America/Los_Angeles"))
70 >>> print(dt)
71 2020-11-01 01:00:00-07:00
72
73 >>> print(dt.replace(fold=1))
74 2020-11-01 01:00:00-08:00
75
76 When converting from another time zone, the fold will be set to the correct
77 value::
78
79 >>> from datetime import timezone
80 >>> LOS_ANGELES = ZoneInfo("America/Los_Angeles")
81 >>> dt_utc = datetime(2020, 11, 1, 8, tzinfo=timezone.utc)
82
83 >>> # Before the PDT -> PST transition
84 >>> print(dt_utc.astimezone(LOS_ANGELES))
85 2020-11-01 01:00:00-07:00
86
87 >>> # After the PDT -> PST transition
88 >>> print((dt_utc + timedelta(hours=1)).astimezone(LOS_ANGELES))
89 2020-11-01 01:00:00-08:00
90
91 Data sources
92 ------------
93
94 The ``zoneinfo`` module does not directly provide time zone data, and instead
95 pulls time zone information from the system time zone database or the
96 first-party PyPI package :pypi:`tzdata`, if available. Some systems, including
97 notably Windows systems, do not have an IANA database available, and so for
98 projects targeting cross-platform compatibility that require time zone data, it
99 is recommended to declare a dependency on tzdata. If neither system data nor
100 tzdata are available, all calls to :class:`ZoneInfo` will raise
101 :exc:`ZoneInfoNotFoundError`.
102
103 .. _zoneinfo_data_configuration:
104
105 Configuring the data sources
106 ****************************
107
108 When ``ZoneInfo(key)`` is called, the constructor first searches the
109 directories specified in :data:`TZPATH` for a file matching ``key``, and on
110 failure looks for a match in the tzdata package. This behavior can be
111 configured in three ways:
112
113 1. The default :data:`TZPATH` when not otherwise specified can be configured at
114 :ref:`compile time <zoneinfo_data_compile_time_config>`.
115 2. :data:`TZPATH` can be configured using :ref:`an environment variable
116 <zoneinfo_data_environment_var>`.
117 3. At :ref:`runtime <zoneinfo_data_runtime_config>`, the search path can be
118 manipulated using the :func:`reset_tzpath` function.
119
120 .. _zoneinfo_data_compile_time_config:
121
122 Compile-time configuration
123 ^^^^^^^^^^^^^^^^^^^^^^^^^^
124
125 The default :data:`TZPATH` includes several common deployment locations for the
126 time zone database (except on Windows, where there are no "well-known"
127 locations for time zone data). On POSIX systems, downstream distributors and
128 those building Python from source who know where their system
129 time zone data is deployed may change the default time zone path by specifying
130 the compile-time option ``TZPATH`` (or, more likely, the :option:`configure
131 flag --with-tzpath <--with-tzpath>`), which should be a string delimited by
132 :data:`os.pathsep`.
133
134 On all platforms, the configured value is available as the ``TZPATH`` key in
135 :func:`sysconfig.get_config_var`.
136
137 .. _zoneinfo_data_environment_var:
138
139 Environment configuration
140 ^^^^^^^^^^^^^^^^^^^^^^^^^
141
142 When initializing :data:`TZPATH` (either at import time or whenever
143 :func:`reset_tzpath` is called with no arguments), the ``zoneinfo`` module will
144 use the environment variable ``PYTHONTZPATH``, if it exists, to set the search
145 path.
146
147 .. envvar:: PYTHONTZPATH
148
149 This is an :data:`os.pathsep`-separated string containing the time zone
150 search path to use. It must consist of only absolute rather than relative
151 paths. Relative components specified in ``PYTHONTZPATH`` will not be used,
152 but otherwise the behavior when a relative path is specified is
153 implementation-defined; CPython will raise :exc:`InvalidTZPathWarning`, but
154 other implementations are free to silently ignore the erroneous component
155 or raise an exception.
156
157 To set the system to ignore the system data and use the tzdata package
158 instead, set ``PYTHONTZPATH=""``.
159
160 .. _zoneinfo_data_runtime_config:
161
162 Runtime configuration
163 ^^^^^^^^^^^^^^^^^^^^^
164
165 The TZ search path can also be configured at runtime using the
166 :func:`reset_tzpath` function. This is generally not an advisable operation,
167 though it is reasonable to use it in test functions that require the use of a
168 specific time zone path (or require disabling access to the system time zones).
169
170
171 The ``ZoneInfo`` class
172 ----------------------
173
174 .. class:: ZoneInfo(key)
175
176 A concrete :class:`datetime.tzinfo` subclass that represents an IANA time
177 zone specified by the string ``key``. Calls to the primary constructor will
178 always return objects that compare identically; put another way, barring
179 cache invalidation via :meth:`ZoneInfo.clear_cache`, for all values of
180 ``key``, the following assertion will always be true:
181
182 .. code-block:: python
183
184 a = ZoneInfo(key)
185 b = ZoneInfo(key)
186 assert a is b
187
188 ``key`` must be in the form of a relative, normalized POSIX path, with no
189 up-level references. The constructor will raise :exc:`ValueError` if a
190 non-conforming key is passed.
191
192 If no file matching ``key`` is found, the constructor will raise
193 :exc:`ZoneInfoNotFoundError`.
194
195
196 The ``ZoneInfo`` class has two alternate constructors:
197
198 .. classmethod:: ZoneInfo.from_file(file_obj, /, key=None)
199
200 Constructs a ``ZoneInfo`` object from a file-like object returning bytes
201 (e.g. a file opened in binary mode or an :class:`io.BytesIO` object).
202 Unlike the primary constructor, this always constructs a new object.
203
204 The ``key`` parameter sets the name of the zone for the purposes of
205 :py:meth:`~object.__str__` and :py:meth:`~object.__repr__`.
206
207 Objects created via this constructor cannot be pickled (see `pickling`_).
208
209 :exc:`ValueError` is raised if the data read from *file_obj* is not a valid
210 TZif file.
211
212 .. classmethod:: ZoneInfo.no_cache(key)
213
214 An alternate constructor that bypasses the constructor's cache. It is
215 identical to the primary constructor, but returns a new object on each
216 call. This is most likely to be useful for testing or demonstration
217 purposes, but it can also be used to create a system with a different cache
218 invalidation strategy.
219
220 Objects created via this constructor will also bypass the cache of a
221 deserializing process when unpickled.
222
223 .. TODO: Add "See `cache_behavior`_" reference when that section is ready.
224
225 .. caution::
226
227 Using this constructor may change the semantics of your datetimes in
228 surprising ways, only use it if you know that you need to.
229
230 The following class methods are also available:
231
232 .. classmethod:: ZoneInfo.clear_cache(*, only_keys=None)
233
234 A method for invalidating the cache on the ``ZoneInfo`` class. If no
235 arguments are passed, all caches are invalidated and the next call to
236 the primary constructor for each key will return a new instance.
237
238 If an iterable of key names is passed to the ``only_keys`` parameter, only
239 the specified keys will be removed from the cache. Keys passed to
240 ``only_keys`` but not found in the cache are ignored.
241
242 .. TODO: Add "See `cache_behavior`_" reference when that section is ready.
243
244 .. warning::
245
246 Invoking this function may change the semantics of datetimes using
247 ``ZoneInfo`` in surprising ways; this modifies module state
248 and thus may have wide-ranging effects. Only use it if you know that you
249 need to.
250
251 The class has one attribute:
252
253 .. attribute:: ZoneInfo.key
254
255 This is a read-only :term:`attribute` that returns the value of ``key``
256 passed to the constructor, which should be a lookup key in the IANA time
257 zone database (e.g. ``America/New_York``, ``Europe/Paris`` or
258 ``Asia/Tokyo``).
259
260 For zones constructed from file without specifying a ``key`` parameter,
261 this will be set to ``None``.
262
263 .. note::
264
265 Although it is a somewhat common practice to expose these to end users,
266 these values are designed to be primary keys for representing the
267 relevant zones and not necessarily user-facing elements. Projects like
268 CLDR (the Unicode Common Locale Data Repository) can be used to get
269 more user-friendly strings from these keys.
270
271 String representations
272 **********************
273
274 The string representation returned when calling :py:class:`str` on a
275 :class:`ZoneInfo` object defaults to using the :attr:`ZoneInfo.key` attribute (see
276 the note on usage in the attribute documentation)::
277
278 >>> zone = ZoneInfo("Pacific/Kwajalein")
279 >>> str(zone)
280 'Pacific/Kwajalein'
281
282 >>> dt = datetime(2020, 4, 1, 3, 15, tzinfo=zone)
283 >>> f"{dt.isoformat()} [{dt.tzinfo}]"
284 '2020-04-01T03:15:00+12:00 [Pacific/Kwajalein]'
285
286 For objects constructed from a file without specifying a ``key`` parameter,
287 ``str`` falls back to calling :func:`repr`. ``ZoneInfo``'s ``repr`` is
288 implementation-defined and not necessarily stable between versions, but it is
289 guaranteed not to be a valid ``ZoneInfo`` key.
290
291 .. _pickling:
292
293 Pickle serialization
294 ********************
295
296 Rather than serializing all transition data, ``ZoneInfo`` objects are
297 serialized by key, and ``ZoneInfo`` objects constructed from files (even those
298 with a value for ``key`` specified) cannot be pickled.
299
300 The behavior of a ``ZoneInfo`` file depends on how it was constructed:
301
302 1. ``ZoneInfo(key)``: When constructed with the primary constructor, a
303 ``ZoneInfo`` object is serialized by key, and when deserialized, the
304 deserializing process uses the primary and thus it is expected that these
305 are the same object as other references to the same time
306 zone. For example, if ``europe_berlin_pkl`` is a string containing a pickle
307 constructed from ``ZoneInfo("Europe/Berlin")``, one would expect the
308 following behavior:
309
310 .. code-block:: pycon
311
312 >>> a = ZoneInfo("Europe/Berlin")
313 >>> b = pickle.loads(europe_berlin_pkl)
314 >>> a is b
315 True
316
317 2. ``ZoneInfo.no_cache(key)``: When constructed from the cache-bypassing
318 constructor, the ``ZoneInfo`` object is also serialized by key, but when
319 deserialized, the deserializing process uses the cache bypassing
320 constructor. If ``europe_berlin_pkl_nc`` is a string containing a pickle
321 constructed from ``ZoneInfo.no_cache("Europe/Berlin")``, one would expect
322 the following behavior:
323
324 .. code-block:: pycon
325
326 >>> a = ZoneInfo("Europe/Berlin")
327 >>> b = pickle.loads(europe_berlin_pkl_nc)
328 >>> a is b
329 False
330
331 3. ``ZoneInfo.from_file(file_obj, /, key=None)``: When constructed from a file, the
332 ``ZoneInfo`` object raises an exception on pickling. If an end user wants to
333 pickle a ``ZoneInfo`` constructed from a file, it is recommended that they
334 use a wrapper type or a custom serialization function: either serializing by
335 key or storing the contents of the file object and serializing that.
336
337 This method of serialization requires that the time zone data for the required
338 key be available on both the serializing and deserializing side, similar to the
339 way that references to classes and functions are expected to exist in both the
340 serializing and deserializing environments. It also means that no guarantees
341 are made about the consistency of results when unpickling a ``ZoneInfo``
342 pickled in an environment with a different version of the time zone data.
343
344 Functions
345 ---------
346
347 .. function:: available_timezones()
348
349 Get a set containing all the valid keys for IANA time zones available
350 anywhere on the time zone path. This is recalculated on every call to the
351 function.
352
353 This function only includes canonical zone names and does not include
354 "special" zones such as those under the ``posix/`` and ``right/``
355 directories, or the ``posixrules`` zone.
356
357 .. caution::
358
359 This function may open a large number of files, as the best way to
360 determine if a file on the time zone path is a valid time zone is to
361 read the "magic string" at the beginning.
362
363 .. note::
364
365 These values are not designed to be exposed to end-users; for user
366 facing elements, applications should use something like CLDR (the
367 Unicode Common Locale Data Repository) to get more user-friendly
368 strings. See also the cautionary note on :attr:`ZoneInfo.key`.
369
370 .. function:: reset_tzpath(to=None)
371
372 Sets or resets the time zone search path (:data:`TZPATH`) for the module.
373 When called with no arguments, :data:`TZPATH` is set to the default value.
374
375 Calling ``reset_tzpath`` will not invalidate the :class:`ZoneInfo` cache,
376 and so calls to the primary ``ZoneInfo`` constructor will only use the new
377 ``TZPATH`` in the case of a cache miss.
378
379 The ``to`` parameter must be a :term:`sequence` of strings or
380 :class:`os.PathLike` and not a string, all of which must be absolute paths.
381 :exc:`ValueError` will be raised if something other than an absolute path
382 is passed.
383
384 Globals
385 -------
386
387 .. data:: TZPATH
388
389 A read-only sequence representing the time zone search path -- when
390 constructing a ``ZoneInfo`` from a key, the key is joined to each entry in
391 the ``TZPATH``, and the first file found is used.
392
393 ``TZPATH`` may contain only absolute paths, never relative paths,
394 regardless of how it is configured.
395
396 The object that ``zoneinfo.TZPATH`` points to may change in response to a
397 call to :func:`reset_tzpath`, so it is recommended to use
398 ``zoneinfo.TZPATH`` rather than importing ``TZPATH`` from ``zoneinfo`` or
399 assigning a long-lived variable to ``zoneinfo.TZPATH``.
400
401 For more information on configuring the time zone search path, see
402 :ref:`zoneinfo_data_configuration`.
403
404 Exceptions and warnings
405 -----------------------
406
407 .. exception:: ZoneInfoNotFoundError
408
409 Raised when construction of a :class:`ZoneInfo` object fails because the
410 specified key could not be found on the system. This is a subclass of
411 :exc:`KeyError`.
412
413 .. exception:: InvalidTZPathWarning
414
415 Raised when :envvar:`PYTHONTZPATH` contains an invalid component that will
416 be filtered out, such as a relative path.
417
418 .. Links and references: