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