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