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