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