1:mod:`datetime` --- Basic date and time types 2============================================= 3 4.. module:: datetime 5 :synopsis: Basic date and time types. 6 7.. moduleauthor:: Tim Peters <tim@zope.com> 8.. sectionauthor:: Tim Peters <tim@zope.com> 9.. sectionauthor:: A.M. Kuchling <amk@amk.ca> 10 11**Source code:** :source:`Lib/datetime.py` 12 13-------------- 14 15.. XXX what order should the types be discussed in? 16 17The :mod:`datetime` module supplies classes for manipulating dates and times. 18 19While date and time arithmetic is supported, the focus of the implementation is 20on efficient attribute extraction for output formatting and manipulation. 21 22.. seealso:: 23 24 Module :mod:`calendar` 25 General calendar related functions. 26 27 Module :mod:`time` 28 Time access and conversions. 29 30 Package `dateutil <https://dateutil.readthedocs.io/en/stable/>`_ 31 Third-party library with expanded time zone and parsing support. 32 33.. _datetime-naive-aware: 34 35Aware and Naive Objects 36----------------------- 37 38Date and time objects may be categorized as "aware" or "naive" depending on 39whether or not they include timezone information. 40 41With sufficient knowledge of applicable algorithmic and political time 42adjustments, such as time zone and daylight saving time information, 43an **aware** object can locate itself relative to other aware objects. 44An aware object represents a specific moment in time that is not open to 45interpretation. [#]_ 46 47A **naive** object does not contain enough information to unambiguously locate 48itself relative to other date/time objects. Whether a naive object represents 49Coordinated Universal Time (UTC), local time, or time in some other timezone is 50purely up to the program, just like it is up to the program whether a 51particular number represents metres, miles, or mass. Naive objects are easy to 52understand and to work with, at the cost of ignoring some aspects of reality. 53 54For applications requiring aware objects, :class:`.datetime` and :class:`.time` 55objects have an optional time zone information attribute, :attr:`!tzinfo`, that 56can be set to an instance of a subclass of the abstract :class:`tzinfo` class. 57These :class:`tzinfo` objects capture information about the offset from UTC 58time, the time zone name, and whether daylight saving time is in effect. 59 60Only one concrete :class:`tzinfo` class, the :class:`timezone` class, is 61supplied by the :mod:`datetime` module. The :class:`timezone` class can 62represent simple timezones with fixed offsets from UTC, such as UTC itself or 63North American EST and EDT timezones. Supporting timezones at deeper levels of 64detail is up to the application. The rules for time adjustment across the 65world are more political than rational, change frequently, and there is no 66standard suitable for every application aside from UTC. 67 68Constants 69--------- 70 71The :mod:`datetime` module exports the following constants: 72 73.. data:: MINYEAR 74 75 The smallest year number allowed in a :class:`date` or :class:`.datetime` object. 76 :const:`MINYEAR` is ``1``. 77 78 79.. data:: MAXYEAR 80 81 The largest year number allowed in a :class:`date` or :class:`.datetime` object. 82 :const:`MAXYEAR` is ``9999``. 83 84Available Types 85--------------- 86 87.. class:: date 88 :noindex: 89 90 An idealized naive date, assuming the current Gregorian calendar always was, and 91 always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and 92 :attr:`day`. 93 94 95.. class:: time 96 :noindex: 97 98 An idealized time, independent of any particular day, assuming that every day 99 has exactly 24\*60\*60 seconds. (There is no notion of "leap seconds" here.) 100 Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`, 101 and :attr:`.tzinfo`. 102 103 104.. class:: datetime 105 :noindex: 106 107 A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`, 108 :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`, 109 and :attr:`.tzinfo`. 110 111 112.. class:: timedelta 113 :noindex: 114 115 A duration expressing the difference between two :class:`date`, :class:`.time`, 116 or :class:`.datetime` instances to microsecond resolution. 117 118 119.. class:: tzinfo 120 :noindex: 121 122 An abstract base class for time zone information objects. These are used by the 123 :class:`.datetime` and :class:`.time` classes to provide a customizable notion of 124 time adjustment (for example, to account for time zone and/or daylight saving 125 time). 126 127.. class:: timezone 128 :noindex: 129 130 A class that implements the :class:`tzinfo` abstract base class as a 131 fixed offset from the UTC. 132 133 .. versionadded:: 3.2 134 135Objects of these types are immutable. 136 137Subclass relationships:: 138 139 object 140 timedelta 141 tzinfo 142 timezone 143 time 144 date 145 datetime 146 147Common Properties 148^^^^^^^^^^^^^^^^^ 149 150The :class:`date`, :class:`.datetime`, :class:`.time`, and :class:`timezone` types 151share these common features: 152 153- Objects of these types are immutable. 154- Objects of these types are hashable, meaning that they can be used as 155 dictionary keys. 156- Objects of these types support efficient pickling via the :mod:`pickle` module. 157 158Determining if an Object is Aware or Naive 159^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 160 161Objects of the :class:`date` type are always naive. 162 163An object of type :class:`.time` or :class:`.datetime` may be aware or naive. 164 165A :class:`.datetime` object *d* is aware if both of the following hold: 166 1671. ``d.tzinfo`` is not ``None`` 1682. ``d.tzinfo.utcoffset(d)`` does not return ``None`` 169 170Otherwise, *d* is naive. 171 172A :class:`.time` object *t* is aware if both of the following hold: 173 1741. ``t.tzinfo`` is not ``None`` 1752. ``t.tzinfo.utcoffset(None)`` does not return ``None``. 176 177Otherwise, *t* is naive. 178 179The distinction between aware and naive doesn't apply to :class:`timedelta` 180objects. 181 182.. _datetime-timedelta: 183 184:class:`timedelta` Objects 185-------------------------- 186 187A :class:`timedelta` object represents a duration, the difference between two 188dates or times. 189 190.. class:: timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) 191 192 All arguments are optional and default to ``0``. Arguments may be integers 193 or floats, and may be positive or negative. 194 195 Only *days*, *seconds* and *microseconds* are stored internally. 196 Arguments are converted to those units: 197 198 * A millisecond is converted to 1000 microseconds. 199 * A minute is converted to 60 seconds. 200 * An hour is converted to 3600 seconds. 201 * A week is converted to 7 days. 202 203 and days, seconds and microseconds are then normalized so that the 204 representation is unique, with 205 206 * ``0 <= microseconds < 1000000`` 207 * ``0 <= seconds < 3600*24`` (the number of seconds in one day) 208 * ``-999999999 <= days <= 999999999`` 209 210 The following example illustrates how any arguments besides 211 *days*, *seconds* and *microseconds* are "merged" and normalized into those 212 three resulting attributes:: 213 214 >>> from datetime import timedelta 215 >>> delta = timedelta( 216 ... days=50, 217 ... seconds=27, 218 ... microseconds=10, 219 ... milliseconds=29000, 220 ... minutes=5, 221 ... hours=8, 222 ... weeks=2 223 ... ) 224 >>> # Only days, seconds, and microseconds remain 225 >>> delta 226 datetime.timedelta(days=64, seconds=29156, microseconds=10) 227 228 If any argument is a float and there are fractional microseconds, 229 the fractional microseconds left over from all arguments are 230 combined and their sum is rounded to the nearest microsecond using 231 round-half-to-even tiebreaker. If no argument is a float, the 232 conversion and normalization processes are exact (no information is 233 lost). 234 235 If the normalized value of days lies outside the indicated range, 236 :exc:`OverflowError` is raised. 237 238 Note that normalization of negative values may be surprising at first. For 239 example:: 240 241 >>> from datetime import timedelta 242 >>> d = timedelta(microseconds=-1) 243 >>> (d.days, d.seconds, d.microseconds) 244 (-1, 86399, 999999) 245 246 247Class attributes: 248 249.. attribute:: timedelta.min 250 251 The most negative :class:`timedelta` object, ``timedelta(-999999999)``. 252 253 254.. attribute:: timedelta.max 255 256 The most positive :class:`timedelta` object, ``timedelta(days=999999999, 257 hours=23, minutes=59, seconds=59, microseconds=999999)``. 258 259 260.. attribute:: timedelta.resolution 261 262 The smallest possible difference between non-equal :class:`timedelta` objects, 263 ``timedelta(microseconds=1)``. 264 265Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``. 266``-timedelta.max`` is not representable as a :class:`timedelta` object. 267 268Instance attributes (read-only): 269 270+------------------+--------------------------------------------+ 271| Attribute | Value | 272+==================+============================================+ 273| ``days`` | Between -999999999 and 999999999 inclusive | 274+------------------+--------------------------------------------+ 275| ``seconds`` | Between 0 and 86399 inclusive | 276+------------------+--------------------------------------------+ 277| ``microseconds`` | Between 0 and 999999 inclusive | 278+------------------+--------------------------------------------+ 279 280Supported operations: 281 282.. XXX this table is too wide! 283 284+--------------------------------+-----------------------------------------------+ 285| Operation | Result | 286+================================+===============================================+ 287| ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == | 288| | *t3* and *t1*-*t3* == *t2* are true. (1) | 289+--------------------------------+-----------------------------------------------+ 290| ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* | 291| | == *t2* - *t3* and *t2* == *t1* + *t3* are | 292| | true. (1)(6) | 293+--------------------------------+-----------------------------------------------+ 294| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer. | 295| | Afterwards *t1* // i == *t2* is true, | 296| | provided ``i != 0``. | 297+--------------------------------+-----------------------------------------------+ 298| | In general, *t1* \* i == *t1* \* (i-1) + *t1* | 299| | is true. (1) | 300+--------------------------------+-----------------------------------------------+ 301| ``t1 = t2 * f or t1 = f * t2`` | Delta multiplied by a float. The result is | 302| | rounded to the nearest multiple of | 303| | timedelta.resolution using round-half-to-even.| 304+--------------------------------+-----------------------------------------------+ 305| ``f = t2 / t3`` | Division (3) of overall duration *t2* by | 306| | interval unit *t3*. Returns a :class:`float` | 307| | object. | 308+--------------------------------+-----------------------------------------------+ 309| ``t1 = t2 / f or t1 = t2 / i`` | Delta divided by a float or an int. The result| 310| | is rounded to the nearest multiple of | 311| | timedelta.resolution using round-half-to-even.| 312+--------------------------------+-----------------------------------------------+ 313| ``t1 = t2 // i`` or | The floor is computed and the remainder (if | 314| ``t1 = t2 // t3`` | any) is thrown away. In the second case, an | 315| | integer is returned. (3) | 316+--------------------------------+-----------------------------------------------+ 317| ``t1 = t2 % t3`` | The remainder is computed as a | 318| | :class:`timedelta` object. (3) | 319+--------------------------------+-----------------------------------------------+ 320| ``q, r = divmod(t1, t2)`` | Computes the quotient and the remainder: | 321| | ``q = t1 // t2`` (3) and ``r = t1 % t2``. | 322| | q is an integer and r is a :class:`timedelta` | 323| | object. | 324+--------------------------------+-----------------------------------------------+ 325| ``+t1`` | Returns a :class:`timedelta` object with the | 326| | same value. (2) | 327+--------------------------------+-----------------------------------------------+ 328| ``-t1`` | equivalent to | 329| | :class:`timedelta`\ (-*t1.days*, | 330| | -*t1.seconds*, -*t1.microseconds*), | 331| | and to *t1*\* -1. (1)(4) | 332+--------------------------------+-----------------------------------------------+ 333| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, | 334| | and to -*t* when ``t.days < 0``. (2) | 335+--------------------------------+-----------------------------------------------+ 336| ``str(t)`` | Returns a string in the form | 337| | ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D | 338| | is negative for negative ``t``. (5) | 339+--------------------------------+-----------------------------------------------+ 340| ``repr(t)`` | Returns a string representation of the | 341| | :class:`timedelta` object as a constructor | 342| | call with canonical attribute values. | 343+--------------------------------+-----------------------------------------------+ 344 345 346Notes: 347 348(1) 349 This is exact but may overflow. 350 351(2) 352 This is exact and cannot overflow. 353 354(3) 355 Division by 0 raises :exc:`ZeroDivisionError`. 356 357(4) 358 -*timedelta.max* is not representable as a :class:`timedelta` object. 359 360(5) 361 String representations of :class:`timedelta` objects are normalized 362 similarly to their internal representation. This leads to somewhat 363 unusual results for negative timedeltas. For example:: 364 365 >>> timedelta(hours=-5) 366 datetime.timedelta(days=-1, seconds=68400) 367 >>> print(_) 368 -1 day, 19:00:00 369 370(6) 371 The expression ``t2 - t3`` will always be equal to the expression ``t2 + (-t3)`` except 372 when t3 is equal to ``timedelta.max``; in that case the former will produce a result 373 while the latter will overflow. 374 375In addition to the operations listed above, :class:`timedelta` objects support 376certain additions and subtractions with :class:`date` and :class:`.datetime` 377objects (see below). 378 379.. versionchanged:: 3.2 380 Floor division and true division of a :class:`timedelta` object by another 381 :class:`timedelta` object are now supported, as are remainder operations and 382 the :func:`divmod` function. True division and multiplication of a 383 :class:`timedelta` object by a :class:`float` object are now supported. 384 385 386Comparisons of :class:`timedelta` objects are supported, with some caveats. 387 388The comparisons ``==`` or ``!=`` *always* return a :class:`bool`, no matter 389the type of the compared object:: 390 391 >>> from datetime import timedelta 392 >>> delta1 = timedelta(seconds=57) 393 >>> delta2 = timedelta(hours=25, seconds=2) 394 >>> delta2 != delta1 395 True 396 >>> delta2 == 5 397 False 398 399For all other comparisons (such as ``<`` and ``>``), when a :class:`timedelta` 400object is compared to an object of a different type, :exc:`TypeError` 401is raised:: 402 403 >>> delta2 > delta1 404 True 405 >>> delta2 > 5 406 Traceback (most recent call last): 407 File "<stdin>", line 1, in <module> 408 TypeError: '>' not supported between instances of 'datetime.timedelta' and 'int' 409 410In Boolean contexts, a :class:`timedelta` object is 411considered to be true if and only if it isn't equal to ``timedelta(0)``. 412 413Instance methods: 414 415.. method:: timedelta.total_seconds() 416 417 Return the total number of seconds contained in the duration. Equivalent to 418 ``td / timedelta(seconds=1)``. For interval units other than seconds, use the 419 division form directly (e.g. ``td / timedelta(microseconds=1)``). 420 421 Note that for very large time intervals (greater than 270 years on 422 most platforms) this method will lose microsecond accuracy. 423 424 .. versionadded:: 3.2 425 426Examples of usage: :class:`timedelta` 427^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 428 429An additional example of normalization:: 430 431 >>> # Components of another_year add up to exactly 365 days 432 >>> from datetime import timedelta 433 >>> year = timedelta(days=365) 434 >>> another_year = timedelta(weeks=40, days=84, hours=23, 435 ... minutes=50, seconds=600) 436 >>> year == another_year 437 True 438 >>> year.total_seconds() 439 31536000.0 440 441Examples of :class:`timedelta` arithmetic:: 442 443 >>> from datetime import timedelta 444 >>> year = timedelta(days=365) 445 >>> ten_years = 10 * year 446 >>> ten_years 447 datetime.timedelta(days=3650) 448 >>> ten_years.days // 365 449 10 450 >>> nine_years = ten_years - year 451 >>> nine_years 452 datetime.timedelta(days=3285) 453 >>> three_years = nine_years // 3 454 >>> three_years, three_years.days // 365 455 (datetime.timedelta(days=1095), 3) 456 457.. _datetime-date: 458 459:class:`date` Objects 460--------------------- 461 462A :class:`date` object represents a date (year, month and day) in an idealized 463calendar, the current Gregorian calendar indefinitely extended in both 464directions. 465 466January 1 of year 1 is called day number 1, January 2 of year 1 is 467called day number 2, and so on. [#]_ 468 469.. class:: date(year, month, day) 470 471 All arguments are required. Arguments must be integers, in the following 472 ranges: 473 474 * ``MINYEAR <= year <= MAXYEAR`` 475 * ``1 <= month <= 12`` 476 * ``1 <= day <= number of days in the given month and year`` 477 478 If an argument outside those ranges is given, :exc:`ValueError` is raised. 479 480 481Other constructors, all class methods: 482 483.. classmethod:: date.today() 484 485 Return the current local date. 486 487 This is equivalent to ``date.fromtimestamp(time.time())``. 488 489.. classmethod:: date.fromtimestamp(timestamp) 490 491 Return the local date corresponding to the POSIX timestamp, such as is 492 returned by :func:`time.time`. 493 494 This may raise :exc:`OverflowError`, if the timestamp is out 495 of the range of values supported by the platform C :c:func:`localtime` 496 function, and :exc:`OSError` on :c:func:`localtime` failure. 497 It's common for this to be restricted to years from 1970 through 2038. Note 498 that on non-POSIX systems that include leap seconds in their notion of a 499 timestamp, leap seconds are ignored by :meth:`fromtimestamp`. 500 501 .. versionchanged:: 3.3 502 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp 503 is out of the range of values supported by the platform C 504 :c:func:`localtime` function. Raise :exc:`OSError` instead of 505 :exc:`ValueError` on :c:func:`localtime` failure. 506 507 508.. classmethod:: date.fromordinal(ordinal) 509 510 Return the date corresponding to the proleptic Gregorian ordinal, where 511 January 1 of year 1 has ordinal 1. 512 513 :exc:`ValueError` is raised unless ``1 <= ordinal <= 514 date.max.toordinal()``. For any date *d*, 515 ``date.fromordinal(d.toordinal()) == d``. 516 517 518.. classmethod:: date.fromisoformat(date_string) 519 520 Return a :class:`date` corresponding to a *date_string* given in the format 521 ``YYYY-MM-DD``:: 522 523 >>> from datetime import date 524 >>> date.fromisoformat('2019-12-04') 525 datetime.date(2019, 12, 4) 526 527 This is the inverse of :meth:`date.isoformat`. It only supports the format 528 ``YYYY-MM-DD``. 529 530 .. versionadded:: 3.7 531 532 533.. classmethod:: date.fromisocalendar(year, week, day) 534 535 Return a :class:`date` corresponding to the ISO calendar date specified by 536 year, week and day. This is the inverse of the function :meth:`date.isocalendar`. 537 538 .. versionadded:: 3.8 539 540 541Class attributes: 542 543.. attribute:: date.min 544 545 The earliest representable date, ``date(MINYEAR, 1, 1)``. 546 547 548.. attribute:: date.max 549 550 The latest representable date, ``date(MAXYEAR, 12, 31)``. 551 552 553.. attribute:: date.resolution 554 555 The smallest possible difference between non-equal date objects, 556 ``timedelta(days=1)``. 557 558 559Instance attributes (read-only): 560 561.. attribute:: date.year 562 563 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive. 564 565 566.. attribute:: date.month 567 568 Between 1 and 12 inclusive. 569 570 571.. attribute:: date.day 572 573 Between 1 and the number of days in the given month of the given year. 574 575 576Supported operations: 577 578+-------------------------------+----------------------------------------------+ 579| Operation | Result | 580+===============================+==============================================+ 581| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed | 582| | from *date1*. (1) | 583+-------------------------------+----------------------------------------------+ 584| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + | 585| | timedelta == date1``. (2) | 586+-------------------------------+----------------------------------------------+ 587| ``timedelta = date1 - date2`` | \(3) | 588+-------------------------------+----------------------------------------------+ 589| ``date1 < date2`` | *date1* is considered less than *date2* when | 590| | *date1* precedes *date2* in time. (4) | 591+-------------------------------+----------------------------------------------+ 592 593Notes: 594 595(1) 596 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if 597 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``. 598 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored. 599 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than 600 :const:`MINYEAR` or larger than :const:`MAXYEAR`. 601 602(2) 603 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored. 604 605(3) 606 This is exact, and cannot overflow. timedelta.seconds and 607 timedelta.microseconds are 0, and date2 + timedelta == date1 after. 608 609(4) 610 In other words, ``date1 < date2`` if and only if ``date1.toordinal() < 611 date2.toordinal()``. Date comparison raises :exc:`TypeError` if 612 the other comparand isn't also a :class:`date` object. However, 613 ``NotImplemented`` is returned instead if the other comparand has a 614 :meth:`timetuple` attribute. This hook gives other kinds of date objects a 615 chance at implementing mixed-type comparison. If not, when a :class:`date` 616 object is compared to an object of a different type, :exc:`TypeError` is raised 617 unless the comparison is ``==`` or ``!=``. The latter cases return 618 :const:`False` or :const:`True`, respectively. 619 620In Boolean contexts, all :class:`date` objects are considered to be true. 621 622Instance methods: 623 624.. method:: date.replace(year=self.year, month=self.month, day=self.day) 625 626 Return a date with the same value, except for those parameters given new 627 values by whichever keyword arguments are specified. 628 629 Example:: 630 631 >>> from datetime import date 632 >>> d = date(2002, 12, 31) 633 >>> d.replace(day=26) 634 datetime.date(2002, 12, 26) 635 636 637.. method:: date.timetuple() 638 639 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`. 640 641 The hours, minutes and seconds are 0, and the DST flag is -1. 642 643 ``d.timetuple()`` is equivalent to:: 644 645 time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1)) 646 647 where ``yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` 648 is the day number within the current year starting with ``1`` for January 1st. 649 650 651.. method:: date.toordinal() 652 653 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 654 has ordinal 1. For any :class:`date` object *d*, 655 ``date.fromordinal(d.toordinal()) == d``. 656 657 658.. method:: date.weekday() 659 660 Return the day of the week as an integer, where Monday is 0 and Sunday is 6. 661 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also 662 :meth:`isoweekday`. 663 664 665.. method:: date.isoweekday() 666 667 Return the day of the week as an integer, where Monday is 1 and Sunday is 7. 668 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also 669 :meth:`weekday`, :meth:`isocalendar`. 670 671 672.. method:: date.isocalendar() 673 674 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). 675 676 The ISO calendar is a widely used variant of the Gregorian calendar. [#]_ 677 678 The ISO year consists of 52 or 53 full weeks, and where a week starts on a 679 Monday and ends on a Sunday. The first week of an ISO year is the first 680 (Gregorian) calendar week of a year containing a Thursday. This is called week 681 number 1, and the ISO year of that Thursday is the same as its Gregorian year. 682 683 For example, 2004 begins on a Thursday, so the first week of ISO year 2004 684 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004:: 685 686 >>> from datetime import date 687 >>> date(2003, 12, 29).isocalendar() 688 (2004, 1, 1) 689 >>> date(2004, 1, 4).isocalendar() 690 (2004, 1, 7) 691 692.. method:: date.isoformat() 693 694 Return a string representing the date in ISO 8601 format, ``YYYY-MM-DD``:: 695 696 >>> from datetime import date 697 >>> date(2002, 12, 4).isoformat() 698 '2002-12-04' 699 700 This is the inverse of :meth:`date.fromisoformat`. 701 702.. method:: date.__str__() 703 704 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``. 705 706 707.. method:: date.ctime() 708 709 Return a string representing the date:: 710 711 >>> from datetime import date 712 >>> date(2002, 12, 4).ctime() 713 'Wed Dec 4 00:00:00 2002' 714 715 ``d.ctime()`` is equivalent to:: 716 717 time.ctime(time.mktime(d.timetuple())) 718 719 on platforms where the native C 720 :c:func:`ctime` function (which :func:`time.ctime` invokes, but which 721 :meth:`date.ctime` does not invoke) conforms to the C standard. 722 723 724.. method:: date.strftime(format) 725 726 Return a string representing the date, controlled by an explicit format string. 727 Format codes referring to hours, minutes or seconds will see 0 values. For a 728 complete list of formatting directives, see 729 :ref:`strftime-strptime-behavior`. 730 731 732.. method:: date.__format__(format) 733 734 Same as :meth:`.date.strftime`. This makes it possible to specify a format 735 string for a :class:`.date` object in :ref:`formatted string 736 literals <f-strings>` and when using :meth:`str.format`. For a 737 complete list of formatting directives, see 738 :ref:`strftime-strptime-behavior`. 739 740Examples of Usage: :class:`date` 741^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 742 743Example of counting days to an event:: 744 745 >>> import time 746 >>> from datetime import date 747 >>> today = date.today() 748 >>> today 749 datetime.date(2007, 12, 5) 750 >>> today == date.fromtimestamp(time.time()) 751 True 752 >>> my_birthday = date(today.year, 6, 24) 753 >>> if my_birthday < today: 754 ... my_birthday = my_birthday.replace(year=today.year + 1) 755 >>> my_birthday 756 datetime.date(2008, 6, 24) 757 >>> time_to_birthday = abs(my_birthday - today) 758 >>> time_to_birthday.days 759 202 760 761More examples of working with :class:`date`: 762 763.. doctest:: 764 765 >>> from datetime import date 766 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001 767 >>> d 768 datetime.date(2002, 3, 11) 769 770 >>> # Methods related to formatting string output 771 >>> d.isoformat() 772 '2002-03-11' 773 >>> d.strftime("%d/%m/%y") 774 '11/03/02' 775 >>> d.strftime("%A %d. %B %Y") 776 'Monday 11. March 2002' 777 >>> d.ctime() 778 'Mon Mar 11 00:00:00 2002' 779 >>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month") 780 'The day is 11, the month is March.' 781 782 >>> # Methods for to extracting 'components' under different calendars 783 >>> t = d.timetuple() 784 >>> for i in t: # doctest: +SKIP 785 ... print(i) 786 2002 # year 787 3 # month 788 11 # day 789 0 790 0 791 0 792 0 # weekday (0 = Monday) 793 70 # 70th day in the year 794 -1 795 >>> ic = d.isocalendar() 796 >>> for i in ic: # doctest: +SKIP 797 ... print(i) 798 2002 # ISO year 799 11 # ISO week number 800 1 # ISO day number ( 1 = Monday ) 801 802 >>> # A date object is immutable; all operations produce a new object 803 >>> d.replace(year=2005) 804 datetime.date(2005, 3, 11) 805 806 807.. _datetime-datetime: 808 809:class:`.datetime` Objects 810-------------------------- 811 812A :class:`.datetime` object is a single object containing all the information 813from a :class:`date` object and a :class:`.time` object. 814 815Like a :class:`date` object, :class:`.datetime` assumes the current Gregorian 816calendar extended in both directions; like a :class:`.time` object, 817:class:`.datetime` assumes there are exactly 3600\*24 seconds in every day. 818 819Constructor: 820 821.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0) 822 823 The *year*, *month* and *day* arguments are required. *tzinfo* may be ``None``, or an 824 instance of a :class:`tzinfo` subclass. The remaining arguments must be integers 825 in the following ranges: 826 827 * ``MINYEAR <= year <= MAXYEAR``, 828 * ``1 <= month <= 12``, 829 * ``1 <= day <= number of days in the given month and year``, 830 * ``0 <= hour < 24``, 831 * ``0 <= minute < 60``, 832 * ``0 <= second < 60``, 833 * ``0 <= microsecond < 1000000``, 834 * ``fold in [0, 1]``. 835 836 If an argument outside those ranges is given, :exc:`ValueError` is raised. 837 838 .. versionadded:: 3.6 839 Added the ``fold`` argument. 840 841Other constructors, all class methods: 842 843.. classmethod:: datetime.today() 844 845 Return the current local datetime, with :attr:`.tzinfo` ``None``. 846 847 Equivalent to:: 848 849 datetime.fromtimestamp(time.time()) 850 851 See also :meth:`now`, :meth:`fromtimestamp`. 852 853 This method is functionally equivalent to :meth:`now`, but without a 854 ``tz`` parameter. 855 856.. classmethod:: datetime.now(tz=None) 857 858 Return the current local date and time. 859 860 If optional argument *tz* is ``None`` 861 or not specified, this is like :meth:`today`, but, if possible, supplies more 862 precision than can be gotten from going through a :func:`time.time` timestamp 863 (for example, this may be possible on platforms supplying the C 864 :c:func:`gettimeofday` function). 865 866 If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` subclass, 867 and the current date and time are converted to *tz*’s time zone. 868 869 This function is preferred over :meth:`today` and :meth:`utcnow`. 870 871 872.. classmethod:: datetime.utcnow() 873 874 Return the current UTC date and time, with :attr:`.tzinfo` ``None``. 875 876 This is like :meth:`now`, but returns the current UTC date and time, as a naive 877 :class:`.datetime` object. An aware current UTC datetime can be obtained by 878 calling ``datetime.now(timezone.utc)``. See also :meth:`now`. 879 880 .. warning:: 881 882 Because naive ``datetime`` objects are treated by many ``datetime`` methods 883 as local times, it is preferred to use aware datetimes to represent times 884 in UTC. As such, the recommended way to create an object representing the 885 current time in UTC is by calling ``datetime.now(timezone.utc)``. 886 887 888.. classmethod:: datetime.fromtimestamp(timestamp, tz=None) 889 890 Return the local date and time corresponding to the POSIX timestamp, such as is 891 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not 892 specified, the timestamp is converted to the platform's local date and time, and 893 the returned :class:`.datetime` object is naive. 894 895 If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` subclass, and the 896 timestamp is converted to *tz*’s time zone. 897 898 :meth:`fromtimestamp` may raise :exc:`OverflowError`, if the timestamp is out of 899 the range of values supported by the platform C :c:func:`localtime` or 900 :c:func:`gmtime` functions, and :exc:`OSError` on :c:func:`localtime` or 901 :c:func:`gmtime` failure. 902 It's common for this to be restricted to years in 903 1970 through 2038. Note that on non-POSIX systems that include leap seconds in 904 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`, 905 and then it's possible to have two timestamps differing by a second that yield 906 identical :class:`.datetime` objects. This method is preferred over 907 :meth:`utcfromtimestamp`. 908 909 .. versionchanged:: 3.3 910 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp 911 is out of the range of values supported by the platform C 912 :c:func:`localtime` or :c:func:`gmtime` functions. Raise :exc:`OSError` 913 instead of :exc:`ValueError` on :c:func:`localtime` or :c:func:`gmtime` 914 failure. 915 916 .. versionchanged:: 3.6 917 :meth:`fromtimestamp` may return instances with :attr:`.fold` set to 1. 918 919.. classmethod:: datetime.utcfromtimestamp(timestamp) 920 921 Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with 922 :attr:`.tzinfo` ``None``. (The resulting object is naive.) 923 924 This may raise :exc:`OverflowError`, if the timestamp is 925 out of the range of values supported by the platform C :c:func:`gmtime` function, 926 and :exc:`OSError` on :c:func:`gmtime` failure. 927 It's common for this to be restricted to years in 1970 through 2038. 928 929 To get an aware :class:`.datetime` object, call :meth:`fromtimestamp`:: 930 931 datetime.fromtimestamp(timestamp, timezone.utc) 932 933 On the POSIX compliant platforms, it is equivalent to the following 934 expression:: 935 936 datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp) 937 938 except the latter formula always supports the full years range: between 939 :const:`MINYEAR` and :const:`MAXYEAR` inclusive. 940 941 .. warning:: 942 943 Because naive ``datetime`` objects are treated by many ``datetime`` methods 944 as local times, it is preferred to use aware datetimes to represent times 945 in UTC. As such, the recommended way to create an object representing a 946 specific timestamp in UTC is by calling 947 ``datetime.fromtimestamp(timestamp, tz=timezone.utc)``. 948 949 .. versionchanged:: 3.3 950 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp 951 is out of the range of values supported by the platform C 952 :c:func:`gmtime` function. Raise :exc:`OSError` instead of 953 :exc:`ValueError` on :c:func:`gmtime` failure. 954 955 956.. classmethod:: datetime.fromordinal(ordinal) 957 958 Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal, 959 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 960 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and 961 microsecond of the result are all 0, and :attr:`.tzinfo` is ``None``. 962 963 964.. classmethod:: datetime.combine(date, time, tzinfo=self.tzinfo) 965 966 Return a new :class:`.datetime` object whose date components are equal to the 967 given :class:`date` object's, and whose time components 968 are equal to the given :class:`.time` object's. If the *tzinfo* 969 argument is provided, its value is used to set the :attr:`.tzinfo` attribute 970 of the result, otherwise the :attr:`~.time.tzinfo` attribute of the *time* argument 971 is used. 972 973 For any :class:`.datetime` object *d*, 974 ``d == datetime.combine(d.date(), d.time(), d.tzinfo)``. If date is a 975 :class:`.datetime` object, its time components and :attr:`.tzinfo` attributes 976 are ignored. 977 978 .. versionchanged:: 3.6 979 Added the *tzinfo* argument. 980 981 982.. classmethod:: datetime.fromisoformat(date_string) 983 984 Return a :class:`.datetime` corresponding to a *date_string* in one of the 985 formats emitted by :meth:`date.isoformat` and :meth:`datetime.isoformat`. 986 987 Specifically, this function supports strings in the format: 988 989 .. code-block:: none 990 991 YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]] 992 993 where ``*`` can match any single character. 994 995 .. caution:: 996 997 This does *not* support parsing arbitrary ISO 8601 strings - it is only intended 998 as the inverse operation of :meth:`datetime.isoformat`. A more full-featured 999 ISO 8601 parser, ``dateutil.parser.isoparse`` is available in the third-party package 1000 `dateutil <https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.isoparse>`__. 1001 1002 Examples:: 1003 1004 >>> from datetime import datetime 1005 >>> datetime.fromisoformat('2011-11-04') 1006 datetime.datetime(2011, 11, 4, 0, 0) 1007 >>> datetime.fromisoformat('2011-11-04T00:05:23') 1008 datetime.datetime(2011, 11, 4, 0, 5, 23) 1009 >>> datetime.fromisoformat('2011-11-04 00:05:23.283') 1010 datetime.datetime(2011, 11, 4, 0, 5, 23, 283000) 1011 >>> datetime.fromisoformat('2011-11-04 00:05:23.283+00:00') 1012 datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.timezone.utc) 1013 >>> datetime.fromisoformat('2011-11-04T00:05:23+04:00') # doctest: +NORMALIZE_WHITESPACE 1014 datetime.datetime(2011, 11, 4, 0, 5, 23, 1015 tzinfo=datetime.timezone(datetime.timedelta(seconds=14400))) 1016 1017 .. versionadded:: 3.7 1018 1019.. classmethod:: datetime.fromisocalendar(year, week, day) 1020 1021 Return a :class:`.datetime` corresponding to the ISO calendar date specified 1022 by year, week and day. The non-date components of the datetime are populated 1023 with their normal default values. This is the inverse of the function 1024 :meth:`datetime.isocalendar`. 1025 1026 .. versionadded:: 3.8 1027 1028.. classmethod:: datetime.strptime(date_string, format) 1029 1030 Return a :class:`.datetime` corresponding to *date_string*, parsed according to 1031 *format*. 1032 1033 This is equivalent to:: 1034 1035 datetime(*(time.strptime(date_string, format)[0:6])) 1036 1037 :exc:`ValueError` is raised if the date_string and format 1038 can't be parsed by :func:`time.strptime` or if it returns a value which isn't a 1039 time tuple. For a complete list of formatting directives, see 1040 :ref:`strftime-strptime-behavior`. 1041 1042 1043 1044Class attributes: 1045 1046.. attribute:: datetime.min 1047 1048 The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1, 1049 tzinfo=None)``. 1050 1051 1052.. attribute:: datetime.max 1053 1054 The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59, 1055 59, 999999, tzinfo=None)``. 1056 1057 1058.. attribute:: datetime.resolution 1059 1060 The smallest possible difference between non-equal :class:`.datetime` objects, 1061 ``timedelta(microseconds=1)``. 1062 1063 1064Instance attributes (read-only): 1065 1066.. attribute:: datetime.year 1067 1068 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive. 1069 1070 1071.. attribute:: datetime.month 1072 1073 Between 1 and 12 inclusive. 1074 1075 1076.. attribute:: datetime.day 1077 1078 Between 1 and the number of days in the given month of the given year. 1079 1080 1081.. attribute:: datetime.hour 1082 1083 In ``range(24)``. 1084 1085 1086.. attribute:: datetime.minute 1087 1088 In ``range(60)``. 1089 1090 1091.. attribute:: datetime.second 1092 1093 In ``range(60)``. 1094 1095 1096.. attribute:: datetime.microsecond 1097 1098 In ``range(1000000)``. 1099 1100 1101.. attribute:: datetime.tzinfo 1102 1103 The object passed as the *tzinfo* argument to the :class:`.datetime` constructor, 1104 or ``None`` if none was passed. 1105 1106 1107.. attribute:: datetime.fold 1108 1109 In ``[0, 1]``. Used to disambiguate wall times during a repeated interval. (A 1110 repeated interval occurs when clocks are rolled back at the end of daylight saving 1111 time or when the UTC offset for the current zone is decreased for political reasons.) 1112 The value 0 (1) represents the earlier (later) of the two moments with the same wall 1113 time representation. 1114 1115 .. versionadded:: 3.6 1116 1117Supported operations: 1118 1119+---------------------------------------+--------------------------------+ 1120| Operation | Result | 1121+=======================================+================================+ 1122| ``datetime2 = datetime1 + timedelta`` | \(1) | 1123+---------------------------------------+--------------------------------+ 1124| ``datetime2 = datetime1 - timedelta`` | \(2) | 1125+---------------------------------------+--------------------------------+ 1126| ``timedelta = datetime1 - datetime2`` | \(3) | 1127+---------------------------------------+--------------------------------+ 1128| ``datetime1 < datetime2`` | Compares :class:`.datetime` to | 1129| | :class:`.datetime`. (4) | 1130+---------------------------------------+--------------------------------+ 1131 1132(1) 1133 datetime2 is a duration of timedelta removed from datetime1, moving forward in 1134 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The 1135 result has the same :attr:`~.datetime.tzinfo` attribute as the input datetime, and 1136 datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if 1137 datetime2.year would be smaller than :const:`MINYEAR` or larger than 1138 :const:`MAXYEAR`. Note that no time zone adjustments are done even if the 1139 input is an aware object. 1140 1141(2) 1142 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for 1143 addition, the result has the same :attr:`~.datetime.tzinfo` attribute as the input 1144 datetime, and no time zone adjustments are done even if the input is aware. 1145 1146(3) 1147 Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if 1148 both operands are naive, or if both are aware. If one is aware and the other is 1149 naive, :exc:`TypeError` is raised. 1150 1151 If both are naive, or both are aware and have the same :attr:`~.datetime.tzinfo` attribute, 1152 the :attr:`~.datetime.tzinfo` attributes are ignored, and the result is a :class:`timedelta` 1153 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments 1154 are done in this case. 1155 1156 If both are aware and have different :attr:`~.datetime.tzinfo` attributes, ``a-b`` acts 1157 as if *a* and *b* were first converted to naive UTC datetimes first. The 1158 result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) 1159 - b.utcoffset())`` except that the implementation never overflows. 1160 1161(4) 1162 *datetime1* is considered less than *datetime2* when *datetime1* precedes 1163 *datetime2* in time. 1164 1165 If one comparand is naive and the other is aware, :exc:`TypeError` 1166 is raised if an order comparison is attempted. For equality 1167 comparisons, naive instances are never equal to aware instances. 1168 1169 If both comparands are aware, and have the same :attr:`~.datetime.tzinfo` attribute, the 1170 common :attr:`~.datetime.tzinfo` attribute is ignored and the base datetimes are 1171 compared. If both comparands are aware and have different :attr:`~.datetime.tzinfo` 1172 attributes, the comparands are first adjusted by subtracting their UTC 1173 offsets (obtained from ``self.utcoffset()``). 1174 1175 .. versionchanged:: 3.3 1176 Equality comparisons between aware and naive :class:`.datetime` 1177 instances don't raise :exc:`TypeError`. 1178 1179 .. note:: 1180 1181 In order to stop comparison from falling back to the default scheme of comparing 1182 object addresses, datetime comparison normally raises :exc:`TypeError` if the 1183 other comparand isn't also a :class:`.datetime` object. However, 1184 ``NotImplemented`` is returned instead if the other comparand has a 1185 :meth:`timetuple` attribute. This hook gives other kinds of date objects a 1186 chance at implementing mixed-type comparison. If not, when a :class:`.datetime` 1187 object is compared to an object of a different type, :exc:`TypeError` is raised 1188 unless the comparison is ``==`` or ``!=``. The latter cases return 1189 :const:`False` or :const:`True`, respectively. 1190 1191Instance methods: 1192 1193.. method:: datetime.date() 1194 1195 Return :class:`date` object with same year, month and day. 1196 1197 1198.. method:: datetime.time() 1199 1200 Return :class:`.time` object with same hour, minute, second, microsecond and fold. 1201 :attr:`.tzinfo` is ``None``. See also method :meth:`timetz`. 1202 1203 .. versionchanged:: 3.6 1204 The fold value is copied to the returned :class:`.time` object. 1205 1206 1207.. method:: datetime.timetz() 1208 1209 Return :class:`.time` object with same hour, minute, second, microsecond, fold, and 1210 tzinfo attributes. See also method :meth:`time`. 1211 1212 .. versionchanged:: 3.6 1213 The fold value is copied to the returned :class:`.time` object. 1214 1215 1216.. method:: datetime.replace(year=self.year, month=self.month, day=self.day, \ 1217 hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, \ 1218 tzinfo=self.tzinfo, *, fold=0) 1219 1220 Return a datetime with the same attributes, except for those attributes given 1221 new values by whichever keyword arguments are specified. Note that 1222 ``tzinfo=None`` can be specified to create a naive datetime from an aware 1223 datetime with no conversion of date and time data. 1224 1225 .. versionadded:: 3.6 1226 Added the ``fold`` argument. 1227 1228 1229.. method:: datetime.astimezone(tz=None) 1230 1231 Return a :class:`.datetime` object with new :attr:`.tzinfo` attribute *tz*, 1232 adjusting the date and time data so the result is the same UTC time as 1233 *self*, but in *tz*'s local time. 1234 1235 If provided, *tz* must be an instance of a :class:`tzinfo` subclass, and its 1236 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. If *self* 1237 is naive, it is presumed to represent time in the system timezone. 1238 1239 If called without arguments (or with ``tz=None``) the system local 1240 timezone is assumed for the target timezone. The ``.tzinfo`` attribute of the converted 1241 datetime instance will be set to an instance of :class:`timezone` 1242 with the zone name and offset obtained from the OS. 1243 1244 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no 1245 adjustment of date or time data is performed. Else the result is local 1246 time in the timezone *tz*, representing the same UTC time as *self*: after 1247 ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will have 1248 the same date and time data as ``dt - dt.utcoffset()``. 1249 1250 If you merely want to attach a time zone object *tz* to a datetime *dt* without 1251 adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you 1252 merely want to remove the time zone object from an aware datetime *dt* without 1253 conversion of date and time data, use ``dt.replace(tzinfo=None)``. 1254 1255 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a 1256 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`. 1257 Ignoring error cases, :meth:`astimezone` acts like:: 1258 1259 def astimezone(self, tz): 1260 if self.tzinfo is tz: 1261 return self 1262 # Convert self to UTC, and attach the new time zone object. 1263 utc = (self - self.utcoffset()).replace(tzinfo=tz) 1264 # Convert from UTC to tz's local time. 1265 return tz.fromutc(utc) 1266 1267 .. versionchanged:: 3.3 1268 *tz* now can be omitted. 1269 1270 .. versionchanged:: 3.6 1271 The :meth:`astimezone` method can now be called on naive instances that 1272 are presumed to represent system local time. 1273 1274 1275.. method:: datetime.utcoffset() 1276 1277 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns 1278 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't 1279 return ``None`` or a :class:`timedelta` object with magnitude less than one day. 1280 1281 .. versionchanged:: 3.7 1282 The UTC offset is not restricted to a whole number of minutes. 1283 1284 1285.. method:: datetime.dst() 1286 1287 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns 1288 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return 1289 ``None`` or a :class:`timedelta` object with magnitude less than one day. 1290 1291 .. versionchanged:: 3.7 1292 The DST offset is not restricted to a whole number of minutes. 1293 1294 1295.. method:: datetime.tzname() 1296 1297 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns 1298 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return 1299 ``None`` or a string object, 1300 1301 1302.. method:: datetime.timetuple() 1303 1304 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`. 1305 1306 ``d.timetuple()`` is equivalent to:: 1307 1308 time.struct_time((d.year, d.month, d.day, 1309 d.hour, d.minute, d.second, 1310 d.weekday(), yday, dst)) 1311 1312 where ``yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` 1313 is the day number within the current year starting with ``1`` for January 1314 1st. The :attr:`tm_isdst` flag of the result is set according to the 1315 :meth:`dst` method: :attr:`.tzinfo` is ``None`` or :meth:`dst` returns 1316 ``None``, :attr:`tm_isdst` is set to ``-1``; else if :meth:`dst` returns a 1317 non-zero value, :attr:`tm_isdst` is set to ``1``; else :attr:`tm_isdst` is 1318 set to ``0``. 1319 1320 1321.. method:: datetime.utctimetuple() 1322 1323 If :class:`.datetime` instance *d* is naive, this is the same as 1324 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what 1325 ``d.dst()`` returns. DST is never in effect for a UTC time. 1326 1327 If *d* is aware, *d* is normalized to UTC time, by subtracting 1328 ``d.utcoffset()``, and a :class:`time.struct_time` for the 1329 normalized time is returned. :attr:`tm_isdst` is forced to 0. Note 1330 that an :exc:`OverflowError` may be raised if *d*.year was 1331 ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year 1332 boundary. 1333 1334 .. warning:: 1335 1336 Because naive ``datetime`` objects are treated by many ``datetime`` methods 1337 as local times, it is preferred to use aware datetimes to represent times 1338 in UTC; as a result, using ``utcfromtimetuple`` may give misleading 1339 results. If you have a naive ``datetime`` representing UTC, use 1340 ``datetime.replace(tzinfo=timezone.utc)`` to make it aware, at which point 1341 you can use :meth:`.datetime.timetuple`. 1342 1343.. method:: datetime.toordinal() 1344 1345 Return the proleptic Gregorian ordinal of the date. The same as 1346 ``self.date().toordinal()``. 1347 1348.. method:: datetime.timestamp() 1349 1350 Return POSIX timestamp corresponding to the :class:`.datetime` 1351 instance. The return value is a :class:`float` similar to that 1352 returned by :func:`time.time`. 1353 1354 Naive :class:`.datetime` instances are assumed to represent local 1355 time and this method relies on the platform C :c:func:`mktime` 1356 function to perform the conversion. Since :class:`.datetime` 1357 supports wider range of values than :c:func:`mktime` on many 1358 platforms, this method may raise :exc:`OverflowError` for times far 1359 in the past or far in the future. 1360 1361 For aware :class:`.datetime` instances, the return value is computed 1362 as:: 1363 1364 (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds() 1365 1366 .. versionadded:: 3.3 1367 1368 .. versionchanged:: 3.6 1369 The :meth:`timestamp` method uses the :attr:`.fold` attribute to 1370 disambiguate the times during a repeated interval. 1371 1372 .. note:: 1373 1374 There is no method to obtain the POSIX timestamp directly from a 1375 naive :class:`.datetime` instance representing UTC time. If your 1376 application uses this convention and your system timezone is not 1377 set to UTC, you can obtain the POSIX timestamp by supplying 1378 ``tzinfo=timezone.utc``:: 1379 1380 timestamp = dt.replace(tzinfo=timezone.utc).timestamp() 1381 1382 or by calculating the timestamp directly:: 1383 1384 timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1) 1385 1386.. method:: datetime.weekday() 1387 1388 Return the day of the week as an integer, where Monday is 0 and Sunday is 6. 1389 The same as ``self.date().weekday()``. See also :meth:`isoweekday`. 1390 1391 1392.. method:: datetime.isoweekday() 1393 1394 Return the day of the week as an integer, where Monday is 1 and Sunday is 7. 1395 The same as ``self.date().isoweekday()``. See also :meth:`weekday`, 1396 :meth:`isocalendar`. 1397 1398 1399.. method:: datetime.isocalendar() 1400 1401 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as 1402 ``self.date().isocalendar()``. 1403 1404 1405.. method:: datetime.isoformat(sep='T', timespec='auto') 1406 1407 Return a string representing the date and time in ISO 8601 format: 1408 1409 - ``YYYY-MM-DDTHH:MM:SS.ffffff``, if :attr:`microsecond` is not 0 1410 - ``YYYY-MM-DDTHH:MM:SS``, if :attr:`microsecond` is 0 1411 1412 If :meth:`utcoffset` does not return ``None``, a string is 1413 appended, giving the UTC offset: 1414 1415 - ``YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]``, if :attr:`microsecond` 1416 is not 0 1417 - ``YYYY-MM-DDTHH:MM:SS+HH:MM[:SS[.ffffff]]``, if :attr:`microsecond` is 0 1418 1419 Examples:: 1420 1421 >>> from datetime import datetime, timezone 1422 >>> datetime(2019, 5, 18, 15, 17, 8, 132263).isoformat() 1423 '2019-05-18T15:17:08.132263' 1424 >>> datetime(2019, 5, 18, 15, 17, tzinfo=timezone.utc).isoformat() 1425 '2019-05-18T15:17:00+00:00' 1426 1427 The optional argument *sep* (default ``'T'``) is a one-character separator, 1428 placed between the date and time portions of the result. For example:: 1429 1430 >>> from datetime import tzinfo, timedelta, datetime 1431 >>> class TZ(tzinfo): 1432 ... """A time zone with an arbitrary, constant -06:39 offset.""" 1433 ... def utcoffset(self, dt): 1434 ... return timedelta(hours=-6, minutes=-39) 1435 ... 1436 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ') 1437 '2002-12-25 00:00:00-06:39' 1438 >>> datetime(2009, 11, 27, microsecond=100, tzinfo=TZ()).isoformat() 1439 '2009-11-27T00:00:00.000100-06:39' 1440 1441 The optional argument *timespec* specifies the number of additional 1442 components of the time to include (the default is ``'auto'``). 1443 It can be one of the following: 1444 1445 - ``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0, 1446 same as ``'microseconds'`` otherwise. 1447 - ``'hours'``: Include the :attr:`hour` in the two-digit ``HH`` format. 1448 - ``'minutes'``: Include :attr:`hour` and :attr:`minute` in ``HH:MM`` format. 1449 - ``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second` 1450 in ``HH:MM:SS`` format. 1451 - ``'milliseconds'``: Include full time, but truncate fractional second 1452 part to milliseconds. ``HH:MM:SS.sss`` format. 1453 - ``'microseconds'``: Include full time in ``HH:MM:SS.ffffff`` format. 1454 1455 .. note:: 1456 1457 Excluded time components are truncated, not rounded. 1458 1459 :exc:`ValueError` will be raised on an invalid *timespec* argument:: 1460 1461 1462 >>> from datetime import datetime 1463 >>> datetime.now().isoformat(timespec='minutes') # doctest: +SKIP 1464 '2002-12-25T00:00' 1465 >>> dt = datetime(2015, 1, 1, 12, 30, 59, 0) 1466 >>> dt.isoformat(timespec='microseconds') 1467 '2015-01-01T12:30:59.000000' 1468 1469 .. versionadded:: 3.6 1470 Added the *timespec* argument. 1471 1472 1473.. method:: datetime.__str__() 1474 1475 For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to 1476 ``d.isoformat(' ')``. 1477 1478 1479.. method:: datetime.ctime() 1480 1481 Return a string representing the date and time:: 1482 1483 >>> from datetime import datetime 1484 >>> datetime(2002, 12, 4, 20, 30, 40).ctime() 1485 'Wed Dec 4 20:30:40 2002' 1486 1487 The output string will *not* include time zone information, regardless 1488 of whether the input is aware or naive. 1489 1490 ``d.ctime()`` is equivalent to:: 1491 1492 time.ctime(time.mktime(d.timetuple())) 1493 1494 on platforms where the native C :c:func:`ctime` function 1495 (which :func:`time.ctime` invokes, but which 1496 :meth:`datetime.ctime` does not invoke) conforms to the C standard. 1497 1498.. method:: datetime.strftime(format) 1499 1500 Return a string representing the date and time, controlled by an explicit format 1501 string. For a complete list of formatting directives, see 1502 :ref:`strftime-strptime-behavior`. 1503 1504 1505.. method:: datetime.__format__(format) 1506 1507 Same as :meth:`.datetime.strftime`. This makes it possible to specify a format 1508 string for a :class:`.datetime` object in :ref:`formatted string 1509 literals <f-strings>` and when using :meth:`str.format`. For a 1510 complete list of formatting directives, see 1511 :ref:`strftime-strptime-behavior`. 1512 1513Examples of Usage: :class:`.datetime` 1514^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1515 1516Examples of working with :class:`~datetime.datetime` objects: 1517 1518.. doctest:: 1519 1520 >>> from datetime import datetime, date, time, timezone 1521 1522 >>> # Using datetime.combine() 1523 >>> d = date(2005, 7, 14) 1524 >>> t = time(12, 30) 1525 >>> datetime.combine(d, t) 1526 datetime.datetime(2005, 7, 14, 12, 30) 1527 1528 >>> # Using datetime.now() 1529 >>> datetime.now() # doctest: +SKIP 1530 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1 1531 >>> datetime.now(timezone.utc) # doctest: +SKIP 1532 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060, tzinfo=datetime.timezone.utc) 1533 1534 >>> # Using datetime.strptime() 1535 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") 1536 >>> dt 1537 datetime.datetime(2006, 11, 21, 16, 30) 1538 1539 >>> # Using datetime.timetuple() to get tuple of all attributes 1540 >>> tt = dt.timetuple() 1541 >>> for it in tt: # doctest: +SKIP 1542 ... print(it) 1543 ... 1544 2006 # year 1545 11 # month 1546 21 # day 1547 16 # hour 1548 30 # minute 1549 0 # second 1550 1 # weekday (0 = Monday) 1551 325 # number of days since 1st January 1552 -1 # dst - method tzinfo.dst() returned None 1553 1554 >>> # Date in ISO format 1555 >>> ic = dt.isocalendar() 1556 >>> for it in ic: # doctest: +SKIP 1557 ... print(it) 1558 ... 1559 2006 # ISO year 1560 47 # ISO week 1561 2 # ISO weekday 1562 1563 >>> # Formatting a datetime 1564 >>> dt.strftime("%A, %d. %B %Y %I:%M%p") 1565 'Tuesday, 21. November 2006 04:30PM' 1566 >>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time") 1567 'The day is 21, the month is November, the time is 04:30PM.' 1568 1569The example below defines a :class:`tzinfo` subclass capturing time zone 1570information for Kabul, Afghanistan, which used +4 UTC until 1945 1571and then +4:30 UTC thereafter:: 1572 1573 from datetime import timedelta, datetime, tzinfo, timezone 1574 1575 class KabulTz(tzinfo): 1576 # Kabul used +4 until 1945, when they moved to +4:30 1577 UTC_MOVE_DATE = datetime(1944, 12, 31, 20, tzinfo=timezone.utc) 1578 1579 def utcoffset(self, dt): 1580 if dt.year < 1945: 1581 return timedelta(hours=4) 1582 elif (1945, 1, 1, 0, 0) <= dt.timetuple()[:5] < (1945, 1, 1, 0, 30): 1583 # An ambiguous ("imaginary") half-hour range representing 1584 # a 'fold' in time due to the shift from +4 to +4:30. 1585 # If dt falls in the imaginary range, use fold to decide how 1586 # to resolve. See PEP495. 1587 return timedelta(hours=4, minutes=(30 if dt.fold else 0)) 1588 else: 1589 return timedelta(hours=4, minutes=30) 1590 1591 def fromutc(self, dt): 1592 # Follow same validations as in datetime.tzinfo 1593 if not isinstance(dt, datetime): 1594 raise TypeError("fromutc() requires a datetime argument") 1595 if dt.tzinfo is not self: 1596 raise ValueError("dt.tzinfo is not self") 1597 1598 # A custom implementation is required for fromutc as 1599 # the input to this function is a datetime with utc values 1600 # but with a tzinfo set to self. 1601 # See datetime.astimezone or fromtimestamp. 1602 if dt.replace(tzinfo=timezone.utc) >= self.UTC_MOVE_DATE: 1603 return dt + timedelta(hours=4, minutes=30) 1604 else: 1605 return dt + timedelta(hours=4) 1606 1607 def dst(self, dt): 1608 # Kabul does not observe daylight saving time. 1609 return timedelta(0) 1610 1611 def tzname(self, dt): 1612 if dt >= self.UTC_MOVE_DATE: 1613 return "+04:30" 1614 return "+04" 1615 1616Usage of ``KabulTz`` from above:: 1617 1618 >>> tz1 = KabulTz() 1619 1620 >>> # Datetime before the change 1621 >>> dt1 = datetime(1900, 11, 21, 16, 30, tzinfo=tz1) 1622 >>> print(dt1.utcoffset()) 1623 4:00:00 1624 1625 >>> # Datetime after the change 1626 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=tz1) 1627 >>> print(dt2.utcoffset()) 1628 4:30:00 1629 1630 >>> # Convert datetime to another time zone 1631 >>> dt3 = dt2.astimezone(timezone.utc) 1632 >>> dt3 1633 datetime.datetime(2006, 6, 14, 8, 30, tzinfo=datetime.timezone.utc) 1634 >>> dt2 1635 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=KabulTz()) 1636 >>> dt2 == dt3 1637 True 1638 1639.. _datetime-time: 1640 1641:class:`.time` Objects 1642---------------------- 1643 1644A :class:`time` object represents a (local) time of day, independent of any particular 1645day, and subject to adjustment via a :class:`tzinfo` object. 1646 1647.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0) 1648 1649 All arguments are optional. *tzinfo* may be ``None``, or an instance of a 1650 :class:`tzinfo` subclass. The remaining arguments must be integers in the 1651 following ranges: 1652 1653 * ``0 <= hour < 24``, 1654 * ``0 <= minute < 60``, 1655 * ``0 <= second < 60``, 1656 * ``0 <= microsecond < 1000000``, 1657 * ``fold in [0, 1]``. 1658 1659 If an argument outside those ranges is given, :exc:`ValueError` is raised. All 1660 default to ``0`` except *tzinfo*, which defaults to :const:`None`. 1661 1662Class attributes: 1663 1664 1665.. attribute:: time.min 1666 1667 The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``. 1668 1669 1670.. attribute:: time.max 1671 1672 The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``. 1673 1674 1675.. attribute:: time.resolution 1676 1677 The smallest possible difference between non-equal :class:`.time` objects, 1678 ``timedelta(microseconds=1)``, although note that arithmetic on 1679 :class:`.time` objects is not supported. 1680 1681 1682Instance attributes (read-only): 1683 1684.. attribute:: time.hour 1685 1686 In ``range(24)``. 1687 1688 1689.. attribute:: time.minute 1690 1691 In ``range(60)``. 1692 1693 1694.. attribute:: time.second 1695 1696 In ``range(60)``. 1697 1698 1699.. attribute:: time.microsecond 1700 1701 In ``range(1000000)``. 1702 1703 1704.. attribute:: time.tzinfo 1705 1706 The object passed as the tzinfo argument to the :class:`.time` constructor, or 1707 ``None`` if none was passed. 1708 1709 1710.. attribute:: time.fold 1711 1712 In ``[0, 1]``. Used to disambiguate wall times during a repeated interval. (A 1713 repeated interval occurs when clocks are rolled back at the end of daylight saving 1714 time or when the UTC offset for the current zone is decreased for political reasons.) 1715 The value 0 (1) represents the earlier (later) of the two moments with the same wall 1716 time representation. 1717 1718 .. versionadded:: 3.6 1719 1720:class:`.time` objects support comparison of :class:`.time` to :class:`.time`, 1721where *a* is considered less 1722than *b* when *a* precedes *b* in time. If one comparand is naive and the other 1723is aware, :exc:`TypeError` is raised if an order comparison is attempted. For equality 1724comparisons, naive instances are never equal to aware instances. 1725 1726If both comparands are aware, and have 1727the same :attr:`~time.tzinfo` attribute, the common :attr:`~time.tzinfo` attribute is 1728ignored and the base times are compared. If both comparands are aware and 1729have different :attr:`~time.tzinfo` attributes, the comparands are first adjusted by 1730subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order 1731to stop mixed-type comparisons from falling back to the default comparison by 1732object address, when a :class:`.time` object is compared to an object of a 1733different type, :exc:`TypeError` is raised unless the comparison is ``==`` or 1734``!=``. The latter cases return :const:`False` or :const:`True`, respectively. 1735 1736.. versionchanged:: 3.3 1737 Equality comparisons between aware and naive :class:`~datetime.time` instances 1738 don't raise :exc:`TypeError`. 1739 1740In Boolean contexts, a :class:`.time` object is always considered to be true. 1741 1742.. versionchanged:: 3.5 1743 Before Python 3.5, a :class:`.time` object was considered to be false if it 1744 represented midnight in UTC. This behavior was considered obscure and 1745 error-prone and has been removed in Python 3.5. See :issue:`13936` for full 1746 details. 1747 1748 1749Other constructor: 1750 1751.. classmethod:: time.fromisoformat(time_string) 1752 1753 Return a :class:`.time` corresponding to a *time_string* in one of the 1754 formats emitted by :meth:`time.isoformat`. Specifically, this function supports 1755 strings in the format: 1756 1757 .. code-block:: none 1758 1759 HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]] 1760 1761 .. caution:: 1762 1763 This does *not* support parsing arbitrary ISO 8601 strings. It is only 1764 intended as the inverse operation of :meth:`time.isoformat`. 1765 1766 Examples:: 1767 1768 >>> from datetime import time 1769 >>> time.fromisoformat('04:23:01') 1770 datetime.time(4, 23, 1) 1771 >>> time.fromisoformat('04:23:01.000384') 1772 datetime.time(4, 23, 1, 384) 1773 >>> time.fromisoformat('04:23:01+04:00') 1774 datetime.time(4, 23, 1, tzinfo=datetime.timezone(datetime.timedelta(seconds=14400))) 1775 1776 .. versionadded:: 3.7 1777 1778 1779Instance methods: 1780 1781.. method:: time.replace(hour=self.hour, minute=self.minute, second=self.second, \ 1782 microsecond=self.microsecond, tzinfo=self.tzinfo, *, fold=0) 1783 1784 Return a :class:`.time` with the same value, except for those attributes given 1785 new values by whichever keyword arguments are specified. Note that 1786 ``tzinfo=None`` can be specified to create a naive :class:`.time` from an 1787 aware :class:`.time`, without conversion of the time data. 1788 1789 .. versionadded:: 3.6 1790 Added the ``fold`` argument. 1791 1792 1793.. method:: time.isoformat(timespec='auto') 1794 1795 Return a string representing the time in ISO 8601 format, one of: 1796 1797 - ``HH:MM:SS.ffffff``, if :attr:`microsecond` is not 0 1798 - ``HH:MM:SS``, if :attr:`microsecond` is 0 1799 - ``HH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]``, if :meth:`utcoffset` does not return ``None`` 1800 - ``HH:MM:SS+HH:MM[:SS[.ffffff]]``, if :attr:`microsecond` is 0 and :meth:`utcoffset` does not return ``None`` 1801 1802 The optional argument *timespec* specifies the number of additional 1803 components of the time to include (the default is ``'auto'``). 1804 It can be one of the following: 1805 1806 - ``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0, 1807 same as ``'microseconds'`` otherwise. 1808 - ``'hours'``: Include the :attr:`hour` in the two-digit ``HH`` format. 1809 - ``'minutes'``: Include :attr:`hour` and :attr:`minute` in ``HH:MM`` format. 1810 - ``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second` 1811 in ``HH:MM:SS`` format. 1812 - ``'milliseconds'``: Include full time, but truncate fractional second 1813 part to milliseconds. ``HH:MM:SS.sss`` format. 1814 - ``'microseconds'``: Include full time in ``HH:MM:SS.ffffff`` format. 1815 1816 .. note:: 1817 1818 Excluded time components are truncated, not rounded. 1819 1820 :exc:`ValueError` will be raised on an invalid *timespec* argument. 1821 1822 Example:: 1823 1824 >>> from datetime import time 1825 >>> time(hour=12, minute=34, second=56, microsecond=123456).isoformat(timespec='minutes') 1826 '12:34' 1827 >>> dt = time(hour=12, minute=34, second=56, microsecond=0) 1828 >>> dt.isoformat(timespec='microseconds') 1829 '12:34:56.000000' 1830 >>> dt.isoformat(timespec='auto') 1831 '12:34:56' 1832 1833 .. versionadded:: 3.6 1834 Added the *timespec* argument. 1835 1836 1837.. method:: time.__str__() 1838 1839 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``. 1840 1841 1842.. method:: time.strftime(format) 1843 1844 Return a string representing the time, controlled by an explicit format 1845 string. For a complete list of formatting directives, see 1846 :ref:`strftime-strptime-behavior`. 1847 1848 1849.. method:: time.__format__(format) 1850 1851 Same as :meth:`.time.strftime`. This makes it possible to specify a format string 1852 for a :class:`.time` object in :ref:`formatted string 1853 literals <f-strings>` and when using :meth:`str.format`. For a 1854 complete list of formatting directives, see 1855 :ref:`strftime-strptime-behavior`. 1856 1857 1858.. method:: time.utcoffset() 1859 1860 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns 1861 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't 1862 return ``None`` or a :class:`timedelta` object with magnitude less than one day. 1863 1864 .. versionchanged:: 3.7 1865 The UTC offset is not restricted to a whole number of minutes. 1866 1867 1868.. method:: time.dst() 1869 1870 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns 1871 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return 1872 ``None``, or a :class:`timedelta` object with magnitude less than one day. 1873 1874 .. versionchanged:: 3.7 1875 The DST offset is not restricted to a whole number of minutes. 1876 1877.. method:: time.tzname() 1878 1879 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns 1880 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't 1881 return ``None`` or a string object. 1882 1883Examples of Usage: :class:`.time` 1884^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1885 1886Examples of working with a :class:`.time` object:: 1887 1888 >>> from datetime import time, tzinfo, timedelta 1889 >>> class TZ1(tzinfo): 1890 ... def utcoffset(self, dt): 1891 ... return timedelta(hours=1) 1892 ... def dst(self, dt): 1893 ... return timedelta(0) 1894 ... def tzname(self,dt): 1895 ... return "+01:00" 1896 ... def __repr__(self): 1897 ... return f"{self.__class__.__name__}()" 1898 ... 1899 >>> t = time(12, 10, 30, tzinfo=TZ1()) 1900 >>> t 1901 datetime.time(12, 10, 30, tzinfo=TZ1()) 1902 >>> t.isoformat() 1903 '12:10:30+01:00' 1904 >>> t.dst() 1905 datetime.timedelta(0) 1906 >>> t.tzname() 1907 '+01:00' 1908 >>> t.strftime("%H:%M:%S %Z") 1909 '12:10:30 +01:00' 1910 >>> 'The {} is {:%H:%M}.'.format("time", t) 1911 'The time is 12:10.' 1912 1913 1914.. _datetime-tzinfo: 1915 1916:class:`tzinfo` Objects 1917----------------------- 1918 1919.. class:: tzinfo() 1920 1921 This is an abstract base class, meaning that this class should not be 1922 instantiated directly. Define a subclass of :class:`tzinfo` to capture 1923 information about a particular time zone. 1924 1925 An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the 1926 constructors for :class:`.datetime` and :class:`.time` objects. The latter objects 1927 view their attributes as being in local time, and the :class:`tzinfo` object 1928 supports methods revealing offset of local time from UTC, the name of the time 1929 zone, and DST offset, all relative to a date or time object passed to them. 1930 1931 You need to derive a concrete subclass, and (at least) 1932 supply implementations of the standard :class:`tzinfo` methods needed by the 1933 :class:`.datetime` methods you use. The :mod:`datetime` module provides 1934 :class:`timezone`, a simple concrete subclass of :class:`tzinfo` which can 1935 represent timezones with fixed offset from UTC such as UTC itself or North 1936 American EST and EDT. 1937 1938 Special requirement for pickling: A :class:`tzinfo` subclass must have an 1939 :meth:`__init__` method that can be called with no arguments, otherwise it can be 1940 pickled but possibly not unpickled again. This is a technical requirement that 1941 may be relaxed in the future. 1942 1943 A concrete subclass of :class:`tzinfo` may need to implement the following 1944 methods. Exactly which methods are needed depends on the uses made of aware 1945 :mod:`datetime` objects. If in doubt, simply implement all of them. 1946 1947 1948.. method:: tzinfo.utcoffset(dt) 1949 1950 Return offset of local time from UTC, as a :class:`timedelta` object that is 1951 positive east of UTC. If local time is west of UTC, this should be negative. 1952 1953 This represents the *total* offset from UTC; for example, if a 1954 :class:`tzinfo` object represents both time zone and DST adjustments, 1955 :meth:`utcoffset` should return their sum. If the UTC offset isn't known, 1956 return ``None``. Else the value returned must be a :class:`timedelta` object 1957 strictly between ``-timedelta(hours=24)`` and ``timedelta(hours=24)`` 1958 (the magnitude of the offset must be less than one day). Most implementations 1959 of :meth:`utcoffset` will probably look like one of these two:: 1960 1961 return CONSTANT # fixed-offset class 1962 return CONSTANT + self.dst(dt) # daylight-aware class 1963 1964 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return 1965 ``None`` either. 1966 1967 The default implementation of :meth:`utcoffset` raises 1968 :exc:`NotImplementedError`. 1969 1970 .. versionchanged:: 3.7 1971 The UTC offset is not restricted to a whole number of minutes. 1972 1973 1974.. method:: tzinfo.dst(dt) 1975 1976 Return the daylight saving time (DST) adjustment, as a :class:`timedelta` 1977 object or 1978 ``None`` if DST information isn't known. 1979 1980 Return ``timedelta(0)`` if DST is not in effect. 1981 If DST is in effect, return the offset as a :class:`timedelta` object 1982 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has 1983 already been added to the UTC offset returned by :meth:`utcoffset`, so there's 1984 no need to consult :meth:`dst` unless you're interested in obtaining DST info 1985 separately. For example, :meth:`datetime.timetuple` calls its :attr:`~.datetime.tzinfo` 1986 attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag 1987 should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for 1988 DST changes when crossing time zones. 1989 1990 An instance *tz* of a :class:`tzinfo` subclass that models both standard and 1991 daylight times must be consistent in this sense: 1992 1993 ``tz.utcoffset(dt) - tz.dst(dt)`` 1994 1995 must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo == 1996 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time 1997 zone's "standard offset", which should not depend on the date or the time, but 1998 only on geographic location. The implementation of :meth:`datetime.astimezone` 1999 relies on this, but cannot detect violations; it's the programmer's 2000 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee 2001 this, it may be able to override the default implementation of 2002 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless. 2003 2004 Most implementations of :meth:`dst` will probably look like one of these two:: 2005 2006 def dst(self, dt): 2007 # a fixed-offset class: doesn't account for DST 2008 return timedelta(0) 2009 2010 or:: 2011 2012 def dst(self, dt): 2013 # Code to set dston and dstoff to the time zone's DST 2014 # transition times based on the input dt.year, and expressed 2015 # in standard local time. 2016 2017 if dston <= dt.replace(tzinfo=None) < dstoff: 2018 return timedelta(hours=1) 2019 else: 2020 return timedelta(0) 2021 2022 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`. 2023 2024 .. versionchanged:: 3.7 2025 The DST offset is not restricted to a whole number of minutes. 2026 2027 2028.. method:: tzinfo.tzname(dt) 2029 2030 Return the time zone name corresponding to the :class:`.datetime` object *dt*, as 2031 a string. Nothing about string names is defined by the :mod:`datetime` module, 2032 and there's no requirement that it mean anything in particular. For example, 2033 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all 2034 valid replies. Return ``None`` if a string name isn't known. Note that this is 2035 a method rather than a fixed string primarily because some :class:`tzinfo` 2036 subclasses will wish to return different names depending on the specific value 2037 of *dt* passed, especially if the :class:`tzinfo` class is accounting for 2038 daylight time. 2039 2040 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`. 2041 2042 2043These methods are called by a :class:`.datetime` or :class:`.time` object, in 2044response to their methods of the same names. A :class:`.datetime` object passes 2045itself as the argument, and a :class:`.time` object passes ``None`` as the 2046argument. A :class:`tzinfo` subclass's methods should therefore be prepared to 2047accept a *dt* argument of ``None``, or of class :class:`.datetime`. 2048 2049When ``None`` is passed, it's up to the class designer to decide the best 2050response. For example, returning ``None`` is appropriate if the class wishes to 2051say that time objects don't participate in the :class:`tzinfo` protocols. It 2052may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as 2053there is no other convention for discovering the standard offset. 2054 2055When a :class:`.datetime` object is passed in response to a :class:`.datetime` 2056method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can 2057rely on this, unless user code calls :class:`tzinfo` methods directly. The 2058intent is that the :class:`tzinfo` methods interpret *dt* as being in local 2059time, and not need worry about objects in other timezones. 2060 2061There is one more :class:`tzinfo` method that a subclass may wish to override: 2062 2063 2064.. method:: tzinfo.fromutc(dt) 2065 2066 This is called from the default :class:`datetime.astimezone()` 2067 implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s 2068 date and time data are to be viewed as expressing a UTC time. The purpose 2069 of :meth:`fromutc` is to adjust the date and time data, returning an 2070 equivalent datetime in *self*'s local time. 2071 2072 Most :class:`tzinfo` subclasses should be able to inherit the default 2073 :meth:`fromutc` implementation without problems. It's strong enough to handle 2074 fixed-offset time zones, and time zones accounting for both standard and 2075 daylight time, and the latter even if the DST transition times differ in 2076 different years. An example of a time zone the default :meth:`fromutc` 2077 implementation may not handle correctly in all cases is one where the standard 2078 offset (from UTC) depends on the specific date and time passed, which can happen 2079 for political reasons. The default implementations of :meth:`astimezone` and 2080 :meth:`fromutc` may not produce the result you want if the result is one of the 2081 hours straddling the moment the standard offset changes. 2082 2083 Skipping code for error cases, the default :meth:`fromutc` implementation acts 2084 like:: 2085 2086 def fromutc(self, dt): 2087 # raise ValueError error if dt.tzinfo is not self 2088 dtoff = dt.utcoffset() 2089 dtdst = dt.dst() 2090 # raise ValueError if dtoff is None or dtdst is None 2091 delta = dtoff - dtdst # this is self's standard offset 2092 if delta: 2093 dt += delta # convert to standard local time 2094 dtdst = dt.dst() 2095 # raise ValueError if dtdst is None 2096 if dtdst: 2097 return dt + dtdst 2098 else: 2099 return dt 2100 2101In the following :download:`tzinfo_examples.py 2102<../includes/tzinfo_examples.py>` file there are some examples of 2103:class:`tzinfo` classes: 2104 2105.. literalinclude:: ../includes/tzinfo_examples.py 2106 2107Note that there are unavoidable subtleties twice per year in a :class:`tzinfo` 2108subclass accounting for both standard and daylight time, at the DST transition 2109points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the 2110minute after 1:59 (EST) on the second Sunday in March, and ends the minute after 21111:59 (EDT) on the first Sunday in November:: 2112 2113 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM 2114 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM 2115 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM 2116 2117 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM 2118 2119 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM 2120 2121When DST starts (the "start" line), the local wall clock leaps from 1:59 to 21223:00. A wall time of the form 2:MM doesn't really make sense on that day, so 2123``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST 2124begins. For example, at the Spring forward transition of 2016, we get:: 2125 2126 >>> from datetime import datetime, timezone 2127 >>> from tzinfo_examples import HOUR, Eastern 2128 >>> u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc) 2129 >>> for i in range(4): 2130 ... u = u0 + i*HOUR 2131 ... t = u.astimezone(Eastern) 2132 ... print(u.time(), 'UTC =', t.time(), t.tzname()) 2133 ... 2134 05:00:00 UTC = 00:00:00 EST 2135 06:00:00 UTC = 01:00:00 EST 2136 07:00:00 UTC = 03:00:00 EDT 2137 08:00:00 UTC = 04:00:00 EDT 2138 2139 2140When DST ends (the "end" line), there's a potentially worse problem: there's an 2141hour that can't be spelled unambiguously in local wall time: the last hour of 2142daylight time. In Eastern, that's times of the form 5:MM UTC on the day 2143daylight time ends. The local wall clock leaps from 1:59 (daylight time) back 2144to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous. 2145:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC 2146hours into the same local hour then. In the Eastern example, UTC times of the 2147form 5:MM and 6:MM both map to 1:MM when converted to Eastern, but earlier times 2148have the :attr:`~datetime.fold` attribute set to 0 and the later times have it set to 1. 2149For example, at the Fall back transition of 2016, we get:: 2150 2151 >>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc) 2152 >>> for i in range(4): 2153 ... u = u0 + i*HOUR 2154 ... t = u.astimezone(Eastern) 2155 ... print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold) 2156 ... 2157 04:00:00 UTC = 00:00:00 EDT 0 2158 05:00:00 UTC = 01:00:00 EDT 0 2159 06:00:00 UTC = 01:00:00 EST 1 2160 07:00:00 UTC = 02:00:00 EST 0 2161 2162Note that the :class:`.datetime` instances that differ only by the value of the 2163:attr:`~datetime.fold` attribute are considered equal in comparisons. 2164 2165Applications that can't bear wall-time ambiguities should explicitly check the 2166value of the :attr:`~datetime.fold` attribute or avoid using hybrid 2167:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`, 2168or any other fixed-offset :class:`tzinfo` subclass (such as a class representing 2169only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)). 2170 2171.. seealso:: 2172 2173 `dateutil.tz <https://dateutil.readthedocs.io/en/stable/tz.html>`_ 2174 The :mod:`datetime` module has a basic :class:`timezone` class (for 2175 handling arbitrary fixed offsets from UTC) and its :attr:`timezone.utc` 2176 attribute (a UTC timezone instance). 2177 2178 *dateutil.tz* library brings the *IANA timezone database* 2179 (also known as the Olson database) to Python, and its usage is 2180 recommended. 2181 2182 `IANA timezone database <https://www.iana.org/time-zones>`_ 2183 The Time Zone Database (often called tz, tzdata or zoneinfo) contains code 2184 and data that represent the history of local time for many representative 2185 locations around the globe. It is updated periodically to reflect changes 2186 made by political bodies to time zone boundaries, UTC offsets, and 2187 daylight-saving rules. 2188 2189 2190.. _datetime-timezone: 2191 2192:class:`timezone` Objects 2193-------------------------- 2194 2195The :class:`timezone` class is a subclass of :class:`tzinfo`, each 2196instance of which represents a timezone defined by a fixed offset from 2197UTC. 2198 2199Objects of this class cannot be used to represent timezone information in the 2200locations where different offsets are used in different days of the year or 2201where historical changes have been made to civil time. 2202 2203 2204.. class:: timezone(offset, name=None) 2205 2206 The *offset* argument must be specified as a :class:`timedelta` 2207 object representing the difference between the local time and UTC. It must 2208 be strictly between ``-timedelta(hours=24)`` and 2209 ``timedelta(hours=24)``, otherwise :exc:`ValueError` is raised. 2210 2211 The *name* argument is optional. If specified it must be a string that 2212 will be used as the value returned by the :meth:`datetime.tzname` method. 2213 2214 .. versionadded:: 3.2 2215 2216 .. versionchanged:: 3.7 2217 The UTC offset is not restricted to a whole number of minutes. 2218 2219 2220.. method:: timezone.utcoffset(dt) 2221 2222 Return the fixed value specified when the :class:`timezone` instance is 2223 constructed. 2224 2225 The *dt* argument is ignored. The return value is a :class:`timedelta` 2226 instance equal to the difference between the local time and UTC. 2227 2228 .. versionchanged:: 3.7 2229 The UTC offset is not restricted to a whole number of minutes. 2230 2231.. method:: timezone.tzname(dt) 2232 2233 Return the fixed value specified when the :class:`timezone` instance 2234 is constructed. 2235 2236 If *name* is not provided in the constructor, the name returned by 2237 ``tzname(dt)`` is generated from the value of the ``offset`` as follows. If 2238 *offset* is ``timedelta(0)``, the name is "UTC", otherwise it is a string in 2239 the format ``UTC±HH:MM``, where ± is the sign of ``offset``, HH and MM are 2240 two digits of ``offset.hours`` and ``offset.minutes`` respectively. 2241 2242 .. versionchanged:: 3.6 2243 Name generated from ``offset=timedelta(0)`` is now plain `'UTC'`, not 2244 ``'UTC+00:00'``. 2245 2246 2247.. method:: timezone.dst(dt) 2248 2249 Always returns ``None``. 2250 2251.. method:: timezone.fromutc(dt) 2252 2253 Return ``dt + offset``. The *dt* argument must be an aware 2254 :class:`.datetime` instance, with ``tzinfo`` set to ``self``. 2255 2256Class attributes: 2257 2258.. attribute:: timezone.utc 2259 2260 The UTC timezone, ``timezone(timedelta(0))``. 2261 2262 2263.. index:: 2264 single: % (percent); datetime format 2265 2266.. _strftime-strptime-behavior: 2267 2268:meth:`strftime` and :meth:`strptime` Behavior 2269---------------------------------------------- 2270 2271:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a 2272``strftime(format)`` method, to create a string representing the time under the 2273control of an explicit format string. 2274 2275Conversely, the :meth:`datetime.strptime` class method creates a 2276:class:`.datetime` object from a string representing a date and time and a 2277corresponding format string. 2278 2279The table below provides a high-level comparison of :meth:`strftime` 2280versus :meth:`strptime`: 2281 2282+----------------+--------------------------------------------------------+------------------------------------------------------------------------------+ 2283| | ``strftime`` | ``strptime`` | 2284+================+========================================================+==============================================================================+ 2285| Usage | Convert object to a string according to a given format | Parse a string into a :class:`.datetime` object given a corresponding format | 2286+----------------+--------------------------------------------------------+------------------------------------------------------------------------------+ 2287| Type of method | Instance method | Class method | 2288+----------------+--------------------------------------------------------+------------------------------------------------------------------------------+ 2289| Method of | :class:`date`; :class:`.datetime`; :class:`.time` | :class:`.datetime` | 2290+----------------+--------------------------------------------------------+------------------------------------------------------------------------------+ 2291| Signature | ``strftime(format)`` | ``strptime(date_string, format)`` | 2292+----------------+--------------------------------------------------------+------------------------------------------------------------------------------+ 2293 2294 2295:meth:`strftime` and :meth:`strptime` Format Codes 2296^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2297 2298The following is a list of all the format codes that the 1989 C standard 2299requires, and these work on all platforms with a standard C implementation. 2300 2301+-----------+--------------------------------+------------------------+-------+ 2302| Directive | Meaning | Example | Notes | 2303+===========+================================+========================+=======+ 2304| ``%a`` | Weekday as locale's || Sun, Mon, ..., Sat | \(1) | 2305| | abbreviated name. | (en_US); | | 2306| | || So, Mo, ..., Sa | | 2307| | | (de_DE) | | 2308+-----------+--------------------------------+------------------------+-------+ 2309| ``%A`` | Weekday as locale's full name. || Sunday, Monday, ..., | \(1) | 2310| | | Saturday (en_US); | | 2311| | || Sonntag, Montag, ..., | | 2312| | | Samstag (de_DE) | | 2313+-----------+--------------------------------+------------------------+-------+ 2314| ``%w`` | Weekday as a decimal number, | 0, 1, ..., 6 | | 2315| | where 0 is Sunday and 6 is | | | 2316| | Saturday. | | | 2317+-----------+--------------------------------+------------------------+-------+ 2318| ``%d`` | Day of the month as a | 01, 02, ..., 31 | \(9) | 2319| | zero-padded decimal number. | | | 2320+-----------+--------------------------------+------------------------+-------+ 2321| ``%b`` | Month as locale's abbreviated || Jan, Feb, ..., Dec | \(1) | 2322| | name. | (en_US); | | 2323| | || Jan, Feb, ..., Dez | | 2324| | | (de_DE) | | 2325+-----------+--------------------------------+------------------------+-------+ 2326| ``%B`` | Month as locale's full name. || January, February, | \(1) | 2327| | | ..., December (en_US);| | 2328| | || Januar, Februar, ..., | | 2329| | | Dezember (de_DE) | | 2330+-----------+--------------------------------+------------------------+-------+ 2331| ``%m`` | Month as a zero-padded | 01, 02, ..., 12 | \(9) | 2332| | decimal number. | | | 2333+-----------+--------------------------------+------------------------+-------+ 2334| ``%y`` | Year without century as a | 00, 01, ..., 99 | \(9) | 2335| | zero-padded decimal number. | | | 2336+-----------+--------------------------------+------------------------+-------+ 2337| ``%Y`` | Year with century as a decimal | 0001, 0002, ..., 2013, | \(2) | 2338| | number. | 2014, ..., 9998, 9999 | | 2339+-----------+--------------------------------+------------------------+-------+ 2340| ``%H`` | Hour (24-hour clock) as a | 00, 01, ..., 23 | \(9) | 2341| | zero-padded decimal number. | | | 2342+-----------+--------------------------------+------------------------+-------+ 2343| ``%I`` | Hour (12-hour clock) as a | 01, 02, ..., 12 | \(9) | 2344| | zero-padded decimal number. | | | 2345+-----------+--------------------------------+------------------------+-------+ 2346| ``%p`` | Locale's equivalent of either || AM, PM (en_US); | \(1), | 2347| | AM or PM. || am, pm (de_DE) | \(3) | 2348+-----------+--------------------------------+------------------------+-------+ 2349| ``%M`` | Minute as a zero-padded | 00, 01, ..., 59 | \(9) | 2350| | decimal number. | | | 2351+-----------+--------------------------------+------------------------+-------+ 2352| ``%S`` | Second as a zero-padded | 00, 01, ..., 59 | \(4), | 2353| | decimal number. | | \(9) | 2354+-----------+--------------------------------+------------------------+-------+ 2355| ``%f`` | Microsecond as a decimal | 000000, 000001, ..., | \(5) | 2356| | number, zero-padded on the | 999999 | | 2357| | left. | | | 2358+-----------+--------------------------------+------------------------+-------+ 2359| ``%z`` | UTC offset in the form | (empty), +0000, | \(6) | 2360| | ``±HHMM[SS[.ffffff]]`` (empty | -0400, +1030, | | 2361| | string if the object is | +063415, | | 2362| | naive). | -030712.345216 | | 2363+-----------+--------------------------------+------------------------+-------+ 2364| ``%Z`` | Time zone name (empty string | (empty), UTC, EST, CST | | 2365| | if the object is naive). | | | 2366+-----------+--------------------------------+------------------------+-------+ 2367| ``%j`` | Day of the year as a | 001, 002, ..., 366 | \(9) | 2368| | zero-padded decimal number. | | | 2369+-----------+--------------------------------+------------------------+-------+ 2370| ``%U`` | Week number of the year | 00, 01, ..., 53 | \(7), | 2371| | (Sunday as the first day of | | \(9) | 2372| | the week) as a zero padded | | | 2373| | decimal number. All days in a | | | 2374| | new year preceding the first | | | 2375| | Sunday are considered to be in | | | 2376| | week 0. | | | 2377+-----------+--------------------------------+------------------------+-------+ 2378| ``%W`` | Week number of the year | 00, 01, ..., 53 | \(7), | 2379| | (Monday as the first day of | | \(9) | 2380| | the week) as a decimal number. | | | 2381| | All days in a new year | | | 2382| | preceding the first Monday | | | 2383| | are considered to be in | | | 2384| | week 0. | | | 2385+-----------+--------------------------------+------------------------+-------+ 2386| ``%c`` | Locale's appropriate date and || Tue Aug 16 21:30:00 | \(1) | 2387| | time representation. | 1988 (en_US); | | 2388| | || Di 16 Aug 21:30:00 | | 2389| | | 1988 (de_DE) | | 2390+-----------+--------------------------------+------------------------+-------+ 2391| ``%x`` | Locale's appropriate date || 08/16/88 (None); | \(1) | 2392| | representation. || 08/16/1988 (en_US); | | 2393| | || 16.08.1988 (de_DE) | | 2394+-----------+--------------------------------+------------------------+-------+ 2395| ``%X`` | Locale's appropriate time || 21:30:00 (en_US); | \(1) | 2396| | representation. || 21:30:00 (de_DE) | | 2397+-----------+--------------------------------+------------------------+-------+ 2398| ``%%`` | A literal ``'%'`` character. | % | | 2399+-----------+--------------------------------+------------------------+-------+ 2400 2401Several additional directives not required by the C89 standard are included for 2402convenience. These parameters all correspond to ISO 8601 date values. 2403 2404+-----------+--------------------------------+------------------------+-------+ 2405| Directive | Meaning | Example | Notes | 2406+===========+================================+========================+=======+ 2407| ``%G`` | ISO 8601 year with century | 0001, 0002, ..., 2013, | \(8) | 2408| | representing the year that | 2014, ..., 9998, 9999 | | 2409| | contains the greater part of | | | 2410| | the ISO week (``%V``). | | | 2411+-----------+--------------------------------+------------------------+-------+ 2412| ``%u`` | ISO 8601 weekday as a decimal | 1, 2, ..., 7 | | 2413| | number where 1 is Monday. | | | 2414+-----------+--------------------------------+------------------------+-------+ 2415| ``%V`` | ISO 8601 week as a decimal | 01, 02, ..., 53 | \(8), | 2416| | number with Monday as | | \(9) | 2417| | the first day of the week. | | | 2418| | Week 01 is the week containing | | | 2419| | Jan 4. | | | 2420+-----------+--------------------------------+------------------------+-------+ 2421 2422These may not be available on all platforms when used with the :meth:`strftime` 2423method. The ISO 8601 year and ISO 8601 week directives are not interchangeable 2424with the year and week number directives above. Calling :meth:`strptime` with 2425incomplete or ambiguous ISO 8601 directives will raise a :exc:`ValueError`. 2426 2427The full set of format codes supported varies across platforms, because Python 2428calls the platform C library's :func:`strftime` function, and platform 2429variations are common. To see the full set of format codes supported on your 2430platform, consult the :manpage:`strftime(3)` documentation. 2431 2432.. versionadded:: 3.6 2433 ``%G``, ``%u`` and ``%V`` were added. 2434 2435Technical Detail 2436^^^^^^^^^^^^^^^^ 2437 2438Broadly speaking, ``d.strftime(fmt)`` acts like the :mod:`time` module's 2439``time.strftime(fmt, d.timetuple())`` although not all objects support a 2440:meth:`timetuple` method. 2441 2442For the :meth:`datetime.strptime` class method, the default value is 2443``1900-01-01T00:00:00.000``: any components not specified in the format string 2444will be pulled from the default value. [#]_ 2445 2446Using ``datetime.strptime(date_string, format)`` is equivalent to:: 2447 2448 datetime(*(time.strptime(date_string, format)[0:6])) 2449 2450except when the format includes sub-second components or timezone offset 2451information, which are supported in ``datetime.strptime`` but are discarded by 2452``time.strptime``. 2453 2454For :class:`.time` objects, the format codes for year, month, and day should not 2455be used, as :class:`time` objects have no such values. If they're used anyway, 2456``1900`` is substituted for the year, and ``1`` for the month and day. 2457 2458For :class:`date` objects, the format codes for hours, minutes, seconds, and 2459microseconds should not be used, as :class:`date` objects have no such 2460values. If they're used anyway, ``0`` is substituted for them. 2461 2462For the same reason, handling of format strings containing Unicode code points 2463that can't be represented in the charset of the current locale is also 2464platform-dependent. On some platforms such code points are preserved intact in 2465the output, while on others ``strftime`` may raise :exc:`UnicodeError` or return 2466an empty string instead. 2467 2468Notes: 2469 2470(1) 2471 Because the format depends on the current locale, care should be taken when 2472 making assumptions about the output value. Field orderings will vary (for 2473 example, "month/day/year" versus "day/month/year"), and the output may 2474 contain Unicode characters encoded using the locale's default encoding (for 2475 example, if the current locale is ``ja_JP``, the default encoding could be 2476 any one of ``eucJP``, ``SJIS``, or ``utf-8``; use :meth:`locale.getlocale` 2477 to determine the current locale's encoding). 2478 2479(2) 2480 The :meth:`strptime` method can parse years in the full [1, 9999] range, but 2481 years < 1000 must be zero-filled to 4-digit width. 2482 2483 .. versionchanged:: 3.2 2484 In previous versions, :meth:`strftime` method was restricted to 2485 years >= 1900. 2486 2487 .. versionchanged:: 3.3 2488 In version 3.2, :meth:`strftime` method was restricted to 2489 years >= 1000. 2490 2491(3) 2492 When used with the :meth:`strptime` method, the ``%p`` directive only affects 2493 the output hour field if the ``%I`` directive is used to parse the hour. 2494 2495(4) 2496 Unlike the :mod:`time` module, the :mod:`datetime` module does not support 2497 leap seconds. 2498 2499(5) 2500 When used with the :meth:`strptime` method, the ``%f`` directive 2501 accepts from one to six digits and zero pads on the right. ``%f`` is 2502 an extension to the set of format characters in the C standard (but 2503 implemented separately in datetime objects, and therefore always 2504 available). 2505 2506(6) 2507 For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty 2508 strings. 2509 2510 For an aware object: 2511 2512 ``%z`` 2513 :meth:`utcoffset` is transformed into a string of the form 2514 ``±HHMM[SS[.ffffff]]``, where ``HH`` is a 2-digit string giving the number 2515 of UTC offset hours, ``MM`` is a 2-digit string giving the number of UTC 2516 offset minutes, ``SS`` is a 2-digit string giving the number of UTC offset 2517 seconds and ``ffffff`` is a 6-digit string giving the number of UTC 2518 offset microseconds. The ``ffffff`` part is omitted when the offset is a 2519 whole number of seconds and both the ``ffffff`` and the ``SS`` part is 2520 omitted when the offset is a whole number of minutes. For example, if 2521 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is 2522 replaced with the string ``'-0330'``. 2523 2524 .. versionchanged:: 3.7 2525 The UTC offset is not restricted to a whole number of minutes. 2526 2527 .. versionchanged:: 3.7 2528 When the ``%z`` directive is provided to the :meth:`strptime` method, 2529 the UTC offsets can have a colon as a separator between hours, minutes 2530 and seconds. 2531 For example, ``'+01:00:00'`` will be parsed as an offset of one hour. 2532 In addition, providing ``'Z'`` is identical to ``'+00:00'``. 2533 2534 ``%Z`` 2535 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty 2536 string. Otherwise ``%Z`` is replaced by the returned value, which must 2537 be a string. 2538 2539 .. versionchanged:: 3.2 2540 When the ``%z`` directive is provided to the :meth:`strptime` method, an 2541 aware :class:`.datetime` object will be produced. The ``tzinfo`` of the 2542 result will be set to a :class:`timezone` instance. 2543 2544(7) 2545 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used 2546 in calculations when the day of the week and the calendar year (``%Y``) 2547 are specified. 2548 2549(8) 2550 Similar to ``%U`` and ``%W``, ``%V`` is only used in calculations when the 2551 day of the week and the ISO year (``%G``) are specified in a 2552 :meth:`strptime` format string. Also note that ``%G`` and ``%Y`` are not 2553 interchangeable. 2554 2555(9) 2556 When used with the :meth:`strptime` method, the leading zero is optional 2557 for formats ``%d``, ``%m``, ``%H``, ``%I``, ``%M``, ``%S``, ``%J``, ``%U``, 2558 ``%W``, and ``%V``. Format ``%y`` does require a leading zero. 2559 2560.. rubric:: Footnotes 2561 2562.. [#] If, that is, we ignore the effects of Relativity 2563 2564.. [#] This matches the definition of the "proleptic Gregorian" calendar in 2565 Dershowitz and Reingold's book *Calendrical Calculations*, 2566 where it's the base calendar for all computations. See the book for 2567 algorithms for converting between proleptic Gregorian ordinals and 2568 many other calendar systems. 2569 2570.. [#] See R. H. van Gent's `guide to the mathematics of the ISO 8601 calendar 2571 <https://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm>`_ 2572 for a good explanation. 2573 2574.. [#] Passing ``datetime.strptime('Feb 29', '%b %d')`` will fail since ``1900`` is not a leap year. 2575