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