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