Debian Codegraph @

Doc/library/datetime.rst

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