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