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