Debian Codegraph @

Doc/library/time.rst

raw
1 :mod:`!time` --- Time access and conversions
2 ============================================
3
4 .. module:: time
5 :synopsis: Time access and conversions.
6
7 --------------
8
9 This module provides various time-related functions. For related
10 functionality, see also the :mod:`datetime` and :mod:`calendar` modules.
11
12 Although this module is always available,
13 not all functions are available on all platforms. Most of the functions
14 defined in this module call platform C library functions with the same name. It
15 may sometimes be helpful to consult the platform documentation, because the
16 semantics of these functions varies among platforms.
17
18 An explanation of some terminology and conventions is in order.
19
20 .. _epoch:
21
22 .. index:: single: epoch
23
24 * The :dfn:`epoch` is the point where the time starts, the return value of
25 ``time.gmtime(0)``. It is January 1, 1970, 00:00:00 (UTC) on all platforms.
26
27 .. _leap seconds: https://en.wikipedia.org/wiki/Leap_second
28
29 .. index:: seconds since the epoch
30
31 * The term :dfn:`seconds since the epoch` refers to the total number
32 of elapsed seconds since the epoch, typically excluding
33 `leap seconds`_. Leap seconds are excluded from this total on all
34 POSIX-compliant platforms.
35
36 .. index:: single: Year 2038
37
38 * The functions in this module may not handle dates and times before the epoch_ or
39 far in the future. The cut-off point in the future is determined by the C
40 library; for 32-bit systems, it is typically in 2038.
41
42 .. index::
43 single: 2-digit years
44
45 * Function :func:`strptime` can parse 2-digit years when given ``%y`` format
46 code. When 2-digit years are parsed, they are converted according to the POSIX
47 and ISO C standards: values 69--99 are mapped to 1969--1999, and values 0--68
48 are mapped to 2000--2068.
49
50 .. index::
51 single: UTC
52 single: Coordinated Universal Time
53 single: Greenwich Mean Time
54
55 * UTC is `Coordinated Universal Time`_ and superseded `Greenwich Mean Time`_ or
56 GMT as the basis of international timekeeping. The acronym UTC is not a
57 mistake but conforms to an earlier, language-agnostic naming scheme for time
58 standards such as UT0, UT1, and UT2.
59
60 .. _Coordinated Universal Time: https://en.wikipedia.org/wiki/Coordinated_Universal_Time
61 .. _Greenwich Mean Time: https://en.wikipedia.org/wiki/Greenwich_Mean_Time
62
63 .. index:: single: Daylight Saving Time
64
65 * DST is Daylight Saving Time, an adjustment of the timezone by (usually) one
66 hour during part of the year. DST rules are magic (determined by local law) and
67 can change from year to year. The C library has a table containing the local
68 rules (often it is read from a system file for flexibility) and is the only
69 source of True Wisdom in this respect.
70
71 * The precision of the various real-time functions may be less than suggested by
72 the units in which their value or argument is expressed. E.g. on most Unix
73 systems, the clock "ticks" only 50 or 100 times a second.
74
75 * On the other hand, the precision of :func:`.time` and :func:`sleep` is better
76 than their Unix equivalents: times are expressed as floating-point numbers,
77 :func:`.time` returns the most accurate time available (using Unix
78 :c:func:`!gettimeofday` where available), and :func:`sleep` will accept a time
79 with a nonzero fraction (Unix :c:func:`!select` is used to implement this, where
80 available).
81
82 * The time value as returned by :func:`gmtime`, :func:`localtime`, and
83 :func:`strptime`, and accepted by :func:`asctime`, :func:`mktime` and
84 :func:`strftime`, is a sequence of 9 integers. The return values of
85 :func:`gmtime`, :func:`localtime`, and :func:`strptime` also offer attribute
86 names for individual fields.
87
88 See :class:`struct_time` for a description of these objects.
89
90 .. versionchanged:: 3.3
91 The :class:`struct_time` type was extended to provide
92 the :attr:`~struct_time.tm_gmtoff` and :attr:`~struct_time.tm_zone`
93 attributes when platform supports corresponding
94 ``struct tm`` members.
95
96 .. versionchanged:: 3.6
97 The :class:`struct_time` attributes
98 :attr:`~struct_time.tm_gmtoff` and :attr:`~struct_time.tm_zone`
99 are now available on all platforms.
100
101 * Use the following functions to convert between time representations:
102
103 +-------------------------+-------------------------+-------------------------+
104 | From | To | Use |
105 +=========================+=========================+=========================+
106 | seconds since the epoch | :class:`struct_time` in | :func:`gmtime` |
107 | | UTC | |
108 +-------------------------+-------------------------+-------------------------+
109 | seconds since the epoch | :class:`struct_time` in | :func:`localtime` |
110 | | local time | |
111 +-------------------------+-------------------------+-------------------------+
112 | :class:`struct_time` in | seconds since the epoch | :func:`calendar.timegm` |
113 | UTC | | |
114 +-------------------------+-------------------------+-------------------------+
115 | :class:`struct_time` in | seconds since the epoch | :func:`mktime` |
116 | local time | | |
117 +-------------------------+-------------------------+-------------------------+
118
119
120 .. _time-functions:
121
122 Functions
123 ---------
124
125 .. function:: asctime([t])
126
127 Convert a tuple or :class:`struct_time` representing a time as returned by
128 :func:`gmtime` or :func:`localtime` to a string of the following
129 form: ``'Sun Jun 20 23:21:05 1993'``. The day field is two characters long
130 and is space padded if the day is a single digit,
131 e.g.: ``'Wed Jun 9 04:26:40 1993'``.
132
133 If *t* is not provided, the current time as returned by :func:`localtime`
134 is used. Locale information is not used by :func:`asctime`.
135
136 .. note::
137
138 Unlike the C function of the same name, :func:`asctime` does not add a
139 trailing newline.
140
141 .. function:: pthread_getcpuclockid(thread_id)
142
143 Return the *clk_id* of the thread-specific CPU-time clock for the specified *thread_id*.
144
145 Use :func:`threading.get_ident` or the :attr:`~threading.Thread.ident`
146 attribute of :class:`threading.Thread` objects to get a suitable value
147 for *thread_id*.
148
149 .. warning::
150 Passing an invalid or expired *thread_id* may result in
151 undefined behavior, such as segmentation fault.
152
153 .. availability:: Unix
154
155 See the man page for :manpage:`pthread_getcpuclockid(3)` for
156 further information.
157
158 .. versionadded:: 3.7
159
160 .. function:: clock_getres(clk_id)
161
162 Return the resolution (precision) of the specified clock *clk_id*. Refer to
163 :ref:`time-clock-id-constants` for a list of accepted values for *clk_id*.
164
165 .. availability:: Unix.
166
167 .. versionadded:: 3.3
168
169
170 .. function:: clock_gettime(clk_id) -> float
171
172 Return the time of the specified clock *clk_id*. Refer to
173 :ref:`time-clock-id-constants` for a list of accepted values for *clk_id*.
174
175 Use :func:`clock_gettime_ns` to avoid the precision loss caused by the
176 :class:`float` type.
177
178 .. availability:: Unix.
179
180 .. versionadded:: 3.3
181
182
183 .. function:: clock_gettime_ns(clk_id) -> int
184
185 Similar to :func:`clock_gettime` but return time as nanoseconds.
186
187 .. availability:: Unix.
188
189 .. versionadded:: 3.7
190
191
192 .. function:: clock_settime(clk_id, time: float)
193
194 Set the time of the specified clock *clk_id*. Currently,
195 :data:`CLOCK_REALTIME` is the only accepted value for *clk_id*.
196
197 Use :func:`clock_settime_ns` to avoid the precision loss caused by the
198 :class:`float` type.
199
200 .. availability:: Unix, not Android, not iOS.
201
202 .. versionadded:: 3.3
203
204
205 .. function:: clock_settime_ns(clk_id, time: int)
206
207 Similar to :func:`clock_settime` but set time with nanoseconds.
208
209 .. availability:: Unix, not Android, not iOS.
210
211 .. versionadded:: 3.7
212
213
214 .. function:: ctime([secs])
215
216 Convert a time expressed in seconds since the epoch_ to a string of a form:
217 ``'Sun Jun 20 23:21:05 1993'`` representing local time. The day field
218 is two characters long and is space padded if the day is a single digit,
219 e.g.: ``'Wed Jun 9 04:26:40 1993'``.
220
221 If *secs* is not provided or :const:`None`, the current time as
222 returned by :func:`.time` is used. ``ctime(secs)`` is equivalent to
223 ``asctime(localtime(secs))``. Locale information is not used by
224 :func:`ctime`.
225
226
227 .. function:: get_clock_info(name)
228
229 Get information on the specified clock as a namespace object.
230 Supported clock names and the corresponding functions to read their value
231 are:
232
233 * ``'monotonic'``: :func:`time.monotonic`
234 * ``'perf_counter'``: :func:`time.perf_counter`
235 * ``'process_time'``: :func:`time.process_time`
236 * ``'thread_time'``: :func:`time.thread_time`
237 * ``'time'``: :func:`time.time`
238
239 The result has the following attributes:
240
241 - *adjustable*: ``True`` if the clock can be set to jump forward or backward
242 in time, ``False`` otherwise. Does not refer to gradual NTP rate adjustments.
243 - *implementation*: The name of the underlying C function used to get
244 the clock value. Refer to :ref:`time-clock-id-constants` for possible values.
245 - *monotonic*: ``True`` if the clock cannot go backward,
246 ``False`` otherwise
247 - *resolution*: The resolution of the clock in seconds (:class:`float`)
248
249 .. versionadded:: 3.3
250
251
252 .. function:: gmtime([secs])
253
254 Convert a time expressed in seconds since the epoch_ to a :class:`struct_time` in
255 UTC in which the dst flag is always zero. If *secs* is not provided or
256 :const:`None`, the current time as returned by :func:`.time` is used. Fractions
257 of a second are ignored. See above for a description of the
258 :class:`struct_time` object. See :func:`calendar.timegm` for the inverse of this
259 function.
260
261
262 .. function:: localtime([secs])
263
264 Like :func:`gmtime` but converts to local time. If *secs* is not provided or
265 :const:`None`, the current time as returned by :func:`.time` is used. The dst
266 flag is set to ``1`` when DST applies to the given time.
267
268 :func:`localtime` may raise :exc:`OverflowError`, if the timestamp is
269 outside the range of values supported by the platform C :c:func:`localtime`
270 or :c:func:`gmtime` functions, and :exc:`OSError` on :c:func:`localtime` or
271 :c:func:`gmtime` failure. It's common for this to be restricted to years
272 between 1970 and 2038.
273
274
275 .. function:: mktime(t)
276
277 This is the inverse function of :func:`localtime`. Its argument is the
278 :class:`struct_time` or full 9-tuple (since the dst flag is needed; use ``-1``
279 as the dst flag if it is unknown) which expresses the time in *local* time, not
280 UTC. It returns a floating-point number, for compatibility with :func:`.time`.
281 If the input value cannot be represented as a valid time, either
282 :exc:`OverflowError` or :exc:`ValueError` will be raised (which depends on
283 whether the invalid value is caught by Python or the underlying C libraries).
284 The earliest date for which it can generate a time is platform-dependent.
285
286
287 .. function:: monotonic() -> float
288
289 Return the value (in fractional seconds) of a monotonic clock, i.e. a clock
290 that cannot go backwards. The clock is not affected by system clock updates.
291 The reference point of the returned value is undefined, so that only the
292 difference between the results of two calls is valid.
293
294 Clock:
295
296 * On Windows, call ``QueryPerformanceCounter()`` and
297 ``QueryPerformanceFrequency()``.
298 * On macOS, call ``mach_absolute_time()`` and ``mach_timebase_info()``.
299 * On HP-UX, call ``gethrtime()``.
300 * Call ``clock_gettime(CLOCK_HIGHRES)`` if available.
301 * Otherwise, call ``clock_gettime(CLOCK_MONOTONIC)``.
302
303 Use :func:`monotonic_ns` to avoid the precision loss caused by the
304 :class:`float` type.
305
306 .. versionadded:: 3.3
307
308 .. versionchanged:: 3.5
309 The function is now always available and the clock is now the same for
310 all processes.
311
312 .. versionchanged:: 3.10
313 On macOS, the clock is now the same for all processes.
314
315
316 .. function:: monotonic_ns() -> int
317
318 Similar to :func:`monotonic`, but return time as nanoseconds.
319
320 .. versionadded:: 3.7
321
322 .. function:: perf_counter() -> float
323
324 .. index::
325 single: benchmarking
326
327 Return the value (in fractional seconds) of a performance counter, i.e. a
328 clock with the highest available resolution to measure a short duration. It
329 does include time elapsed during sleep. The clock is the same for all
330 processes. The reference
331 point of the returned value is undefined, so that only the difference between
332 the results of two calls is valid.
333
334 .. impl-detail::
335
336 On CPython, use the same clock as :func:`time.monotonic` and is a
337 monotonic clock, i.e. a clock that cannot go backwards.
338
339 Use :func:`perf_counter_ns` to avoid the precision loss caused by the
340 :class:`float` type.
341
342 .. versionadded:: 3.3
343
344 .. versionchanged:: 3.10
345 On Windows, the clock is now the same for all processes.
346
347 .. versionchanged:: 3.13
348 Use the same clock as :func:`time.monotonic`.
349
350
351 .. function:: perf_counter_ns() -> int
352
353 Similar to :func:`perf_counter`, but return time as nanoseconds.
354
355 .. versionadded:: 3.7
356
357
358 .. function:: process_time() -> float
359
360 .. index::
361 single: CPU time
362 single: processor time
363 single: benchmarking
364
365 Return the value (in fractional seconds) of the sum of the system and user
366 CPU time of the current process. It does not include time elapsed during
367 sleep. It is process-wide by definition. The reference point of the
368 returned value is undefined, so that only the difference between the results
369 of two calls is valid.
370
371 Use :func:`process_time_ns` to avoid the precision loss caused by the
372 :class:`float` type.
373
374 .. versionadded:: 3.3
375
376 .. function:: process_time_ns() -> int
377
378 Similar to :func:`process_time` but return time as nanoseconds.
379
380 .. versionadded:: 3.7
381
382 .. function:: sleep(secs)
383
384 Suspend execution of the calling thread for the given number of seconds.
385 The argument may be a floating-point number to indicate a more precise sleep
386 time.
387
388 If the sleep is interrupted by a signal and no exception is raised by the
389 signal handler, the sleep is restarted with a recomputed timeout.
390
391 The suspension time may be longer than requested by an arbitrary amount,
392 because of the scheduling of other activity in the system.
393
394 .. rubric:: Windows implementation
395
396 On Windows, if *secs* is zero, the thread relinquishes the remainder of its
397 time slice to any other thread that is ready to run. If there are no other
398 threads ready to run, the function returns immediately, and the thread
399 continues execution. On Windows 10 and newer the implementation uses
400 a `high-resolution timer
401 <https://learn.microsoft.com/windows/win32/api/synchapi/nf-synchapi-createwaitabletimerexw>`_
402 which provides resolution of 100 nanoseconds. If *secs* is zero, ``Sleep(0)`` is used.
403
404 .. rubric:: Unix implementation
405
406 * Use ``clock_nanosleep()`` if available (resolution: 1 nanosecond);
407 * Or use ``nanosleep()`` if available (resolution: 1 nanosecond);
408 * Or use ``select()`` (resolution: 1 microsecond).
409
410 .. note::
411
412 To emulate a "no-op", use :keyword:`pass` instead of ``time.sleep(0)``.
413
414 To voluntarily relinquish the CPU, specify a real-time :ref:`scheduling
415 policy <os-scheduling-policy>` and use :func:`os.sched_yield` instead.
416
417 .. audit-event:: time.sleep secs
418
419 .. versionchanged:: 3.5
420 The function now sleeps at least *secs* even if the sleep is interrupted
421 by a signal, except if the signal handler raises an exception (see
422 :pep:`475` for the rationale).
423
424 .. versionchanged:: 3.11
425 On Unix, the ``clock_nanosleep()`` and ``nanosleep()`` functions are now
426 used if available. On Windows, a waitable timer is now used.
427
428 .. versionchanged:: 3.13
429 Raises an auditing event.
430
431 .. index::
432 single: % (percent); datetime format
433
434 .. function:: strftime(format[, t])
435
436 Convert a tuple or :class:`struct_time` representing a time as returned by
437 :func:`gmtime` or :func:`localtime` to a string as specified by the *format*
438 argument. If *t* is not provided, the current time as returned by
439 :func:`localtime` is used. *format* must be a string. :exc:`ValueError` is
440 raised if any field in *t* is outside of the allowed range.
441
442 0 is a legal argument for any position in the time tuple; if it is normally
443 illegal the value is forced to a correct one.
444
445 The following directives can be embedded in the *format* string. They are shown
446 without the optional field width and precision specification, and are replaced
447 by the indicated characters in the :func:`strftime` result:
448
449 +-----------+------------------------------------------------+-------+
450 | Directive | Meaning | Notes |
451 +===========+================================================+=======+
452 | ``%a`` | Locale's abbreviated weekday name. | |
453 | | | |
454 +-----------+------------------------------------------------+-------+
455 | ``%A`` | Locale's full weekday name. | |
456 +-----------+------------------------------------------------+-------+
457 | ``%b`` | Locale's abbreviated month name. | |
458 | | | |
459 +-----------+------------------------------------------------+-------+
460 | ``%B`` | Locale's full month name. | |
461 +-----------+------------------------------------------------+-------+
462 | ``%c`` | Locale's appropriate date and time | |
463 | | representation. | |
464 +-----------+------------------------------------------------+-------+
465 | ``%d`` | Day of the month as a decimal number [01,31]. | |
466 | | | |
467 +-----------+------------------------------------------------+-------+
468 | ``%f`` | Microseconds as a decimal number | \(1) |
469 | | [000000,999999]. | |
470 | | | |
471 +-----------+------------------------------------------------+-------+
472 | ``%H`` | Hour (24-hour clock) as a decimal number | |
473 | | [00,23]. | |
474 +-----------+------------------------------------------------+-------+
475 | ``%I`` | Hour (12-hour clock) as a decimal number | |
476 | | [01,12]. | |
477 +-----------+------------------------------------------------+-------+
478 | ``%j`` | Day of the year as a decimal number [001,366]. | |
479 | | | |
480 +-----------+------------------------------------------------+-------+
481 | ``%m`` | Month as a decimal number [01,12]. | |
482 | | | |
483 +-----------+------------------------------------------------+-------+
484 | ``%M`` | Minute as a decimal number [00,59]. | |
485 | | | |
486 +-----------+------------------------------------------------+-------+
487 | ``%p`` | Locale's equivalent of either AM or PM. | \(2) |
488 | | | |
489 +-----------+------------------------------------------------+-------+
490 | ``%S`` | Second as a decimal number [00,61]. | \(3) |
491 | | | |
492 +-----------+------------------------------------------------+-------+
493 | ``%U`` | Week number of the year (Sunday as the first | \(4) |
494 | | day of the week) as a decimal number [00,53]. | |
495 | | All days in a new year preceding the first | |
496 | | Sunday are considered to be in week 0. | |
497 | | | |
498 | | | |
499 | | | |
500 +-----------+------------------------------------------------+-------+
501 | ``%u`` | Day of the week (Monday is 1; Sunday is 7) | |
502 | | as a decimal number [1, 7]. | |
503 +-----------+------------------------------------------------+-------+
504 | ``%w`` | Weekday as a decimal number [0(Sunday),6]. | |
505 | | | |
506 +-----------+------------------------------------------------+-------+
507 | ``%W`` | Week number of the year (Monday as the first | \(4) |
508 | | day of the week) as a decimal number [00,53]. | |
509 | | All days in a new year preceding the first | |
510 | | Monday are considered to be in week 0. | |
511 | | | |
512 | | | |
513 | | | |
514 +-----------+------------------------------------------------+-------+
515 | ``%x`` | Locale's appropriate date representation. | |
516 | | | |
517 +-----------+------------------------------------------------+-------+
518 | ``%X`` | Locale's appropriate time representation. | |
519 | | | |
520 +-----------+------------------------------------------------+-------+
521 | ``%y`` | Year without century as a decimal number | |
522 | | [00,99]. | |
523 +-----------+------------------------------------------------+-------+
524 | ``%Y`` | Year with century as a decimal number. | |
525 | | | |
526 +-----------+------------------------------------------------+-------+
527 | ``%z`` | Time zone offset indicating a positive or | |
528 | | negative time difference from UTC/GMT of the | |
529 | | form +HHMM or -HHMM, where H represents decimal| |
530 | | hour digits and M represents decimal minute | |
531 | | digits [-23:59, +23:59]. [1]_ | |
532 +-----------+------------------------------------------------+-------+
533 | ``%Z`` | Time zone name (no characters if no time zone | |
534 | | exists). Deprecated. [1]_ | |
535 +-----------+------------------------------------------------+-------+
536 | ``%G`` | ISO 8601 year (similar to ``%Y`` but follows | |
537 | | the rules for the ISO 8601 calendar year). | |
538 | | The year starts with the week that contains | |
539 | | the first Thursday of the calendar year. | |
540 +-----------+------------------------------------------------+-------+
541 | ``%V`` | ISO 8601 week number (as a decimal number | |
542 | | [01,53]). The first week of the year is the | |
543 | | one that contains the first Thursday of the | |
544 | | year. Weeks start on Monday. | |
545 +-----------+------------------------------------------------+-------+
546 | ``%%`` | A literal ``'%'`` character. | |
547 +-----------+------------------------------------------------+-------+
548
549 Notes:
550
551 (1)
552 The ``%f`` format directive only applies to :func:`strptime`,
553 not to :func:`strftime`. However, see also :meth:`datetime.datetime.strptime` and
554 :meth:`datetime.datetime.strftime` where the ``%f`` format directive
555 :ref:`applies to microseconds <format-codes>`.
556
557 (2)
558 When used with the :func:`strptime` function, the ``%p`` directive only affects
559 the output hour field if the ``%I`` directive is used to parse the hour.
560
561 .. _leap-second:
562
563 (3)
564 The range really is ``0`` to ``61``; value ``60`` is valid in
565 timestamps representing `leap seconds`_ and value ``61`` is supported
566 for historical reasons.
567
568 (4)
569 When used with the :func:`strptime` function, ``%U`` and ``%W`` are only used in
570 calculations when the day of the week and the year are specified.
571
572 Here is an example, a format for dates compatible with that specified in the
573 :rfc:`5322` Internet email standard. [1]_ ::
574
575 >>> from time import gmtime, strftime
576 >>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
577 'Thu, 28 Jun 2001 14:17:15 +0000'
578
579 Additional directives may be supported on certain platforms, but only the
580 ones listed here have a meaning standardized by ANSI C. To see the full set
581 of format codes supported on your platform, consult the :manpage:`strftime(3)`
582 documentation.
583
584 On some platforms, an optional field width and precision specification can
585 immediately follow the initial ``'%'`` of a directive in the following order;
586 this is also not portable. The field width is normally 2 except for ``%j`` where
587 it is 3.
588
589
590 .. index::
591 single: % (percent); datetime format
592
593 .. function:: strptime(string[, format])
594
595 Parse a string representing a time according to a format. The return value
596 is a :class:`struct_time` as returned by :func:`gmtime` or
597 :func:`localtime`.
598
599 The *format* parameter uses the same directives as those used by
600 :func:`strftime`; it defaults to ``"%a %b %d %H:%M:%S %Y"`` which matches the
601 formatting returned by :func:`ctime`. If *string* cannot be parsed according
602 to *format*, or if it has excess data after parsing, :exc:`ValueError` is
603 raised. The default values used to fill in any missing data when more
604 accurate values cannot be inferred are ``(1900, 1, 1, 0, 0, 0, 0, 1, -1)``.
605 Both *string* and *format* must be strings.
606
607 For example:
608
609 >>> import time
610 >>> time.strptime("30 Nov 00", "%d %b %y") # doctest: +NORMALIZE_WHITESPACE
611 time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0,
612 tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
613
614 Support for the ``%Z`` directive is based on the values contained in ``tzname``
615 and whether ``daylight`` is true. Because of this, it is platform-specific
616 except for recognizing UTC and GMT which are always known (and are considered to
617 be non-daylight savings timezones).
618
619 Only the directives specified in the documentation are supported. Because
620 ``strftime()`` is implemented per platform it can sometimes offer more
621 directives than those listed. But ``strptime()`` is independent of any platform
622 and thus does not necessarily support all directives available that are not
623 documented as supported.
624
625
626 .. class:: struct_time
627
628 The type of the time value sequence returned by :func:`gmtime`,
629 :func:`localtime`, and :func:`strptime`. It is an object with a :term:`named
630 tuple` interface: values can be accessed by index and by attribute name. The
631 following values are present:
632
633 .. list-table::
634
635 * - Index
636 - Attribute
637 - Values
638
639 * - 0
640 - .. attribute:: tm_year
641 - (for example, 1993)
642
643 * - 1
644 - .. attribute:: tm_mon
645 - range [1, 12]
646
647 * - 2
648 - .. attribute:: tm_mday
649 - range [1, 31]
650
651 * - 3
652 - .. attribute:: tm_hour
653 - range [0, 23]
654
655 * - 4
656 - .. attribute:: tm_min
657 - range [0, 59]
658
659 * - 5
660 - .. attribute:: tm_sec
661 - range [0, 61]; see :ref:`Note (2) <leap-second>` in :func:`strftime`
662
663 * - 6
664 - .. attribute:: tm_wday
665 - range [0, 6]; Monday is 0
666
667 * - 7
668 - .. attribute:: tm_yday
669 - range [1, 366]
670
671 * - 8
672 - .. attribute:: tm_isdst
673 - 0, 1 or -1; see below
674
675 * - N/A
676 - .. attribute:: tm_zone
677 - abbreviation of timezone name
678
679 * - N/A
680 - .. attribute:: tm_gmtoff
681 - offset east of UTC in seconds
682
683 Note that unlike the C structure, the month value is a range of [1, 12], not
684 [0, 11].
685
686 In calls to :func:`mktime`, :attr:`tm_isdst` may be set to 1 when daylight
687 savings time is in effect, and 0 when it is not. A value of -1 indicates that
688 this is not known, and will usually result in the correct state being filled in.
689
690 When a tuple with an incorrect length is passed to a function expecting a
691 :class:`struct_time`, or having elements of the wrong type, a
692 :exc:`TypeError` is raised.
693
694 .. function:: time() -> float
695
696 Return the time in seconds since the epoch_ as a floating-point
697 number. The handling of `leap seconds`_ is platform dependent.
698 On Windows and most Unix systems, the leap seconds are not counted towards
699 the time in seconds since the epoch_. This is commonly referred to as `Unix
700 time <https://en.wikipedia.org/wiki/Unix_time>`_.
701
702 Note that even though the time is always returned as a floating-point
703 number, not all systems provide time with a better precision than 1 second.
704 While this function normally returns non-decreasing values, it can return a
705 lower value than a previous call if the system clock has been set back
706 between the two calls.
707
708 The number returned by :func:`.time` may be converted into a more common
709 time format (i.e. year, month, day, hour, etc...) in UTC by passing it to
710 :func:`gmtime` function or in local time by passing it to the
711 :func:`localtime` function. In both cases a
712 :class:`struct_time` object is returned, from which the components
713 of the calendar date may be accessed as attributes.
714
715 Clock:
716
717 * On Windows, call ``GetSystemTimePreciseAsFileTime()``.
718 * Call ``clock_gettime(CLOCK_REALTIME)`` if available.
719 * Otherwise, call ``gettimeofday()``.
720
721 Use :func:`time_ns` to avoid the precision loss caused by the :class:`float`
722 type.
723
724 .. versionchanged:: 3.13
725
726 On Windows, calls ``GetSystemTimePreciseAsFileTime()`` instead of
727 ``GetSystemTimeAsFileTime()``.
728
729
730 .. function:: time_ns() -> int
731
732 Similar to :func:`~time.time` but returns time as an integer number of
733 nanoseconds since the epoch_.
734
735 .. versionadded:: 3.7
736
737
738 .. function:: thread_time() -> float
739
740 .. index::
741 single: CPU time
742 single: processor time
743 single: benchmarking
744
745 Return the value (in fractional seconds) of the sum of the system and user
746 CPU time of the current thread. It does not include time elapsed during
747 sleep. It is thread-specific by definition. The reference point of the
748 returned value is undefined, so that only the difference between the results
749 of two calls in the same thread is valid.
750
751 Use :func:`thread_time_ns` to avoid the precision loss caused by the
752 :class:`float` type.
753
754 .. availability:: Linux, Unix, Windows.
755
756 Unix systems supporting ``CLOCK_THREAD_CPUTIME_ID``.
757
758 .. versionadded:: 3.7
759
760
761 .. function:: thread_time_ns() -> int
762
763 Similar to :func:`thread_time` but return time as nanoseconds.
764
765 .. versionadded:: 3.7
766
767
768 .. function:: tzset()
769
770 Reset the time conversion rules used by the library routines. The environment
771 variable :envvar:`TZ` specifies how this is done. It will also set the variables
772 ``tzname`` (from the :envvar:`TZ` environment variable), ``timezone`` (non-DST
773 seconds West of UTC), ``altzone`` (DST seconds west of UTC) and ``daylight``
774 (to 0 if this timezone does not have any daylight saving time rules, or to
775 nonzero if there is a time, past, present or future when daylight saving time
776 applies).
777
778 .. availability:: Unix.
779
780 .. note::
781
782 Although in many cases, changing the :envvar:`TZ` environment variable may
783 affect the output of functions like :func:`localtime` without calling
784 :func:`tzset`, this behavior should not be relied on.
785
786 The :envvar:`TZ` environment variable should contain no whitespace.
787
788 The standard format of the :envvar:`TZ` environment variable is (whitespace
789 added for clarity)::
790
791 std offset [dst [offset [,start[/time], end[/time]]]]
792
793 Where the components are:
794
795 ``std`` and ``dst``
796 Three or more alphanumerics giving the timezone abbreviations. These will be
797 propagated into time.tzname
798
799 ``offset``
800 The offset has the form: ``± hh[:mm[:ss]]``. This indicates the value
801 added the local time to arrive at UTC. If preceded by a '-', the timezone
802 is east of the Prime Meridian; otherwise, it is west. If no offset follows
803 dst, summer time is assumed to be one hour ahead of standard time.
804
805 ``start[/time], end[/time]``
806 Indicates when to change to and back from DST. The format of the
807 start and end dates are one of the following:
808
809 :samp:`J{n}`
810 The Julian day *n* (1 <= *n* <= 365). Leap days are not counted, so in
811 all years February 28 is day 59 and March 1 is day 60.
812
813 :samp:`{n}`
814 The zero-based Julian day (0 <= *n* <= 365). Leap days are counted, and
815 it is possible to refer to February 29.
816
817 :samp:`M{m}.{n}.{d}`
818 The *d*'th day (0 <= *d* <= 6) of week *n* of month *m* of the year (1
819 <= *n* <= 5, 1 <= *m* <= 12, where week 5 means "the last *d* day in
820 month *m*" which may occur in either the fourth or the fifth
821 week). Week 1 is the first week in which the *d*'th day occurs. Day
822 zero is a Sunday.
823
824 ``time`` has the same format as ``offset`` except that no leading sign
825 ('-' or '+') is allowed. The default, if time is not given, is 02:00:00.
826
827 ::
828
829 >>> os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0'
830 >>> time.tzset()
831 >>> time.strftime('%X %x %Z')
832 '02:07:36 05/08/03 EDT'
833 >>> os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
834 >>> time.tzset()
835 >>> time.strftime('%X %x %Z')
836 '16:08:12 05/08/03 AEST'
837
838 On many Unix systems (including \*BSD, Linux, Solaris, and Darwin), it is more
839 convenient to use the system's zoneinfo (:manpage:`tzfile(5)`) database to
840 specify the timezone rules. To do this, set the :envvar:`TZ` environment
841 variable to the path of the required timezone datafile, relative to the root of
842 the systems 'zoneinfo' timezone database, usually located at
843 :file:`/usr/share/zoneinfo`. For example, ``'US/Eastern'``,
844 ``'Australia/Melbourne'``, ``'Egypt'`` or ``'Europe/Amsterdam'``. ::
845
846 >>> os.environ['TZ'] = 'US/Eastern'
847 >>> time.tzset()
848 >>> time.tzname
849 ('EST', 'EDT')
850 >>> os.environ['TZ'] = 'Egypt'
851 >>> time.tzset()
852 >>> time.tzname
853 ('EET', 'EEST')
854
855
856 .. _time-clock-id-constants:
857
858 Clock ID Constants
859 ------------------
860
861 These constants are used as parameters for :func:`clock_getres` and
862 :func:`clock_gettime`.
863
864 .. data:: CLOCK_BOOTTIME
865
866 Identical to :data:`CLOCK_MONOTONIC`, except it also includes any time that
867 the system is suspended.
868
869 This allows applications to get a suspend-aware monotonic clock without
870 having to deal with the complications of :data:`CLOCK_REALTIME`, which may
871 have discontinuities if the time is changed using ``settimeofday()`` or
872 similar.
873
874 .. availability:: Linux >= 2.6.39.
875
876 .. versionadded:: 3.7
877
878
879 .. data:: CLOCK_HIGHRES
880
881 The Solaris OS has a ``CLOCK_HIGHRES`` timer that attempts to use an optimal
882 hardware source, and may give close to nanosecond resolution.
883 ``CLOCK_HIGHRES`` is the nonadjustable, high-resolution clock.
884
885 .. availability:: Solaris.
886
887 .. versionadded:: 3.3
888
889
890 .. data:: CLOCK_MONOTONIC
891
892 Clock that cannot be set and represents monotonic time since some unspecified
893 starting point.
894
895 .. availability:: Unix.
896
897 .. versionadded:: 3.3
898
899
900 .. data:: CLOCK_MONOTONIC_RAW
901
902 Similar to :data:`CLOCK_MONOTONIC`, but provides access to a raw
903 hardware-based time that is not subject to NTP adjustments.
904
905 .. availability:: Linux >= 2.6.28, macOS >= 10.12.
906
907 .. versionadded:: 3.3
908
909 .. data:: CLOCK_MONOTONIC_RAW_APPROX
910
911 Similar to :data:`CLOCK_MONOTONIC_RAW`, but reads a value cached by
912 the system at context switch and hence has less accuracy.
913
914 .. availability:: macOS >= 10.12.
915
916 .. versionadded:: 3.13
917
918
919 .. data:: CLOCK_PROCESS_CPUTIME_ID
920
921 High-resolution per-process timer from the CPU.
922
923 .. availability:: Unix.
924
925 .. versionadded:: 3.3
926
927
928 .. data:: CLOCK_PROF
929
930 High-resolution per-process timer from the CPU.
931
932 .. availability:: FreeBSD, NetBSD >= 7, OpenBSD.
933
934 .. versionadded:: 3.7
935
936 .. data:: CLOCK_TAI
937
938 `International Atomic Time <https://www.nist.gov/pml/time-and-frequency-division/how-utcnist-related-coordinated-universal-time-utc-international>`_
939
940 The system must have a current leap second table in order for this to give
941 the correct answer. PTP or NTP software can maintain a leap second table.
942
943 .. availability:: Linux.
944
945 .. versionadded:: 3.9
946
947 .. data:: CLOCK_THREAD_CPUTIME_ID
948
949 Thread-specific CPU-time clock.
950
951 .. availability:: Unix.
952
953 .. versionadded:: 3.3
954
955
956 .. data:: CLOCK_UPTIME
957
958 Time whose absolute value is the time the system has been running and not
959 suspended, providing accurate uptime measurement, both absolute and
960 interval.
961
962 .. availability:: FreeBSD, OpenBSD >= 5.5.
963
964 .. versionadded:: 3.7
965
966
967 .. data:: CLOCK_UPTIME_RAW
968
969 Clock that increments monotonically, tracking the time since an arbitrary
970 point, unaffected by frequency or time adjustments and not incremented while
971 the system is asleep.
972
973 .. availability:: macOS >= 10.12.
974
975 .. versionadded:: 3.8
976
977 .. data:: CLOCK_UPTIME_RAW_APPROX
978
979 Like :data:`CLOCK_UPTIME_RAW`, but the value is cached by the system
980 at context switches and therefore has less accuracy.
981
982 .. availability:: macOS >= 10.12.
983
984 .. versionadded:: 3.13
985
986 The following constant is the only parameter that can be sent to
987 :func:`clock_settime`.
988
989
990 .. data:: CLOCK_REALTIME
991
992 Real-time clock. Setting this clock requires appropriate privileges.
993 The clock is the same for all processes.
994
995 .. availability:: Unix.
996
997 .. versionadded:: 3.3
998
999
1000 .. _time-timezone-constants:
1001
1002 Timezone Constants
1003 -------------------
1004
1005 .. data:: altzone
1006
1007 The offset of the local DST timezone, in seconds west of UTC, if one is defined.
1008 This is negative if the local DST timezone is east of UTC (as in Western Europe,
1009 including the UK). Only use this if ``daylight`` is nonzero. See note below.
1010
1011 .. data:: daylight
1012
1013 Nonzero if a DST timezone is defined. See note below.
1014
1015 .. data:: timezone
1016
1017 The offset of the local (non-DST) timezone, in seconds west of UTC (negative in
1018 most of Western Europe, positive in the US, zero in the UK). See note below.
1019
1020 .. data:: tzname
1021
1022 A tuple of two strings: the first is the name of the local non-DST timezone, the
1023 second is the name of the local DST timezone. If no DST timezone is defined,
1024 the second string should not be used. See note below.
1025
1026 .. note::
1027
1028 For the above Timezone constants (:data:`altzone`, :data:`daylight`, :data:`timezone`,
1029 and :data:`tzname`), the value is determined by the timezone rules in effect
1030 at module load time or the last time :func:`tzset` is called and may be incorrect
1031 for times in the past. It is recommended to use the :attr:`~struct_time.tm_gmtoff` and
1032 :attr:`~struct_time.tm_zone` results from :func:`localtime` to obtain timezone information.
1033
1034
1035 .. seealso::
1036
1037 Module :mod:`datetime`
1038 More object-oriented interface to dates and times.
1039
1040 Module :mod:`locale`
1041 Internationalization services. The locale setting affects the interpretation
1042 of many format specifiers in :func:`strftime` and :func:`strptime`.
1043
1044 Module :mod:`calendar`
1045 General calendar-related functions. :func:`~calendar.timegm` is the
1046 inverse of :func:`gmtime` from this module.
1047
1048 .. rubric:: Footnotes
1049
1050 .. [1] The use of ``%Z`` is now deprecated, but the ``%z`` escape that expands to the
1051 preferred hour/minute offset is not supported by all ANSI C libraries. Also, a
1052 strict reading of the original 1982 :rfc:`822` standard calls for a two-digit
1053 year (``%y`` rather than ``%Y``), but practice moved to 4-digit years long before the
1054 year 2000. After that, :rfc:`822` became obsolete and the 4-digit year has
1055 been first recommended by :rfc:`1123` and then mandated by :rfc:`2822`,
1056 with :rfc:`5322` continuing this requirement.