blob: 800361c54ba717aca5288a45ac0e712208f2d881 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`datetime` --- Basic date and time types
2=============================================
3
4.. module:: datetime
5 :synopsis: Basic date and time types.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Tim Peters <tim@zope.com>
8.. sectionauthor:: Tim Peters <tim@zope.com>
9.. sectionauthor:: A.M. Kuchling <amk@amk.ca>
10
Andrew Kuchling2e3743c2014-03-19 16:23:01 -040011**Source code:** :source:`Lib/datetime.py`
12
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040013--------------
14
Christian Heimes5b5e81c2007-12-31 16:14:33 +000015.. XXX what order should the types be discussed in?
Georg Brandl116aa622007-08-15 14:28:22 +000016
Brad3fb13632019-09-11 05:19:05 -040017The :mod:`datetime` module supplies classes for manipulating dates and times.
Georg Brandl116aa622007-08-15 14:28:22 +000018
Brad3fb13632019-09-11 05:19:05 -040019While date and time arithmetic is supported, the focus of the implementation is
20on efficient attribute extraction for output formatting and manipulation.
Georg Brandl116aa622007-08-15 14:28:22 +000021
Brad3fb13632019-09-11 05:19:05 -040022.. seealso::
R David Murray9075d8b2012-05-14 22:14:46 -040023
Brad3fb13632019-09-11 05:19:05 -040024 Module :mod:`calendar`
25 General calendar related functions.
26
27 Module :mod:`time`
28 Time access and conversions.
29
30 Package `dateutil <https://dateutil.readthedocs.io/en/stable/>`_
31 Third-party library with expanded time zone and parsing support.
32
33.. _datetime-naive-aware:
34
35Aware and Naive Objects
36-----------------------
37
Mathieu Dupuy4eba6772020-05-17 21:24:59 +000038Date and time objects may be categorized as "aware" or "naive".
Brad3fb13632019-09-11 05:19:05 -040039
40With sufficient knowledge of applicable algorithmic and political time
41adjustments, such as time zone and daylight saving time information,
42an **aware** object can locate itself relative to other aware objects.
43An aware object represents a specific moment in time that is not open to
44interpretation. [#]_
45
46A **naive** object does not contain enough information to unambiguously locate
47itself relative to other date/time objects. Whether a naive object represents
R David Murray539f2392012-05-14 22:17:23 -040048Coordinated Universal Time (UTC), local time, or time in some other timezone is
49purely up to the program, just like it is up to the program whether a
Brad3fb13632019-09-11 05:19:05 -040050particular number represents metres, miles, or mass. Naive objects are easy to
R David Murray539f2392012-05-14 22:17:23 -040051understand and to work with, at the cost of ignoring some aspects of reality.
Georg Brandl116aa622007-08-15 14:28:22 +000052
R David Murray539f2392012-05-14 22:17:23 -040053For applications requiring aware objects, :class:`.datetime` and :class:`.time`
Martin Panter16c7cfd2016-04-01 21:48:24 +000054objects have an optional time zone information attribute, :attr:`!tzinfo`, that
R David Murray539f2392012-05-14 22:17:23 -040055can be set to an instance of a subclass of the abstract :class:`tzinfo` class.
56These :class:`tzinfo` objects capture information about the offset from UTC
Brad3fb13632019-09-11 05:19:05 -040057time, the time zone name, and whether daylight saving time is in effect.
58
59Only one concrete :class:`tzinfo` class, the :class:`timezone` class, is
60supplied by the :mod:`datetime` module. The :class:`timezone` class can
61represent simple timezones with fixed offsets from UTC, such as UTC itself or
62North American EST and EDT timezones. Supporting timezones at deeper levels of
63detail is up to the application. The rules for time adjustment across the
Alexander Belopolsky4e749a12010-06-14 14:15:50 +000064world are more political than rational, change frequently, and there is no
65standard suitable for every application aside from UTC.
Georg Brandl116aa622007-08-15 14:28:22 +000066
Brad3fb13632019-09-11 05:19:05 -040067Constants
68---------
69
Georg Brandl116aa622007-08-15 14:28:22 +000070The :mod:`datetime` module exports the following constants:
71
Georg Brandl116aa622007-08-15 14:28:22 +000072.. data:: MINYEAR
73
Ezio Melotti35ec7f72011-10-02 12:44:50 +030074 The smallest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl116aa622007-08-15 14:28:22 +000075 :const:`MINYEAR` is ``1``.
76
77
78.. data:: MAXYEAR
79
Ezio Melotti35ec7f72011-10-02 12:44:50 +030080 The largest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl116aa622007-08-15 14:28:22 +000081 :const:`MAXYEAR` is ``9999``.
82
Georg Brandl116aa622007-08-15 14:28:22 +000083Available Types
84---------------
85
Georg Brandl116aa622007-08-15 14:28:22 +000086.. class:: date
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000087 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000088
89 An idealized naive date, assuming the current Gregorian calendar always was, and
90 always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and
91 :attr:`day`.
92
93
94.. class:: time
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000095 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000096
97 An idealized time, independent of any particular day, assuming that every day
Brad3fb13632019-09-11 05:19:05 -040098 has exactly 24\*60\*60 seconds. (There is no notion of "leap seconds" here.)
Georg Brandl116aa622007-08-15 14:28:22 +000099 Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
Martin Panter16c7cfd2016-04-01 21:48:24 +0000100 and :attr:`.tzinfo`.
Georg Brandl116aa622007-08-15 14:28:22 +0000101
102
103.. class:: datetime
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000104 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000105
106 A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`,
107 :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
Martin Panter16c7cfd2016-04-01 21:48:24 +0000108 and :attr:`.tzinfo`.
Georg Brandl116aa622007-08-15 14:28:22 +0000109
110
111.. class:: timedelta
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000112 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000113
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300114 A duration expressing the difference between two :class:`date`, :class:`.time`,
115 or :class:`.datetime` instances to microsecond resolution.
Georg Brandl116aa622007-08-15 14:28:22 +0000116
117
118.. class:: tzinfo
Martin Panter16c7cfd2016-04-01 21:48:24 +0000119 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000120
Brad3fb13632019-09-11 05:19:05 -0400121 An abstract base class for time zone information objects. These are used by the
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300122 :class:`.datetime` and :class:`.time` classes to provide a customizable notion of
Georg Brandl116aa622007-08-15 14:28:22 +0000123 time adjustment (for example, to account for time zone and/or daylight saving
124 time).
125
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000126.. class:: timezone
Martin Panter16c7cfd2016-04-01 21:48:24 +0000127 :noindex:
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000128
129 A class that implements the :class:`tzinfo` abstract base class as a
130 fixed offset from the UTC.
131
132 .. versionadded:: 3.2
133
Georg Brandl116aa622007-08-15 14:28:22 +0000134Objects of these types are immutable.
135
Georg Brandl116aa622007-08-15 14:28:22 +0000136Subclass relationships::
137
138 object
139 timedelta
140 tzinfo
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000141 timezone
Georg Brandl116aa622007-08-15 14:28:22 +0000142 time
143 date
144 datetime
145
Brad3fb13632019-09-11 05:19:05 -0400146Common Properties
147^^^^^^^^^^^^^^^^^
148
149The :class:`date`, :class:`.datetime`, :class:`.time`, and :class:`timezone` types
150share these common features:
151
152- Objects of these types are immutable.
153- Objects of these types are hashable, meaning that they can be used as
154 dictionary keys.
155- Objects of these types support efficient pickling via the :mod:`pickle` module.
156
157Determining if an Object is Aware or Naive
158^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
159
160Objects of the :class:`date` type are always naive.
161
162An object of type :class:`.time` or :class:`.datetime` may be aware or naive.
163
164A :class:`.datetime` object *d* is aware if both of the following hold:
165
1661. ``d.tzinfo`` is not ``None``
1672. ``d.tzinfo.utcoffset(d)`` does not return ``None``
168
169Otherwise, *d* is naive.
170
171A :class:`.time` object *t* is aware if both of the following hold:
172
1731. ``t.tzinfo`` is not ``None``
1742. ``t.tzinfo.utcoffset(None)`` does not return ``None``.
175
176Otherwise, *t* is naive.
177
178The distinction between aware and naive doesn't apply to :class:`timedelta`
179objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000180
181.. _datetime-timedelta:
182
183:class:`timedelta` Objects
184--------------------------
185
186A :class:`timedelta` object represents a duration, the difference between two
187dates or times.
188
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000189.. class:: timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000190
Brad3fb13632019-09-11 05:19:05 -0400191 All arguments are optional and default to ``0``. Arguments may be integers
Georg Brandl116aa622007-08-15 14:28:22 +0000192 or floats, and may be positive or negative.
193
Brad3fb13632019-09-11 05:19:05 -0400194 Only *days*, *seconds* and *microseconds* are stored internally.
195 Arguments are converted to those units:
Georg Brandl116aa622007-08-15 14:28:22 +0000196
197 * A millisecond is converted to 1000 microseconds.
198 * A minute is converted to 60 seconds.
199 * An hour is converted to 3600 seconds.
200 * A week is converted to 7 days.
201
202 and days, seconds and microseconds are then normalized so that the
203 representation is unique, with
204
205 * ``0 <= microseconds < 1000000``
206 * ``0 <= seconds < 3600*24`` (the number of seconds in one day)
207 * ``-999999999 <= days <= 999999999``
208
Brad3fb13632019-09-11 05:19:05 -0400209 The following example illustrates how any arguments besides
210 *days*, *seconds* and *microseconds* are "merged" and normalized into those
211 three resulting attributes::
212
213 >>> from datetime import timedelta
214 >>> delta = timedelta(
215 ... days=50,
216 ... seconds=27,
217 ... microseconds=10,
218 ... milliseconds=29000,
219 ... minutes=5,
220 ... hours=8,
221 ... weeks=2
222 ... )
223 >>> # Only days, seconds, and microseconds remain
224 >>> delta
225 datetime.timedelta(days=64, seconds=29156, microseconds=10)
226
Alexander Belopolsky790d2692013-08-04 14:51:35 -0400227 If any argument is a float and there are fractional microseconds,
228 the fractional microseconds left over from all arguments are
229 combined and their sum is rounded to the nearest microsecond using
Brad3fb13632019-09-11 05:19:05 -0400230 round-half-to-even tiebreaker. If no argument is a float, the
Alexander Belopolsky790d2692013-08-04 14:51:35 -0400231 conversion and normalization processes are exact (no information is
232 lost).
Georg Brandl116aa622007-08-15 14:28:22 +0000233
234 If the normalized value of days lies outside the indicated range,
235 :exc:`OverflowError` is raised.
236
237 Note that normalization of negative values may be surprising at first. For
Brad3fb13632019-09-11 05:19:05 -0400238 example::
Georg Brandl116aa622007-08-15 14:28:22 +0000239
Christian Heimes895627f2007-12-08 17:28:33 +0000240 >>> from datetime import timedelta
Georg Brandl116aa622007-08-15 14:28:22 +0000241 >>> d = timedelta(microseconds=-1)
242 >>> (d.days, d.seconds, d.microseconds)
243 (-1, 86399, 999999)
244
Georg Brandl116aa622007-08-15 14:28:22 +0000245
Brad3fb13632019-09-11 05:19:05 -0400246Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000247
248.. attribute:: timedelta.min
249
250 The most negative :class:`timedelta` object, ``timedelta(-999999999)``.
251
252
253.. attribute:: timedelta.max
254
255 The most positive :class:`timedelta` object, ``timedelta(days=999999999,
256 hours=23, minutes=59, seconds=59, microseconds=999999)``.
257
258
259.. attribute:: timedelta.resolution
260
261 The smallest possible difference between non-equal :class:`timedelta` objects,
262 ``timedelta(microseconds=1)``.
263
264Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``.
265``-timedelta.max`` is not representable as a :class:`timedelta` object.
266
267Instance attributes (read-only):
268
269+------------------+--------------------------------------------+
270| Attribute | Value |
271+==================+============================================+
272| ``days`` | Between -999999999 and 999999999 inclusive |
273+------------------+--------------------------------------------+
274| ``seconds`` | Between 0 and 86399 inclusive |
275+------------------+--------------------------------------------+
276| ``microseconds`` | Between 0 and 999999 inclusive |
277+------------------+--------------------------------------------+
278
279Supported operations:
280
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000281.. XXX this table is too wide!
Georg Brandl116aa622007-08-15 14:28:22 +0000282
283+--------------------------------+-----------------------------------------------+
284| Operation | Result |
285+================================+===============================================+
286| ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == |
287| | *t3* and *t1*-*t3* == *t2* are true. (1) |
288+--------------------------------+-----------------------------------------------+
289| ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* |
290| | == *t2* - *t3* and *t2* == *t1* + *t3* are |
Farhaan Bukhsh5b6e49a2018-07-05 00:12:05 +0530291| | true. (1)(6) |
Georg Brandl116aa622007-08-15 14:28:22 +0000292+--------------------------------+-----------------------------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000293| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer. |
Georg Brandl116aa622007-08-15 14:28:22 +0000294| | Afterwards *t1* // i == *t2* is true, |
295| | provided ``i != 0``. |
296+--------------------------------+-----------------------------------------------+
297| | In general, *t1* \* i == *t1* \* (i-1) + *t1* |
298| | is true. (1) |
299+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000300| ``t1 = t2 * f or t1 = f * t2`` | Delta multiplied by a float. The result is |
301| | rounded to the nearest multiple of |
302| | timedelta.resolution using round-half-to-even.|
303+--------------------------------+-----------------------------------------------+
Yasser Af40b4a02019-03-15 23:56:58 -0400304| ``f = t2 / t3`` | Division (3) of overall duration *t2* by |
305| | interval unit *t3*. Returns a :class:`float` |
306| | object. |
Mark Dickinson7c186e22010-04-20 22:32:49 +0000307+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000308| ``t1 = t2 / f or t1 = t2 / i`` | Delta divided by a float or an int. The result|
309| | is rounded to the nearest multiple of |
310| | timedelta.resolution using round-half-to-even.|
311+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000312| ``t1 = t2 // i`` or | The floor is computed and the remainder (if |
Brad3fb13632019-09-11 05:19:05 -0400313| ``t1 = t2 // t3`` | any) is thrown away. In the second case, an |
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000314| | integer is returned. (3) |
Mark Dickinson7c186e22010-04-20 22:32:49 +0000315+--------------------------------+-----------------------------------------------+
316| ``t1 = t2 % t3`` | The remainder is computed as a |
317| | :class:`timedelta` object. (3) |
318+--------------------------------+-----------------------------------------------+
319| ``q, r = divmod(t1, t2)`` | Computes the quotient and the remainder: |
320| | ``q = t1 // t2`` (3) and ``r = t1 % t2``. |
321| | q is an integer and r is a :class:`timedelta` |
322| | object. |
Georg Brandl116aa622007-08-15 14:28:22 +0000323+--------------------------------+-----------------------------------------------+
324| ``+t1`` | Returns a :class:`timedelta` object with the |
325| | same value. (2) |
326+--------------------------------+-----------------------------------------------+
Serhiy Storchaka3f819ca2018-10-31 02:26:06 +0200327| ``-t1`` | equivalent to |
328| | :class:`timedelta`\ (-*t1.days*, |
329| | -*t1.seconds*, -*t1.microseconds*), |
330| | and to *t1*\* -1. (1)(4) |
Georg Brandl116aa622007-08-15 14:28:22 +0000331+--------------------------------+-----------------------------------------------+
Brad3fb13632019-09-11 05:19:05 -0400332| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, |
333| | and to -*t* when ``t.days < 0``. (2) |
Georg Brandl116aa622007-08-15 14:28:22 +0000334+--------------------------------+-----------------------------------------------+
Georg Brandlf55c3152010-07-31 11:40:07 +0000335| ``str(t)`` | Returns a string in the form |
336| | ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D |
337| | is negative for negative ``t``. (5) |
338+--------------------------------+-----------------------------------------------+
Utkarsh Upadhyaycc5a65c2017-07-25 23:51:33 +0200339| ``repr(t)`` | Returns a string representation of the |
340| | :class:`timedelta` object as a constructor |
341| | call with canonical attribute values. |
Georg Brandlf55c3152010-07-31 11:40:07 +0000342+--------------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000343
Utkarsh Upadhyaycc5a65c2017-07-25 23:51:33 +0200344
Georg Brandl116aa622007-08-15 14:28:22 +0000345Notes:
346
347(1)
Brad3fb13632019-09-11 05:19:05 -0400348 This is exact but may overflow.
Georg Brandl116aa622007-08-15 14:28:22 +0000349
350(2)
Brad3fb13632019-09-11 05:19:05 -0400351 This is exact and cannot overflow.
Georg Brandl116aa622007-08-15 14:28:22 +0000352
353(3)
354 Division by 0 raises :exc:`ZeroDivisionError`.
355
356(4)
357 -*timedelta.max* is not representable as a :class:`timedelta` object.
358
Georg Brandlf55c3152010-07-31 11:40:07 +0000359(5)
Brad3fb13632019-09-11 05:19:05 -0400360 String representations of :class:`timedelta` objects are normalized
361 similarly to their internal representation. This leads to somewhat
362 unusual results for negative timedeltas. For example::
Georg Brandlf55c3152010-07-31 11:40:07 +0000363
Brad3fb13632019-09-11 05:19:05 -0400364 >>> timedelta(hours=-5)
365 datetime.timedelta(days=-1, seconds=68400)
366 >>> print(_)
367 -1 day, 19:00:00
Georg Brandlf55c3152010-07-31 11:40:07 +0000368
Farhaan Bukhsh5b6e49a2018-07-05 00:12:05 +0530369(6)
370 The expression ``t2 - t3`` will always be equal to the expression ``t2 + (-t3)`` except
371 when t3 is equal to ``timedelta.max``; in that case the former will produce a result
372 while the latter will overflow.
373
Brad3fb13632019-09-11 05:19:05 -0400374In addition to the operations listed above, :class:`timedelta` objects support
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300375certain additions and subtractions with :class:`date` and :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +0000376objects (see below).
377
Georg Brandl67b21b72010-08-17 15:07:14 +0000378.. versionchanged:: 3.2
379 Floor division and true division of a :class:`timedelta` object by another
380 :class:`timedelta` object are now supported, as are remainder operations and
Brad3fb13632019-09-11 05:19:05 -0400381 the :func:`divmod` function. True division and multiplication of a
Georg Brandl67b21b72010-08-17 15:07:14 +0000382 :class:`timedelta` object by a :class:`float` object are now supported.
Mark Dickinson7c186e22010-04-20 22:32:49 +0000383
384
Brad3fb13632019-09-11 05:19:05 -0400385Comparisons of :class:`timedelta` objects are supported, with some caveats.
Georg Brandl116aa622007-08-15 14:28:22 +0000386
Brad3fb13632019-09-11 05:19:05 -0400387The comparisons ``==`` or ``!=`` *always* return a :class:`bool`, no matter
388the type of the compared object::
389
390 >>> from datetime import timedelta
391 >>> delta1 = timedelta(seconds=57)
392 >>> delta2 = timedelta(hours=25, seconds=2)
393 >>> delta2 != delta1
394 True
395 >>> delta2 == 5
396 False
397
398For all other comparisons (such as ``<`` and ``>``), when a :class:`timedelta`
399object is compared to an object of a different type, :exc:`TypeError`
400is raised::
401
402 >>> delta2 > delta1
403 True
404 >>> delta2 > 5
405 Traceback (most recent call last):
406 File "<stdin>", line 1, in <module>
407 TypeError: '>' not supported between instances of 'datetime.timedelta' and 'int'
408
409In Boolean contexts, a :class:`timedelta` object is
Georg Brandl116aa622007-08-15 14:28:22 +0000410considered to be true if and only if it isn't equal to ``timedelta(0)``.
411
Antoine Pitroube6859d2009-11-25 23:02:32 +0000412Instance methods:
413
414.. method:: timedelta.total_seconds()
415
416 Return the total number of seconds contained in the duration. Equivalent to
Yasser Af40b4a02019-03-15 23:56:58 -0400417 ``td / timedelta(seconds=1)``. For interval units other than seconds, use the
418 division form directly (e.g. ``td / timedelta(microseconds=1)``).
Mark Dickinson0381e3f2010-05-08 14:35:02 +0000419
420 Note that for very large time intervals (greater than 270 years on
421 most platforms) this method will lose microsecond accuracy.
Antoine Pitroube6859d2009-11-25 23:02:32 +0000422
423 .. versionadded:: 3.2
424
Brad3fb13632019-09-11 05:19:05 -0400425Examples of usage: :class:`timedelta`
426^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Antoine Pitroube6859d2009-11-25 23:02:32 +0000427
Brad3fb13632019-09-11 05:19:05 -0400428An additional example of normalization::
Georg Brandl48310cd2009-01-03 21:18:54 +0000429
Brad3fb13632019-09-11 05:19:05 -0400430 >>> # Components of another_year add up to exactly 365 days
Christian Heimes895627f2007-12-08 17:28:33 +0000431 >>> from datetime import timedelta
432 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000433 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Brad3fb13632019-09-11 05:19:05 -0400434 ... minutes=50, seconds=600)
Christian Heimes895627f2007-12-08 17:28:33 +0000435 >>> year == another_year
436 True
Brad3fb13632019-09-11 05:19:05 -0400437 >>> year.total_seconds()
438 31536000.0
439
440Examples of :class:`timedelta` arithmetic::
441
442 >>> from datetime import timedelta
443 >>> year = timedelta(days=365)
Christian Heimes895627f2007-12-08 17:28:33 +0000444 >>> ten_years = 10 * year
Brad3fb13632019-09-11 05:19:05 -0400445 >>> ten_years
446 datetime.timedelta(days=3650)
447 >>> ten_years.days // 365
448 10
Christian Heimes895627f2007-12-08 17:28:33 +0000449 >>> nine_years = ten_years - year
Brad3fb13632019-09-11 05:19:05 -0400450 >>> nine_years
451 datetime.timedelta(days=3285)
delirious-lettucec7b3f0f2017-05-18 19:01:00 -0600452 >>> three_years = nine_years // 3
Christian Heimes895627f2007-12-08 17:28:33 +0000453 >>> three_years, three_years.days // 365
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +0200454 (datetime.timedelta(days=1095), 3)
Georg Brandl116aa622007-08-15 14:28:22 +0000455
456.. _datetime-date:
457
458:class:`date` Objects
459---------------------
460
461A :class:`date` object represents a date (year, month and day) in an idealized
462calendar, the current Gregorian calendar indefinitely extended in both
Brad3fb13632019-09-11 05:19:05 -0400463directions.
Georg Brandl116aa622007-08-15 14:28:22 +0000464
Brad3fb13632019-09-11 05:19:05 -0400465January 1 of year 1 is called day number 1, January 2 of year 1 is
466called day number 2, and so on. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +0000467
468.. class:: date(year, month, day)
469
Brad3fb13632019-09-11 05:19:05 -0400470 All arguments are required. Arguments must be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000471 ranges:
472
473 * ``MINYEAR <= year <= MAXYEAR``
474 * ``1 <= month <= 12``
475 * ``1 <= day <= number of days in the given month and year``
476
477 If an argument outside those ranges is given, :exc:`ValueError` is raised.
478
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000479
Georg Brandl116aa622007-08-15 14:28:22 +0000480Other constructors, all class methods:
481
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000482.. classmethod:: date.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000483
Brad3fb13632019-09-11 05:19:05 -0400484 Return the current local date.
Georg Brandl116aa622007-08-15 14:28:22 +0000485
Brad3fb13632019-09-11 05:19:05 -0400486 This is equivalent to ``date.fromtimestamp(time.time())``.
Georg Brandl116aa622007-08-15 14:28:22 +0000487
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000488.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000489
Brad3fb13632019-09-11 05:19:05 -0400490 Return the local date corresponding to the POSIX timestamp, such as is
491 returned by :func:`time.time`.
492
493 This may raise :exc:`OverflowError`, if the timestamp is out
494 of the range of values supported by the platform C :c:func:`localtime`
495 function, and :exc:`OSError` on :c:func:`localtime` failure.
496 It's common for this to be restricted to years from 1970 through 2038. Note
Georg Brandl116aa622007-08-15 14:28:22 +0000497 that on non-POSIX systems that include leap seconds in their notion of a
498 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
499
Victor Stinner5d272cc2012-03-13 13:35:55 +0100500 .. versionchanged:: 3.3
501 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
502 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100503 :c:func:`localtime` function. Raise :exc:`OSError` instead of
504 :exc:`ValueError` on :c:func:`localtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100505
Georg Brandl116aa622007-08-15 14:28:22 +0000506
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000507.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000508
Brad3fb13632019-09-11 05:19:05 -0400509 Return the date corresponding to the proleptic Gregorian ordinal, where
510 January 1 of year 1 has ordinal 1.
511
512 :exc:`ValueError` is raised unless ``1 <= ordinal <=
513 date.max.toordinal()``. For any date *d*,
514 ``date.fromordinal(d.toordinal()) == d``.
Georg Brandl116aa622007-08-15 14:28:22 +0000515
Georg Brandl116aa622007-08-15 14:28:22 +0000516
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500517.. classmethod:: date.fromisoformat(date_string)
518
Brad3fb13632019-09-11 05:19:05 -0400519 Return a :class:`date` corresponding to a *date_string* given in the format
520 ``YYYY-MM-DD``::
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500521
Brad3fb13632019-09-11 05:19:05 -0400522 >>> from datetime import date
523 >>> date.fromisoformat('2019-12-04')
524 datetime.date(2019, 12, 4)
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500525
Brad3fb13632019-09-11 05:19:05 -0400526 This is the inverse of :meth:`date.isoformat`. It only supports the format
527 ``YYYY-MM-DD``.
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500528
Brad3fb13632019-09-11 05:19:05 -0400529 .. versionadded:: 3.7
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500530
531
Paul Ganssle88c09372019-04-29 09:22:03 -0400532.. classmethod:: date.fromisocalendar(year, week, day)
533
534 Return a :class:`date` corresponding to the ISO calendar date specified by
535 year, week and day. This is the inverse of the function :meth:`date.isocalendar`.
536
537 .. versionadded:: 3.8
538
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500539
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000540Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000541
542.. attribute:: date.min
543
544 The earliest representable date, ``date(MINYEAR, 1, 1)``.
545
546
547.. attribute:: date.max
548
549 The latest representable date, ``date(MAXYEAR, 12, 31)``.
550
551
552.. attribute:: date.resolution
553
554 The smallest possible difference between non-equal date objects,
555 ``timedelta(days=1)``.
556
Georg Brandl116aa622007-08-15 14:28:22 +0000557
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000558Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000559
560.. attribute:: date.year
561
562 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
563
564
565.. attribute:: date.month
566
567 Between 1 and 12 inclusive.
568
569
570.. attribute:: date.day
571
572 Between 1 and the number of days in the given month of the given year.
573
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000574
Georg Brandl116aa622007-08-15 14:28:22 +0000575Supported operations:
576
577+-------------------------------+----------------------------------------------+
578| Operation | Result |
579+===============================+==============================================+
580| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
Brad3fb13632019-09-11 05:19:05 -0400581| | from *date1*. (1) |
Georg Brandl116aa622007-08-15 14:28:22 +0000582+-------------------------------+----------------------------------------------+
583| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
584| | timedelta == date1``. (2) |
585+-------------------------------+----------------------------------------------+
586| ``timedelta = date1 - date2`` | \(3) |
587+-------------------------------+----------------------------------------------+
588| ``date1 < date2`` | *date1* is considered less than *date2* when |
589| | *date1* precedes *date2* in time. (4) |
590+-------------------------------+----------------------------------------------+
591
592Notes:
593
594(1)
595 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
Brad3fb13632019-09-11 05:19:05 -0400596 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
Georg Brandl116aa622007-08-15 14:28:22 +0000597 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
598 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
599 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
600
601(2)
Georg Brandl116aa622007-08-15 14:28:22 +0000602 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
603
604(3)
Brad3fb13632019-09-11 05:19:05 -0400605 This is exact, and cannot overflow. timedelta.seconds and
Georg Brandl116aa622007-08-15 14:28:22 +0000606 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
607
608(4)
609 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
Danish Prakash9c223792018-09-12 02:29:23 +0530610 date2.toordinal()``. Date comparison raises :exc:`TypeError` if
611 the other comparand isn't also a :class:`date` object. However,
612 ``NotImplemented`` is returned instead if the other comparand has a
Brad3fb13632019-09-11 05:19:05 -0400613 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
Georg Brandl116aa622007-08-15 14:28:22 +0000614 chance at implementing mixed-type comparison. If not, when a :class:`date`
615 object is compared to an object of a different type, :exc:`TypeError` is raised
Brad3fb13632019-09-11 05:19:05 -0400616 unless the comparison is ``==`` or ``!=``. The latter cases return
Georg Brandl116aa622007-08-15 14:28:22 +0000617 :const:`False` or :const:`True`, respectively.
618
Brad3fb13632019-09-11 05:19:05 -0400619In Boolean contexts, all :class:`date` objects are considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +0000620
621Instance methods:
622
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400623.. method:: date.replace(year=self.year, month=self.month, day=self.day)
Georg Brandl116aa622007-08-15 14:28:22 +0000624
Senthil Kumarana6bac952011-07-04 11:28:30 -0700625 Return a date with the same value, except for those parameters given new
Brad3fb13632019-09-11 05:19:05 -0400626 values by whichever keyword arguments are specified.
627
628 Example::
629
630 >>> from datetime import date
631 >>> d = date(2002, 12, 31)
632 >>> d.replace(day=26)
633 datetime.date(2002, 12, 26)
Georg Brandl116aa622007-08-15 14:28:22 +0000634
635
636.. method:: date.timetuple()
637
638 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
Brad3fb13632019-09-11 05:19:05 -0400639
640 The hours, minutes and seconds are 0, and the DST flag is -1.
641
642 ``d.timetuple()`` is equivalent to::
643
644 time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1))
645
646 where ``yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1``
647 is the day number within the current year starting with ``1`` for January 1st.
Georg Brandl116aa622007-08-15 14:28:22 +0000648
649
650.. method:: date.toordinal()
651
652 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
Brad3fb13632019-09-11 05:19:05 -0400653 has ordinal 1. For any :class:`date` object *d*,
Georg Brandl116aa622007-08-15 14:28:22 +0000654 ``date.fromordinal(d.toordinal()) == d``.
655
656
657.. method:: date.weekday()
658
659 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
660 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
661 :meth:`isoweekday`.
662
663
664.. method:: date.isoweekday()
665
666 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
667 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
668 :meth:`weekday`, :meth:`isocalendar`.
669
670
671.. method:: date.isocalendar()
672
Paul Ganssle1b97b9b2020-05-16 10:02:59 -0400673 Return a :term:`named tuple` object with three components: ``year``,
674 ``week`` and ``weekday``.
Georg Brandl116aa622007-08-15 14:28:22 +0000675
Brad3fb13632019-09-11 05:19:05 -0400676 The ISO calendar is a widely used variant of the Gregorian calendar. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +0000677
678 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
Brad3fb13632019-09-11 05:19:05 -0400679 Monday and ends on a Sunday. The first week of an ISO year is the first
Georg Brandl116aa622007-08-15 14:28:22 +0000680 (Gregorian) calendar week of a year containing a Thursday. This is called week
681 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
682
683 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
Brad3fb13632019-09-11 05:19:05 -0400684 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004::
Georg Brandl116aa622007-08-15 14:28:22 +0000685
Paul Ganssle1b97b9b2020-05-16 10:02:59 -0400686 >>> from datetime import date
687 >>> date(2003, 12, 29).isocalendar()
688 datetime.IsoCalendarDate(year=2004, week=1, weekday=1)
689 >>> date(2004, 1, 4).isocalendar()
690 datetime.IsoCalendarDate(year=2004, week=1, weekday=7)
691
692 .. versionchanged:: 3.9
693 Result changed from a tuple to a :term:`named tuple`.
Georg Brandl116aa622007-08-15 14:28:22 +0000694
695.. method:: date.isoformat()
696
Brad3fb13632019-09-11 05:19:05 -0400697 Return a string representing the date in ISO 8601 format, ``YYYY-MM-DD``::
Georg Brandl116aa622007-08-15 14:28:22 +0000698
Brad3fb13632019-09-11 05:19:05 -0400699 >>> from datetime import date
700 >>> date(2002, 12, 4).isoformat()
701 '2002-12-04'
702
703 This is the inverse of :meth:`date.fromisoformat`.
Georg Brandl116aa622007-08-15 14:28:22 +0000704
705.. method:: date.__str__()
706
707 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
708
709
710.. method:: date.ctime()
711
Brad3fb13632019-09-11 05:19:05 -0400712 Return a string representing the date::
713
714 >>> from datetime import date
715 >>> date(2002, 12, 4).ctime()
716 'Wed Dec 4 00:00:00 2002'
717
718 ``d.ctime()`` is equivalent to::
719
720 time.ctime(time.mktime(d.timetuple()))
721
722 on platforms where the native C
Georg Brandl60203b42010-10-06 10:11:56 +0000723 :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +0000724 :meth:`date.ctime` does not invoke) conforms to the C standard.
725
726
727.. method:: date.strftime(format)
728
729 Return a string representing the date, controlled by an explicit format string.
David Wolever569a5fa2013-08-12 16:56:02 -0400730 Format codes referring to hours, minutes or seconds will see 0 values. For a
731 complete list of formatting directives, see
732 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000733
Georg Brandl116aa622007-08-15 14:28:22 +0000734
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300735.. method:: date.__format__(format)
736
Martin Panterd5db1472016-02-08 01:34:09 +0000737 Same as :meth:`.date.strftime`. This makes it possible to specify a format
Martin Panterbc1ee462016-02-13 00:41:37 +0000738 string for a :class:`.date` object in :ref:`formatted string
739 literals <f-strings>` and when using :meth:`str.format`. For a
David Wolever569a5fa2013-08-12 16:56:02 -0400740 complete list of formatting directives, see
741 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300742
Brad3fb13632019-09-11 05:19:05 -0400743Examples of Usage: :class:`date`
744^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300745
Christian Heimes895627f2007-12-08 17:28:33 +0000746Example of counting days to an event::
747
748 >>> import time
749 >>> from datetime import date
750 >>> today = date.today()
751 >>> today
752 datetime.date(2007, 12, 5)
753 >>> today == date.fromtimestamp(time.time())
754 True
755 >>> my_birthday = date(today.year, 6, 24)
756 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000757 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000758 >>> my_birthday
759 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000760 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000761 >>> time_to_birthday.days
762 202
763
Brad3fb13632019-09-11 05:19:05 -0400764More examples of working with :class:`date`:
Christian Heimesfe337bf2008-03-23 21:54:12 +0000765
766.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000767
768 >>> from datetime import date
769 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
770 >>> d
771 datetime.date(2002, 3, 11)
Brad3fb13632019-09-11 05:19:05 -0400772
773 >>> # Methods related to formatting string output
774 >>> d.isoformat()
775 '2002-03-11'
776 >>> d.strftime("%d/%m/%y")
777 '11/03/02'
778 >>> d.strftime("%A %d. %B %Y")
779 'Monday 11. March 2002'
780 >>> d.ctime()
781 'Mon Mar 11 00:00:00 2002'
782 >>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")
783 'The day is 11, the month is March.'
784
785 >>> # Methods for to extracting 'components' under different calendars
Christian Heimes895627f2007-12-08 17:28:33 +0000786 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000787 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000788 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000789 2002 # year
790 3 # month
791 11 # day
792 0
793 0
794 0
795 0 # weekday (0 = Monday)
796 70 # 70th day in the year
797 -1
798 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000799 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000800 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000801 2002 # ISO year
802 11 # ISO week number
803 1 # ISO day number ( 1 = Monday )
Brad3fb13632019-09-11 05:19:05 -0400804
805 >>> # A date object is immutable; all operations produce a new object
806 >>> d.replace(year=2005)
807 datetime.date(2005, 3, 11)
Christian Heimes895627f2007-12-08 17:28:33 +0000808
Georg Brandl116aa622007-08-15 14:28:22 +0000809
810.. _datetime-datetime:
811
Benjamin Petersond87dd432015-04-25 14:15:16 -0400812:class:`.datetime` Objects
813--------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000814
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300815A :class:`.datetime` object is a single object containing all the information
Brad3fb13632019-09-11 05:19:05 -0400816from a :class:`date` object and a :class:`.time` object.
817
818Like a :class:`date` object, :class:`.datetime` assumes the current Gregorian
819calendar extended in both directions; like a :class:`.time` object,
820:class:`.datetime` assumes there are exactly 3600\*24 seconds in every day.
Georg Brandl116aa622007-08-15 14:28:22 +0000821
822Constructor:
823
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400824.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000825
Brad3fb13632019-09-11 05:19:05 -0400826 The *year*, *month* and *day* arguments are required. *tzinfo* may be ``None``, or an
827 instance of a :class:`tzinfo` subclass. The remaining arguments must be integers
Georg Brandl5c106642007-11-29 17:41:05 +0000828 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000829
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400830 * ``MINYEAR <= year <= MAXYEAR``,
831 * ``1 <= month <= 12``,
832 * ``1 <= day <= number of days in the given month and year``,
833 * ``0 <= hour < 24``,
834 * ``0 <= minute < 60``,
835 * ``0 <= second < 60``,
836 * ``0 <= microsecond < 1000000``,
837 * ``fold in [0, 1]``.
Georg Brandl116aa622007-08-15 14:28:22 +0000838
839 If an argument outside those ranges is given, :exc:`ValueError` is raised.
840
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400841 .. versionadded:: 3.6
842 Added the ``fold`` argument.
843
Georg Brandl116aa622007-08-15 14:28:22 +0000844Other constructors, all class methods:
845
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000846.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000847
Brad3fb13632019-09-11 05:19:05 -0400848 Return the current local datetime, with :attr:`.tzinfo` ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000849
Brad3fb13632019-09-11 05:19:05 -0400850 Equivalent to::
851
852 datetime.fromtimestamp(time.time())
853
854 See also :meth:`now`, :meth:`fromtimestamp`.
855
856 This method is functionally equivalent to :meth:`now`, but without a
857 ``tz`` parameter.
Georg Brandl116aa622007-08-15 14:28:22 +0000858
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000859.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000860
Brad3fb13632019-09-11 05:19:05 -0400861 Return the current local date and time.
862
863 If optional argument *tz* is ``None``
Georg Brandl116aa622007-08-15 14:28:22 +0000864 or not specified, this is like :meth:`today`, but, if possible, supplies more
865 precision than can be gotten from going through a :func:`time.time` timestamp
866 (for example, this may be possible on platforms supplying the C
Georg Brandl60203b42010-10-06 10:11:56 +0000867 :c:func:`gettimeofday` function).
Georg Brandl116aa622007-08-15 14:28:22 +0000868
Joannah Nanjekye1a53c782019-09-11 14:58:42 +0100869 If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` subclass,
870 and the current date and time are converted to *tz*’s time zone.
Brad3fb13632019-09-11 05:19:05 -0400871
Joannah Nanjekye1a53c782019-09-11 14:58:42 +0100872 This function is preferred over :meth:`today` and :meth:`utcnow`.
Georg Brandl116aa622007-08-15 14:28:22 +0000873
874
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000875.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000876
Brad3fb13632019-09-11 05:19:05 -0400877 Return the current UTC date and time, with :attr:`.tzinfo` ``None``.
878
879 This is like :meth:`now`, but returns the current UTC date and time, as a naive
880 :class:`.datetime` object. An aware current UTC datetime can be obtained by
881 calling ``datetime.now(timezone.utc)``. See also :meth:`now`.
Georg Brandl116aa622007-08-15 14:28:22 +0000882
Joannah Nanjekye1a53c782019-09-11 14:58:42 +0100883 .. warning::
884
885 Because naive ``datetime`` objects are treated by many ``datetime`` methods
886 as local times, it is preferred to use aware datetimes to represent times
887 in UTC. As such, the recommended way to create an object representing the
Ofek Lev575d0b42019-12-01 00:44:21 -0500888 current time in UTC is by calling ``datetime.now(timezone.utc)``.
Joannah Nanjekye1a53c782019-09-11 14:58:42 +0100889
890
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000891.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000892
893 Return the local date and time corresponding to the POSIX timestamp, such as is
894 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
895 specified, the timestamp is converted to the platform's local date and time, and
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300896 the returned :class:`.datetime` object is naive.
Georg Brandl116aa622007-08-15 14:28:22 +0000897
Martin Panter16c7cfd2016-04-01 21:48:24 +0000898 If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` subclass, and the
Brad3fb13632019-09-11 05:19:05 -0400899 timestamp is converted to *tz*’s time zone.
900
Victor Stinnerecc6e662012-03-14 00:39:29 +0100901 :meth:`fromtimestamp` may raise :exc:`OverflowError`, if the timestamp is out of
Georg Brandl60203b42010-10-06 10:11:56 +0000902 the range of values supported by the platform C :c:func:`localtime` or
Victor Stinnerecc6e662012-03-14 00:39:29 +0100903 :c:func:`gmtime` functions, and :exc:`OSError` on :c:func:`localtime` or
904 :c:func:`gmtime` failure.
905 It's common for this to be restricted to years in
Georg Brandl116aa622007-08-15 14:28:22 +0000906 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
907 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
908 and then it's possible to have two timestamps differing by a second that yield
Joannah Nanjekye1a53c782019-09-11 14:58:42 +0100909 identical :class:`.datetime` objects. This method is preferred over
910 :meth:`utcfromtimestamp`.
Georg Brandl116aa622007-08-15 14:28:22 +0000911
Victor Stinner5d272cc2012-03-13 13:35:55 +0100912 .. versionchanged:: 3.3
913 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
914 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100915 :c:func:`localtime` or :c:func:`gmtime` functions. Raise :exc:`OSError`
916 instead of :exc:`ValueError` on :c:func:`localtime` or :c:func:`gmtime`
917 failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100918
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400919 .. versionchanged:: 3.6
920 :meth:`fromtimestamp` may return instances with :attr:`.fold` set to 1.
Georg Brandl116aa622007-08-15 14:28:22 +0000921
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000922.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000923
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300924 Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with
Brad3fb13632019-09-11 05:19:05 -0400925 :attr:`.tzinfo` ``None``. (The resulting object is naive.)
926
927 This may raise :exc:`OverflowError`, if the timestamp is
Victor Stinnerecc6e662012-03-14 00:39:29 +0100928 out of the range of values supported by the platform C :c:func:`gmtime` function,
929 and :exc:`OSError` on :c:func:`gmtime` failure.
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500930 It's common for this to be restricted to years in 1970 through 2038.
Georg Brandl116aa622007-08-15 14:28:22 +0000931
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500932 To get an aware :class:`.datetime` object, call :meth:`fromtimestamp`::
Alexander Belopolsky54afa552011-04-25 13:00:40 -0400933
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500934 datetime.fromtimestamp(timestamp, timezone.utc)
935
936 On the POSIX compliant platforms, it is equivalent to the following
937 expression::
938
939 datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)
940
941 except the latter formula always supports the full years range: between
942 :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
Alexander Belopolsky54afa552011-04-25 13:00:40 -0400943
Joannah Nanjekye1a53c782019-09-11 14:58:42 +0100944 .. warning::
945
946 Because naive ``datetime`` objects are treated by many ``datetime`` methods
947 as local times, it is preferred to use aware datetimes to represent times
948 in UTC. As such, the recommended way to create an object representing a
Ofek Lev575d0b42019-12-01 00:44:21 -0500949 specific timestamp in UTC is by calling
Joannah Nanjekye1a53c782019-09-11 14:58:42 +0100950 ``datetime.fromtimestamp(timestamp, tz=timezone.utc)``.
951
Victor Stinner5d272cc2012-03-13 13:35:55 +0100952 .. versionchanged:: 3.3
953 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
954 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100955 :c:func:`gmtime` function. Raise :exc:`OSError` instead of
956 :exc:`ValueError` on :c:func:`gmtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100957
Georg Brandl116aa622007-08-15 14:28:22 +0000958
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000959.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000960
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300961 Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal,
Georg Brandl116aa622007-08-15 14:28:22 +0000962 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
Brad3fb13632019-09-11 05:19:05 -0400963 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
Martin Panter16c7cfd2016-04-01 21:48:24 +0000964 microsecond of the result are all 0, and :attr:`.tzinfo` is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000965
966
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400967.. classmethod:: datetime.combine(date, time, tzinfo=self.tzinfo)
Georg Brandl116aa622007-08-15 14:28:22 +0000968
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300969 Return a new :class:`.datetime` object whose date components are equal to the
Alexander Belopolsky43746c32016-08-02 17:49:30 -0400970 given :class:`date` object's, and whose time components
Brad3fb13632019-09-11 05:19:05 -0400971 are equal to the given :class:`.time` object's. If the *tzinfo*
Alexander Belopolsky43746c32016-08-02 17:49:30 -0400972 argument is provided, its value is used to set the :attr:`.tzinfo` attribute
973 of the result, otherwise the :attr:`~.time.tzinfo` attribute of the *time* argument
974 is used.
975
976 For any :class:`.datetime` object *d*,
Brad3fb13632019-09-11 05:19:05 -0400977 ``d == datetime.combine(d.date(), d.time(), d.tzinfo)``. If date is a
Martin Panter16c7cfd2016-04-01 21:48:24 +0000978 :class:`.datetime` object, its time components and :attr:`.tzinfo` attributes
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800979 are ignored.
Georg Brandl116aa622007-08-15 14:28:22 +0000980
Alexander Belopolsky43746c32016-08-02 17:49:30 -0400981 .. versionchanged:: 3.6
982 Added the *tzinfo* argument.
983
Georg Brandl116aa622007-08-15 14:28:22 +0000984
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500985.. classmethod:: datetime.fromisoformat(date_string)
986
Brad3fb13632019-09-11 05:19:05 -0400987 Return a :class:`.datetime` corresponding to a *date_string* in one of the
988 formats emitted by :meth:`date.isoformat` and :meth:`datetime.isoformat`.
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500989
Brad3fb13632019-09-11 05:19:05 -0400990 Specifically, this function supports strings in the format:
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500991
Brad3fb13632019-09-11 05:19:05 -0400992 .. code-block:: none
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500993
Brad3fb13632019-09-11 05:19:05 -0400994 YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]]
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500995
Brad3fb13632019-09-11 05:19:05 -0400996 where ``*`` can match any single character.
997
998 .. caution::
999
1000 This does *not* support parsing arbitrary ISO 8601 strings - it is only intended
1001 as the inverse operation of :meth:`datetime.isoformat`. A more full-featured
1002 ISO 8601 parser, ``dateutil.parser.isoparse`` is available in the third-party package
1003 `dateutil <https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.isoparse>`__.
Brad3fb13632019-09-11 05:19:05 -04001004
1005 Examples::
1006
1007 >>> from datetime import datetime
1008 >>> datetime.fromisoformat('2011-11-04')
1009 datetime.datetime(2011, 11, 4, 0, 0)
1010 >>> datetime.fromisoformat('2011-11-04T00:05:23')
1011 datetime.datetime(2011, 11, 4, 0, 5, 23)
1012 >>> datetime.fromisoformat('2011-11-04 00:05:23.283')
1013 datetime.datetime(2011, 11, 4, 0, 5, 23, 283000)
1014 >>> datetime.fromisoformat('2011-11-04 00:05:23.283+00:00')
1015 datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.timezone.utc)
1016 >>> datetime.fromisoformat('2011-11-04T00:05:23+04:00') # doctest: +NORMALIZE_WHITESPACE
1017 datetime.datetime(2011, 11, 4, 0, 5, 23,
1018 tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))
1019
1020 .. versionadded:: 3.7
Paul Ganssle88c09372019-04-29 09:22:03 -04001021
1022.. classmethod:: datetime.fromisocalendar(year, week, day)
1023
Brad3fb13632019-09-11 05:19:05 -04001024 Return a :class:`.datetime` corresponding to the ISO calendar date specified
Paul Ganssle88c09372019-04-29 09:22:03 -04001025 by year, week and day. The non-date components of the datetime are populated
1026 with their normal default values. This is the inverse of the function
1027 :meth:`datetime.isocalendar`.
1028
1029 .. versionadded:: 3.8
1030
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001031.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +00001032
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001033 Return a :class:`.datetime` corresponding to *date_string*, parsed according to
Brad3fb13632019-09-11 05:19:05 -04001034 *format*.
1035
1036 This is equivalent to::
1037
1038 datetime(*(time.strptime(date_string, format)[0:6]))
1039
1040 :exc:`ValueError` is raised if the date_string and format
Georg Brandl116aa622007-08-15 14:28:22 +00001041 can't be parsed by :func:`time.strptime` or if it returns a value which isn't a
David Wolever569a5fa2013-08-12 16:56:02 -04001042 time tuple. For a complete list of formatting directives, see
1043 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001044
Georg Brandl116aa622007-08-15 14:28:22 +00001045
Georg Brandl116aa622007-08-15 14:28:22 +00001046
1047Class attributes:
1048
Georg Brandl116aa622007-08-15 14:28:22 +00001049.. attribute:: datetime.min
1050
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001051 The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1,
Georg Brandl116aa622007-08-15 14:28:22 +00001052 tzinfo=None)``.
1053
1054
1055.. attribute:: datetime.max
1056
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001057 The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
Georg Brandl116aa622007-08-15 14:28:22 +00001058 59, 999999, tzinfo=None)``.
1059
1060
1061.. attribute:: datetime.resolution
1062
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001063 The smallest possible difference between non-equal :class:`.datetime` objects,
Georg Brandl116aa622007-08-15 14:28:22 +00001064 ``timedelta(microseconds=1)``.
1065
Georg Brandl116aa622007-08-15 14:28:22 +00001066
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001067Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001068
1069.. attribute:: datetime.year
1070
1071 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
1072
1073
1074.. attribute:: datetime.month
1075
1076 Between 1 and 12 inclusive.
1077
1078
1079.. attribute:: datetime.day
1080
1081 Between 1 and the number of days in the given month of the given year.
1082
1083
1084.. attribute:: datetime.hour
1085
1086 In ``range(24)``.
1087
1088
1089.. attribute:: datetime.minute
1090
1091 In ``range(60)``.
1092
1093
1094.. attribute:: datetime.second
1095
1096 In ``range(60)``.
1097
1098
1099.. attribute:: datetime.microsecond
1100
1101 In ``range(1000000)``.
1102
1103
1104.. attribute:: datetime.tzinfo
1105
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001106 The object passed as the *tzinfo* argument to the :class:`.datetime` constructor,
Georg Brandl116aa622007-08-15 14:28:22 +00001107 or ``None`` if none was passed.
1108
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001109
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001110.. attribute:: datetime.fold
1111
Brad3fb13632019-09-11 05:19:05 -04001112 In ``[0, 1]``. Used to disambiguate wall times during a repeated interval. (A
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001113 repeated interval occurs when clocks are rolled back at the end of daylight saving
1114 time or when the UTC offset for the current zone is decreased for political reasons.)
1115 The value 0 (1) represents the earlier (later) of the two moments with the same wall
1116 time representation.
1117
1118 .. versionadded:: 3.6
1119
Georg Brandl116aa622007-08-15 14:28:22 +00001120Supported operations:
1121
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001122+---------------------------------------+--------------------------------+
1123| Operation | Result |
1124+=======================================+================================+
1125| ``datetime2 = datetime1 + timedelta`` | \(1) |
1126+---------------------------------------+--------------------------------+
1127| ``datetime2 = datetime1 - timedelta`` | \(2) |
1128+---------------------------------------+--------------------------------+
1129| ``timedelta = datetime1 - datetime2`` | \(3) |
1130+---------------------------------------+--------------------------------+
1131| ``datetime1 < datetime2`` | Compares :class:`.datetime` to |
1132| | :class:`.datetime`. (4) |
1133+---------------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001134
1135(1)
1136 datetime2 is a duration of timedelta removed from datetime1, moving forward in
Brad3fb13632019-09-11 05:19:05 -04001137 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
Martin Panter16c7cfd2016-04-01 21:48:24 +00001138 result has the same :attr:`~.datetime.tzinfo` attribute as the input datetime, and
Senthil Kumarana6bac952011-07-04 11:28:30 -07001139 datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
1140 datetime2.year would be smaller than :const:`MINYEAR` or larger than
1141 :const:`MAXYEAR`. Note that no time zone adjustments are done even if the
1142 input is an aware object.
Georg Brandl116aa622007-08-15 14:28:22 +00001143
1144(2)
1145 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
Martin Panter16c7cfd2016-04-01 21:48:24 +00001146 addition, the result has the same :attr:`~.datetime.tzinfo` attribute as the input
Senthil Kumarana6bac952011-07-04 11:28:30 -07001147 datetime, and no time zone adjustments are done even if the input is aware.
Georg Brandl116aa622007-08-15 14:28:22 +00001148
1149(3)
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001150 Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if
Brad3fb13632019-09-11 05:19:05 -04001151 both operands are naive, or if both are aware. If one is aware and the other is
Georg Brandl116aa622007-08-15 14:28:22 +00001152 naive, :exc:`TypeError` is raised.
1153
Martin Panter16c7cfd2016-04-01 21:48:24 +00001154 If both are naive, or both are aware and have the same :attr:`~.datetime.tzinfo` attribute,
1155 the :attr:`~.datetime.tzinfo` attributes are ignored, and the result is a :class:`timedelta`
Brad3fb13632019-09-11 05:19:05 -04001156 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
Georg Brandl116aa622007-08-15 14:28:22 +00001157 are done in this case.
1158
Martin Panter16c7cfd2016-04-01 21:48:24 +00001159 If both are aware and have different :attr:`~.datetime.tzinfo` attributes, ``a-b`` acts
Brad3fb13632019-09-11 05:19:05 -04001160 as if *a* and *b* were first converted to naive UTC datetimes first. The
Senthil Kumarana6bac952011-07-04 11:28:30 -07001161 result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
1162 - b.utcoffset())`` except that the implementation never overflows.
Georg Brandl116aa622007-08-15 14:28:22 +00001163
1164(4)
1165 *datetime1* is considered less than *datetime2* when *datetime1* precedes
1166 *datetime2* in time.
1167
Alexander Belopolsky08313822012-06-15 20:19:47 -04001168 If one comparand is naive and the other is aware, :exc:`TypeError`
Brad3fb13632019-09-11 05:19:05 -04001169 is raised if an order comparison is attempted. For equality
Alexander Belopolsky08313822012-06-15 20:19:47 -04001170 comparisons, naive instances are never equal to aware instances.
1171
Martin Panter16c7cfd2016-04-01 21:48:24 +00001172 If both comparands are aware, and have the same :attr:`~.datetime.tzinfo` attribute, the
1173 common :attr:`~.datetime.tzinfo` attribute is ignored and the base datetimes are
Brad3fb13632019-09-11 05:19:05 -04001174 compared. If both comparands are aware and have different :attr:`~.datetime.tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -07001175 attributes, the comparands are first adjusted by subtracting their UTC
1176 offsets (obtained from ``self.utcoffset()``).
Georg Brandl116aa622007-08-15 14:28:22 +00001177
Alexander Belopolsky08313822012-06-15 20:19:47 -04001178 .. versionchanged:: 3.3
Brad3fb13632019-09-11 05:19:05 -04001179 Equality comparisons between aware and naive :class:`.datetime`
Éric Araujob0f08952012-06-24 16:22:09 -04001180 instances don't raise :exc:`TypeError`.
Alexander Belopolsky08313822012-06-15 20:19:47 -04001181
Georg Brandl116aa622007-08-15 14:28:22 +00001182 .. note::
1183
1184 In order to stop comparison from falling back to the default scheme of comparing
1185 object addresses, datetime comparison normally raises :exc:`TypeError` if the
Brad3fb13632019-09-11 05:19:05 -04001186 other comparand isn't also a :class:`.datetime` object. However,
Georg Brandl116aa622007-08-15 14:28:22 +00001187 ``NotImplemented`` is returned instead if the other comparand has a
Brad3fb13632019-09-11 05:19:05 -04001188 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
1189 chance at implementing mixed-type comparison. If not, when a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +00001190 object is compared to an object of a different type, :exc:`TypeError` is raised
Brad3fb13632019-09-11 05:19:05 -04001191 unless the comparison is ``==`` or ``!=``. The latter cases return
Georg Brandl116aa622007-08-15 14:28:22 +00001192 :const:`False` or :const:`True`, respectively.
1193
Georg Brandl116aa622007-08-15 14:28:22 +00001194Instance methods:
1195
Georg Brandl116aa622007-08-15 14:28:22 +00001196.. method:: datetime.date()
1197
1198 Return :class:`date` object with same year, month and day.
1199
1200
1201.. method:: datetime.time()
1202
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001203 Return :class:`.time` object with same hour, minute, second, microsecond and fold.
Brad3fb13632019-09-11 05:19:05 -04001204 :attr:`.tzinfo` is ``None``. See also method :meth:`timetz`.
Georg Brandl116aa622007-08-15 14:28:22 +00001205
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001206 .. versionchanged:: 3.6
1207 The fold value is copied to the returned :class:`.time` object.
1208
Georg Brandl116aa622007-08-15 14:28:22 +00001209
1210.. method:: datetime.timetz()
1211
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001212 Return :class:`.time` object with same hour, minute, second, microsecond, fold, and
Brad3fb13632019-09-11 05:19:05 -04001213 tzinfo attributes. See also method :meth:`time`.
Georg Brandl116aa622007-08-15 14:28:22 +00001214
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001215 .. versionchanged:: 3.6
1216 The fold value is copied to the returned :class:`.time` object.
Georg Brandl116aa622007-08-15 14:28:22 +00001217
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001218
1219.. method:: datetime.replace(year=self.year, month=self.month, day=self.day, \
1220 hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, \
1221 tzinfo=self.tzinfo, * fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001222
Senthil Kumarana6bac952011-07-04 11:28:30 -07001223 Return a datetime with the same attributes, except for those attributes given
Brad3fb13632019-09-11 05:19:05 -04001224 new values by whichever keyword arguments are specified. Note that
Senthil Kumarana6bac952011-07-04 11:28:30 -07001225 ``tzinfo=None`` can be specified to create a naive datetime from an aware
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001226 datetime with no conversion of date and time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001227
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001228 .. versionadded:: 3.6
1229 Added the ``fold`` argument.
1230
Georg Brandl116aa622007-08-15 14:28:22 +00001231
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001232.. method:: datetime.astimezone(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001233
Martin Panter16c7cfd2016-04-01 21:48:24 +00001234 Return a :class:`.datetime` object with new :attr:`.tzinfo` attribute *tz*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001235 adjusting the date and time data so the result is the same UTC time as
Senthil Kumarana6bac952011-07-04 11:28:30 -07001236 *self*, but in *tz*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00001237
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001238 If provided, *tz* must be an instance of a :class:`tzinfo` subclass, and its
Brad3fb13632019-09-11 05:19:05 -04001239 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. If *self*
Alexander Belopolsky877b2322018-06-10 17:02:58 -04001240 is naive, it is presumed to represent time in the system timezone.
Georg Brandl116aa622007-08-15 14:28:22 +00001241
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001242 If called without arguments (or with ``tz=None``) the system local
Brad3fb13632019-09-11 05:19:05 -04001243 timezone is assumed for the target timezone. The ``.tzinfo`` attribute of the converted
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001244 datetime instance will be set to an instance of :class:`timezone`
1245 with the zone name and offset obtained from the OS.
1246
Georg Brandl116aa622007-08-15 14:28:22 +00001247 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001248 adjustment of date or time data is performed. Else the result is local
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001249 time in the timezone *tz*, representing the same UTC time as *self*: after
1250 ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will have
1251 the same date and time data as ``dt - dt.utcoffset()``.
Georg Brandl116aa622007-08-15 14:28:22 +00001252
1253 If you merely want to attach a time zone object *tz* to a datetime *dt* without
Brad3fb13632019-09-11 05:19:05 -04001254 adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you
Georg Brandl116aa622007-08-15 14:28:22 +00001255 merely want to remove the time zone object from an aware datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001256 conversion of date and time data, use ``dt.replace(tzinfo=None)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001257
1258 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
1259 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
1260 Ignoring error cases, :meth:`astimezone` acts like::
1261
1262 def astimezone(self, tz):
1263 if self.tzinfo is tz:
1264 return self
1265 # Convert self to UTC, and attach the new time zone object.
1266 utc = (self - self.utcoffset()).replace(tzinfo=tz)
1267 # Convert from UTC to tz's local time.
1268 return tz.fromutc(utc)
1269
Georg Brandlee0be402012-06-26 09:14:40 +02001270 .. versionchanged:: 3.3
1271 *tz* now can be omitted.
1272
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001273 .. versionchanged:: 3.6
1274 The :meth:`astimezone` method can now be called on naive instances that
1275 are presumed to represent system local time.
1276
Georg Brandl116aa622007-08-15 14:28:22 +00001277
1278.. method:: datetime.utcoffset()
1279
Martin Panter16c7cfd2016-04-01 21:48:24 +00001280 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001281 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001282 return ``None`` or a :class:`timedelta` object with magnitude less than one day.
1283
1284 .. versionchanged:: 3.7
1285 The UTC offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001286
1287
1288.. method:: datetime.dst()
1289
Martin Panter16c7cfd2016-04-01 21:48:24 +00001290 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001291 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001292 ``None`` or a :class:`timedelta` object with magnitude less than one day.
1293
1294 .. versionchanged:: 3.7
1295 The DST offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001296
1297
1298.. method:: datetime.tzname()
1299
Martin Panter16c7cfd2016-04-01 21:48:24 +00001300 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001301 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
1302 ``None`` or a string object,
1303
1304
1305.. method:: datetime.timetuple()
1306
1307 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
Brad3fb13632019-09-11 05:19:05 -04001308
1309 ``d.timetuple()`` is equivalent to::
1310
1311 time.struct_time((d.year, d.month, d.day,
1312 d.hour, d.minute, d.second,
1313 d.weekday(), yday, dst))
1314
1315 where ``yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1``
1316 is the day number within the current year starting with ``1`` for January
1317 1st. The :attr:`tm_isdst` flag of the result is set according to the
1318 :meth:`dst` method: :attr:`.tzinfo` is ``None`` or :meth:`dst` returns
1319 ``None``, :attr:`tm_isdst` is set to ``-1``; else if :meth:`dst` returns a
1320 non-zero value, :attr:`tm_isdst` is set to ``1``; else :attr:`tm_isdst` is
1321 set to ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +00001322
1323
1324.. method:: datetime.utctimetuple()
1325
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001326 If :class:`.datetime` instance *d* is naive, this is the same as
Georg Brandl116aa622007-08-15 14:28:22 +00001327 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
Brad3fb13632019-09-11 05:19:05 -04001328 ``d.dst()`` returns. DST is never in effect for a UTC time.
Georg Brandl116aa622007-08-15 14:28:22 +00001329
1330 If *d* is aware, *d* is normalized to UTC time, by subtracting
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00001331 ``d.utcoffset()``, and a :class:`time.struct_time` for the
Brad3fb13632019-09-11 05:19:05 -04001332 normalized time is returned. :attr:`tm_isdst` is forced to 0. Note
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00001333 that an :exc:`OverflowError` may be raised if *d*.year was
1334 ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
Georg Brandl116aa622007-08-15 14:28:22 +00001335 boundary.
1336
Joannah Nanjekye1a53c782019-09-11 14:58:42 +01001337 .. warning::
1338
1339 Because naive ``datetime`` objects are treated by many ``datetime`` methods
1340 as local times, it is preferred to use aware datetimes to represent times
1341 in UTC; as a result, using ``utcfromtimetuple`` may give misleading
1342 results. If you have a naive ``datetime`` representing UTC, use
1343 ``datetime.replace(tzinfo=timezone.utc)`` to make it aware, at which point
1344 you can use :meth:`.datetime.timetuple`.
Georg Brandl116aa622007-08-15 14:28:22 +00001345
1346.. method:: datetime.toordinal()
1347
Brad3fb13632019-09-11 05:19:05 -04001348 Return the proleptic Gregorian ordinal of the date. The same as
Georg Brandl116aa622007-08-15 14:28:22 +00001349 ``self.date().toordinal()``.
1350
Alexander Belopolskya4415142012-06-08 12:33:09 -04001351.. method:: datetime.timestamp()
1352
Martin Panter16c7cfd2016-04-01 21:48:24 +00001353 Return POSIX timestamp corresponding to the :class:`.datetime`
Brad3fb13632019-09-11 05:19:05 -04001354 instance. The return value is a :class:`float` similar to that
Alexander Belopolskya4415142012-06-08 12:33:09 -04001355 returned by :func:`time.time`.
1356
Martin Panter16c7cfd2016-04-01 21:48:24 +00001357 Naive :class:`.datetime` instances are assumed to represent local
Alexander Belopolskya4415142012-06-08 12:33:09 -04001358 time and this method relies on the platform C :c:func:`mktime`
Brad3fb13632019-09-11 05:19:05 -04001359 function to perform the conversion. Since :class:`.datetime`
Alexander Belopolskya4415142012-06-08 12:33:09 -04001360 supports wider range of values than :c:func:`mktime` on many
1361 platforms, this method may raise :exc:`OverflowError` for times far
1362 in the past or far in the future.
1363
Martin Panter16c7cfd2016-04-01 21:48:24 +00001364 For aware :class:`.datetime` instances, the return value is computed
Alexander Belopolskya4415142012-06-08 12:33:09 -04001365 as::
1366
1367 (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
1368
1369 .. versionadded:: 3.3
1370
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001371 .. versionchanged:: 3.6
1372 The :meth:`timestamp` method uses the :attr:`.fold` attribute to
1373 disambiguate the times during a repeated interval.
1374
Alexander Belopolskya4415142012-06-08 12:33:09 -04001375 .. note::
1376
1377 There is no method to obtain the POSIX timestamp directly from a
Brad3fb13632019-09-11 05:19:05 -04001378 naive :class:`.datetime` instance representing UTC time. If your
Alexander Belopolskya4415142012-06-08 12:33:09 -04001379 application uses this convention and your system timezone is not
1380 set to UTC, you can obtain the POSIX timestamp by supplying
1381 ``tzinfo=timezone.utc``::
1382
1383 timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
1384
1385 or by calculating the timestamp directly::
1386
1387 timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001388
1389.. method:: datetime.weekday()
1390
1391 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
1392 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
1393
1394
1395.. method:: datetime.isoweekday()
1396
1397 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
1398 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
1399 :meth:`isocalendar`.
1400
1401
1402.. method:: datetime.isocalendar()
1403
Paul Ganssle1b97b9b2020-05-16 10:02:59 -04001404 Return a :term:`named tuple` with three components: ``year``, ``week``
1405 and ``weekday``. The same as ``self.date().isocalendar()``.
Georg Brandl116aa622007-08-15 14:28:22 +00001406
1407
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001408.. method:: datetime.isoformat(sep='T', timespec='auto')
Georg Brandl116aa622007-08-15 14:28:22 +00001409
Brad3fb13632019-09-11 05:19:05 -04001410 Return a string representing the date and time in ISO 8601 format:
1411
1412 - ``YYYY-MM-DDTHH:MM:SS.ffffff``, if :attr:`microsecond` is not 0
1413 - ``YYYY-MM-DDTHH:MM:SS``, if :attr:`microsecond` is 0
Georg Brandl116aa622007-08-15 14:28:22 +00001414
Christophe Nanteuil92878822018-10-06 00:57:02 +02001415 If :meth:`utcoffset` does not return ``None``, a string is
1416 appended, giving the UTC offset:
Brad3fb13632019-09-11 05:19:05 -04001417
1418 - ``YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]``, if :attr:`microsecond`
1419 is not 0
1420 - ``YYYY-MM-DDTHH:MM:SS+HH:MM[:SS[.ffffff]]``, if :attr:`microsecond` is 0
1421
1422 Examples::
1423
1424 >>> from datetime import datetime, timezone
1425 >>> datetime(2019, 5, 18, 15, 17, 8, 132263).isoformat()
1426 '2019-05-18T15:17:08.132263'
1427 >>> datetime(2019, 5, 18, 15, 17, tzinfo=timezone.utc).isoformat()
1428 '2019-05-18T15:17:00+00:00'
Georg Brandl116aa622007-08-15 14:28:22 +00001429
1430 The optional argument *sep* (default ``'T'``) is a one-character separator,
Brad3fb13632019-09-11 05:19:05 -04001431 placed between the date and time portions of the result. For example::
Georg Brandl116aa622007-08-15 14:28:22 +00001432
1433 >>> from datetime import tzinfo, timedelta, datetime
1434 >>> class TZ(tzinfo):
Brad3fb13632019-09-11 05:19:05 -04001435 ... """A time zone with an arbitrary, constant -06:39 offset."""
1436 ... def utcoffset(self, dt):
1437 ... return timedelta(hours=-6, minutes=-39)
Georg Brandl116aa622007-08-15 14:28:22 +00001438 ...
1439 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1440 '2002-12-25 00:00:00-06:39'
Brad3fb13632019-09-11 05:19:05 -04001441 >>> datetime(2009, 11, 27, microsecond=100, tzinfo=TZ()).isoformat()
1442 '2009-11-27T00:00:00.000100-06:39'
Georg Brandl116aa622007-08-15 14:28:22 +00001443
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001444 The optional argument *timespec* specifies the number of additional
1445 components of the time to include (the default is ``'auto'``).
1446 It can be one of the following:
1447
1448 - ``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0,
1449 same as ``'microseconds'`` otherwise.
Brad3fb13632019-09-11 05:19:05 -04001450 - ``'hours'``: Include the :attr:`hour` in the two-digit ``HH`` format.
1451 - ``'minutes'``: Include :attr:`hour` and :attr:`minute` in ``HH:MM`` format.
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001452 - ``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second`
Brad3fb13632019-09-11 05:19:05 -04001453 in ``HH:MM:SS`` format.
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001454 - ``'milliseconds'``: Include full time, but truncate fractional second
Brad3fb13632019-09-11 05:19:05 -04001455 part to milliseconds. ``HH:MM:SS.sss`` format.
1456 - ``'microseconds'``: Include full time in ``HH:MM:SS.ffffff`` format.
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001457
1458 .. note::
1459
1460 Excluded time components are truncated, not rounded.
1461
Brad3fb13632019-09-11 05:19:05 -04001462 :exc:`ValueError` will be raised on an invalid *timespec* argument::
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001463
1464
1465 >>> from datetime import datetime
Marco Buttu909a6f62017-03-18 17:59:33 +01001466 >>> datetime.now().isoformat(timespec='minutes') # doctest: +SKIP
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001467 '2002-12-25T00:00'
1468 >>> dt = datetime(2015, 1, 1, 12, 30, 59, 0)
1469 >>> dt.isoformat(timespec='microseconds')
1470 '2015-01-01T12:30:59.000000'
1471
1472 .. versionadded:: 3.6
1473 Added the *timespec* argument.
1474
Georg Brandl116aa622007-08-15 14:28:22 +00001475
1476.. method:: datetime.__str__()
1477
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001478 For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to
Georg Brandl116aa622007-08-15 14:28:22 +00001479 ``d.isoformat(' ')``.
1480
1481
1482.. method:: datetime.ctime()
1483
Brad3fb13632019-09-11 05:19:05 -04001484 Return a string representing the date and time::
Georg Brandl116aa622007-08-15 14:28:22 +00001485
Brad3fb13632019-09-11 05:19:05 -04001486 >>> from datetime import datetime
1487 >>> datetime(2002, 12, 4, 20, 30, 40).ctime()
1488 'Wed Dec 4 20:30:40 2002'
1489
1490 The output string will *not* include time zone information, regardless
1491 of whether the input is aware or naive.
1492
1493 ``d.ctime()`` is equivalent to::
1494
1495 time.ctime(time.mktime(d.timetuple()))
1496
1497 on platforms where the native C :c:func:`ctime` function
1498 (which :func:`time.ctime` invokes, but which
1499 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
Georg Brandl116aa622007-08-15 14:28:22 +00001500
1501.. method:: datetime.strftime(format)
1502
1503 Return a string representing the date and time, controlled by an explicit format
Brad3fb13632019-09-11 05:19:05 -04001504 string. For a complete list of formatting directives, see
David Wolever569a5fa2013-08-12 16:56:02 -04001505 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001506
Georg Brandl116aa622007-08-15 14:28:22 +00001507
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001508.. method:: datetime.__format__(format)
1509
Brad3fb13632019-09-11 05:19:05 -04001510 Same as :meth:`.datetime.strftime`. This makes it possible to specify a format
Martin Panterbc1ee462016-02-13 00:41:37 +00001511 string for a :class:`.datetime` object in :ref:`formatted string
Brad3fb13632019-09-11 05:19:05 -04001512 literals <f-strings>` and when using :meth:`str.format`. For a
David Wolever569a5fa2013-08-12 16:56:02 -04001513 complete list of formatting directives, see
1514 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001515
Brad3fb13632019-09-11 05:19:05 -04001516Examples of Usage: :class:`.datetime`
1517^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001518
Brad3fb13632019-09-11 05:19:05 -04001519Examples of working with :class:`~datetime.datetime` objects:
Christian Heimesfe337bf2008-03-23 21:54:12 +00001520
1521.. doctest::
1522
Joannah Nanjekye1a53c782019-09-11 14:58:42 +01001523 >>> from datetime import datetime, date, time, timezone
Brad3fb13632019-09-11 05:19:05 -04001524
Christian Heimes895627f2007-12-08 17:28:33 +00001525 >>> # Using datetime.combine()
1526 >>> d = date(2005, 7, 14)
1527 >>> t = time(12, 30)
1528 >>> datetime.combine(d, t)
1529 datetime.datetime(2005, 7, 14, 12, 30)
Brad3fb13632019-09-11 05:19:05 -04001530
Joannah Nanjekye1a53c782019-09-11 14:58:42 +01001531 >>> # Using datetime.now()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001532 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001533 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Joannah Nanjekye1a53c782019-09-11 14:58:42 +01001534 >>> datetime.now(timezone.utc) # doctest: +SKIP
1535 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060, tzinfo=datetime.timezone.utc)
Brad3fb13632019-09-11 05:19:05 -04001536
Christian Heimes895627f2007-12-08 17:28:33 +00001537 >>> # Using datetime.strptime()
1538 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1539 >>> dt
1540 datetime.datetime(2006, 11, 21, 16, 30)
Brad3fb13632019-09-11 05:19:05 -04001541
Christian Heimes895627f2007-12-08 17:28:33 +00001542 >>> # Using datetime.timetuple() to get tuple of all attributes
1543 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001544 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001545 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001546 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001547 2006 # year
1548 11 # month
1549 21 # day
1550 16 # hour
1551 30 # minute
1552 0 # second
1553 1 # weekday (0 = Monday)
1554 325 # number of days since 1st January
1555 -1 # dst - method tzinfo.dst() returned None
Brad3fb13632019-09-11 05:19:05 -04001556
Christian Heimes895627f2007-12-08 17:28:33 +00001557 >>> # Date in ISO format
1558 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001559 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001560 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001561 ...
1562 2006 # ISO year
1563 47 # ISO week
1564 2 # ISO weekday
Brad3fb13632019-09-11 05:19:05 -04001565
1566 >>> # Formatting a datetime
Christian Heimes895627f2007-12-08 17:28:33 +00001567 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1568 'Tuesday, 21. November 2006 04:30PM'
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001569 >>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
1570 'The day is 21, the month is November, the time is 04:30PM.'
Christian Heimes895627f2007-12-08 17:28:33 +00001571
Brad3fb13632019-09-11 05:19:05 -04001572The example below defines a :class:`tzinfo` subclass capturing time zone
1573information for Kabul, Afghanistan, which used +4 UTC until 1945
1574and then +4:30 UTC thereafter::
Christian Heimes895627f2007-12-08 17:28:33 +00001575
Brad3fb13632019-09-11 05:19:05 -04001576 from datetime import timedelta, datetime, tzinfo, timezone
Georg Brandl48310cd2009-01-03 21:18:54 +00001577
Brad3fb13632019-09-11 05:19:05 -04001578 class KabulTz(tzinfo):
1579 # Kabul used +4 until 1945, when they moved to +4:30
1580 UTC_MOVE_DATE = datetime(1944, 12, 31, 20, tzinfo=timezone.utc)
Christian Heimes895627f2007-12-08 17:28:33 +00001581
Brad3fb13632019-09-11 05:19:05 -04001582 def utcoffset(self, dt):
1583 if dt.year < 1945:
1584 return timedelta(hours=4)
1585 elif (1945, 1, 1, 0, 0) <= dt.timetuple()[:5] < (1945, 1, 1, 0, 30):
1586 # An ambiguous ("imaginary") half-hour range representing
1587 # a 'fold' in time due to the shift from +4 to +4:30.
1588 # If dt falls in the imaginary range, use fold to decide how
1589 # to resolve. See PEP495.
1590 return timedelta(hours=4, minutes=(30 if dt.fold else 0))
1591 else:
1592 return timedelta(hours=4, minutes=30)
1593
1594 def fromutc(self, dt):
1595 # Follow same validations as in datetime.tzinfo
1596 if not isinstance(dt, datetime):
1597 raise TypeError("fromutc() requires a datetime argument")
1598 if dt.tzinfo is not self:
1599 raise ValueError("dt.tzinfo is not self")
1600
1601 # A custom implementation is required for fromutc as
1602 # the input to this function is a datetime with utc values
1603 # but with a tzinfo set to self.
1604 # See datetime.astimezone or fromtimestamp.
1605 if dt.replace(tzinfo=timezone.utc) >= self.UTC_MOVE_DATE:
1606 return dt + timedelta(hours=4, minutes=30)
1607 else:
1608 return dt + timedelta(hours=4)
1609
1610 def dst(self, dt):
1611 # Kabul does not observe daylight saving time.
1612 return timedelta(0)
1613
1614 def tzname(self, dt):
1615 if dt >= self.UTC_MOVE_DATE:
1616 return "+04:30"
1617 return "+04"
1618
1619Usage of ``KabulTz`` from above::
1620
1621 >>> tz1 = KabulTz()
1622
1623 >>> # Datetime before the change
1624 >>> dt1 = datetime(1900, 11, 21, 16, 30, tzinfo=tz1)
1625 >>> print(dt1.utcoffset())
1626 4:00:00
1627
1628 >>> # Datetime after the change
1629 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=tz1)
1630 >>> print(dt2.utcoffset())
1631 4:30:00
1632
1633 >>> # Convert datetime to another time zone
1634 >>> dt3 = dt2.astimezone(timezone.utc)
1635 >>> dt3
1636 datetime.datetime(2006, 6, 14, 8, 30, tzinfo=datetime.timezone.utc)
1637 >>> dt2
1638 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=KabulTz())
Joannah Nanjekye1a53c782019-09-11 14:58:42 +01001639 >>> dt2 == dt3
Brad3fb13632019-09-11 05:19:05 -04001640 True
Georg Brandl116aa622007-08-15 14:28:22 +00001641
1642.. _datetime-time:
1643
Serhiy Storchakaee1b01a2016-12-02 23:13:53 +02001644:class:`.time` Objects
1645----------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001646
Brad3fb13632019-09-11 05:19:05 -04001647A :class:`time` object represents a (local) time of day, independent of any particular
Georg Brandl116aa622007-08-15 14:28:22 +00001648day, and subject to adjustment via a :class:`tzinfo` object.
1649
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001650.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001651
Brad3fb13632019-09-11 05:19:05 -04001652 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
1653 :class:`tzinfo` subclass. The remaining arguments must be integers in the
Georg Brandl116aa622007-08-15 14:28:22 +00001654 following ranges:
1655
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001656 * ``0 <= hour < 24``,
1657 * ``0 <= minute < 60``,
1658 * ``0 <= second < 60``,
1659 * ``0 <= microsecond < 1000000``,
1660 * ``fold in [0, 1]``.
Georg Brandl116aa622007-08-15 14:28:22 +00001661
Brad3fb13632019-09-11 05:19:05 -04001662 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
Georg Brandl116aa622007-08-15 14:28:22 +00001663 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1664
1665Class attributes:
1666
1667
1668.. attribute:: time.min
1669
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001670 The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001671
1672
1673.. attribute:: time.max
1674
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001675 The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001676
1677
1678.. attribute:: time.resolution
1679
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001680 The smallest possible difference between non-equal :class:`.time` objects,
1681 ``timedelta(microseconds=1)``, although note that arithmetic on
1682 :class:`.time` objects is not supported.
Georg Brandl116aa622007-08-15 14:28:22 +00001683
Georg Brandl116aa622007-08-15 14:28:22 +00001684
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001685Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001686
1687.. attribute:: time.hour
1688
1689 In ``range(24)``.
1690
1691
1692.. attribute:: time.minute
1693
1694 In ``range(60)``.
1695
1696
1697.. attribute:: time.second
1698
1699 In ``range(60)``.
1700
1701
1702.. attribute:: time.microsecond
1703
1704 In ``range(1000000)``.
1705
1706
1707.. attribute:: time.tzinfo
1708
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001709 The object passed as the tzinfo argument to the :class:`.time` constructor, or
Georg Brandl116aa622007-08-15 14:28:22 +00001710 ``None`` if none was passed.
1711
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001712
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001713.. attribute:: time.fold
1714
Brad3fb13632019-09-11 05:19:05 -04001715 In ``[0, 1]``. Used to disambiguate wall times during a repeated interval. (A
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001716 repeated interval occurs when clocks are rolled back at the end of daylight saving
1717 time or when the UTC offset for the current zone is decreased for political reasons.)
1718 The value 0 (1) represents the earlier (later) of the two moments with the same wall
1719 time representation.
1720
1721 .. versionadded:: 3.6
1722
Brad3fb13632019-09-11 05:19:05 -04001723:class:`.time` objects support comparison of :class:`.time` to :class:`.time`,
1724where *a* is considered less
1725than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1726is aware, :exc:`TypeError` is raised if an order comparison is attempted. For equality
1727comparisons, naive instances are never equal to aware instances.
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001728
Brad3fb13632019-09-11 05:19:05 -04001729If both comparands are aware, and have
1730the same :attr:`~time.tzinfo` attribute, the common :attr:`~time.tzinfo` attribute is
1731ignored and the base times are compared. If both comparands are aware and
1732have different :attr:`~time.tzinfo` attributes, the comparands are first adjusted by
1733subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
1734to stop mixed-type comparisons from falling back to the default comparison by
1735object address, when a :class:`.time` object is compared to an object of a
1736different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
1737``!=``. The latter cases return :const:`False` or :const:`True`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +00001738
Brad3fb13632019-09-11 05:19:05 -04001739.. versionchanged:: 3.3
1740 Equality comparisons between aware and naive :class:`~datetime.time` instances
1741 don't raise :exc:`TypeError`.
Alexander Belopolsky08313822012-06-15 20:19:47 -04001742
Brad3fb13632019-09-11 05:19:05 -04001743In Boolean contexts, a :class:`.time` object is always considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +00001744
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05001745.. versionchanged:: 3.5
1746 Before Python 3.5, a :class:`.time` object was considered to be false if it
Brad3fb13632019-09-11 05:19:05 -04001747 represented midnight in UTC. This behavior was considered obscure and
1748 error-prone and has been removed in Python 3.5. See :issue:`13936` for full
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05001749 details.
Georg Brandl116aa622007-08-15 14:28:22 +00001750
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001751
1752Other constructor:
1753
1754.. classmethod:: time.fromisoformat(time_string)
1755
Brad3fb13632019-09-11 05:19:05 -04001756 Return a :class:`.time` corresponding to a *time_string* in one of the
1757 formats emitted by :meth:`time.isoformat`. Specifically, this function supports
1758 strings in the format:
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001759
Brad3fb13632019-09-11 05:19:05 -04001760 .. code-block:: none
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001761
Brad3fb13632019-09-11 05:19:05 -04001762 HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001763
Brad3fb13632019-09-11 05:19:05 -04001764 .. caution::
1765
1766 This does *not* support parsing arbitrary ISO 8601 strings. It is only
1767 intended as the inverse operation of :meth:`time.isoformat`.
1768
1769 Examples::
1770
1771 >>> from datetime import time
1772 >>> time.fromisoformat('04:23:01')
1773 datetime.time(4, 23, 1)
1774 >>> time.fromisoformat('04:23:01.000384')
1775 datetime.time(4, 23, 1, 384)
1776 >>> time.fromisoformat('04:23:01+04:00')
1777 datetime.time(4, 23, 1, tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))
1778
1779 .. versionadded:: 3.7
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001780
1781
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001782Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001783
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001784.. method:: time.replace(hour=self.hour, minute=self.minute, second=self.second, \
1785 microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001786
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001787 Return a :class:`.time` with the same value, except for those attributes given
Brad3fb13632019-09-11 05:19:05 -04001788 new values by whichever keyword arguments are specified. Note that
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001789 ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
1790 aware :class:`.time`, without conversion of the time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001791
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001792 .. versionadded:: 3.6
1793 Added the ``fold`` argument.
1794
Georg Brandl116aa622007-08-15 14:28:22 +00001795
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001796.. method:: time.isoformat(timespec='auto')
Georg Brandl116aa622007-08-15 14:28:22 +00001797
Brad3fb13632019-09-11 05:19:05 -04001798 Return a string representing the time in ISO 8601 format, one of:
1799
1800 - ``HH:MM:SS.ffffff``, if :attr:`microsecond` is not 0
1801 - ``HH:MM:SS``, if :attr:`microsecond` is 0
1802 - ``HH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]``, if :meth:`utcoffset` does not return ``None``
1803 - ``HH:MM:SS+HH:MM[:SS[.ffffff]]``, if :attr:`microsecond` is 0 and :meth:`utcoffset` does not return ``None``
Georg Brandl116aa622007-08-15 14:28:22 +00001804
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001805 The optional argument *timespec* specifies the number of additional
1806 components of the time to include (the default is ``'auto'``).
1807 It can be one of the following:
1808
1809 - ``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0,
1810 same as ``'microseconds'`` otherwise.
Brad3fb13632019-09-11 05:19:05 -04001811 - ``'hours'``: Include the :attr:`hour` in the two-digit ``HH`` format.
1812 - ``'minutes'``: Include :attr:`hour` and :attr:`minute` in ``HH:MM`` format.
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001813 - ``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second`
Brad3fb13632019-09-11 05:19:05 -04001814 in ``HH:MM:SS`` format.
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001815 - ``'milliseconds'``: Include full time, but truncate fractional second
Brad3fb13632019-09-11 05:19:05 -04001816 part to milliseconds. ``HH:MM:SS.sss`` format.
1817 - ``'microseconds'``: Include full time in ``HH:MM:SS.ffffff`` format.
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001818
1819 .. note::
1820
1821 Excluded time components are truncated, not rounded.
1822
1823 :exc:`ValueError` will be raised on an invalid *timespec* argument.
1824
Brad3fb13632019-09-11 05:19:05 -04001825 Example::
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001826
1827 >>> from datetime import time
Berker Peksag94f89a62016-06-04 21:36:53 -07001828 >>> time(hour=12, minute=34, second=56, microsecond=123456).isoformat(timespec='minutes')
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001829 '12:34'
Berker Peksag94f89a62016-06-04 21:36:53 -07001830 >>> dt = time(hour=12, minute=34, second=56, microsecond=0)
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001831 >>> dt.isoformat(timespec='microseconds')
1832 '12:34:56.000000'
1833 >>> dt.isoformat(timespec='auto')
1834 '12:34:56'
1835
1836 .. versionadded:: 3.6
1837 Added the *timespec* argument.
1838
Georg Brandl116aa622007-08-15 14:28:22 +00001839
1840.. method:: time.__str__()
1841
1842 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1843
1844
1845.. method:: time.strftime(format)
1846
David Wolever569a5fa2013-08-12 16:56:02 -04001847 Return a string representing the time, controlled by an explicit format
Brad3fb13632019-09-11 05:19:05 -04001848 string. For a complete list of formatting directives, see
David Woleverbbf4a462013-08-12 17:15:36 -04001849 :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001850
1851
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001852.. method:: time.__format__(format)
1853
Martin Panterd5db1472016-02-08 01:34:09 +00001854 Same as :meth:`.time.strftime`. This makes it possible to specify a format string
Martin Panterbc1ee462016-02-13 00:41:37 +00001855 for a :class:`.time` object in :ref:`formatted string
Brad3fb13632019-09-11 05:19:05 -04001856 literals <f-strings>` and when using :meth:`str.format`. For a
David Wolever569a5fa2013-08-12 16:56:02 -04001857 complete list of formatting directives, see
1858 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001859
1860
Georg Brandl116aa622007-08-15 14:28:22 +00001861.. method:: time.utcoffset()
1862
Martin Panter16c7cfd2016-04-01 21:48:24 +00001863 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001864 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001865 return ``None`` or a :class:`timedelta` object with magnitude less than one day.
1866
1867 .. versionchanged:: 3.7
1868 The UTC offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001869
1870
1871.. method:: time.dst()
1872
Martin Panter16c7cfd2016-04-01 21:48:24 +00001873 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001874 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001875 ``None``, or a :class:`timedelta` object with magnitude less than one day.
Georg Brandl116aa622007-08-15 14:28:22 +00001876
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001877 .. versionchanged:: 3.7
1878 The DST offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001879
1880.. method:: time.tzname()
1881
Martin Panter16c7cfd2016-04-01 21:48:24 +00001882 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001883 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1884 return ``None`` or a string object.
1885
Brad3fb13632019-09-11 05:19:05 -04001886Examples of Usage: :class:`.time`
1887^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1888
1889Examples of working with a :class:`.time` object::
Georg Brandl48310cd2009-01-03 21:18:54 +00001890
Xiang Zhang6721c7c2016-12-27 12:23:59 +08001891 >>> from datetime import time, tzinfo, timedelta
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001892 >>> class TZ1(tzinfo):
Christian Heimes895627f2007-12-08 17:28:33 +00001893 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001894 ... return timedelta(hours=1)
1895 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001896 ... return timedelta(0)
1897 ... def tzname(self,dt):
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001898 ... return "+01:00"
1899 ... def __repr__(self):
1900 ... return f"{self.__class__.__name__}()"
Christian Heimes895627f2007-12-08 17:28:33 +00001901 ...
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001902 >>> t = time(12, 10, 30, tzinfo=TZ1())
1903 >>> t
1904 datetime.time(12, 10, 30, tzinfo=TZ1())
Christian Heimes895627f2007-12-08 17:28:33 +00001905 >>> t.isoformat()
1906 '12:10:30+01:00'
1907 >>> t.dst()
1908 datetime.timedelta(0)
1909 >>> t.tzname()
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001910 '+01:00'
Christian Heimes895627f2007-12-08 17:28:33 +00001911 >>> t.strftime("%H:%M:%S %Z")
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001912 '12:10:30 +01:00'
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001913 >>> 'The {} is {:%H:%M}.'.format("time", t)
1914 'The time is 12:10.'
Christian Heimes895627f2007-12-08 17:28:33 +00001915
Georg Brandl116aa622007-08-15 14:28:22 +00001916
1917.. _datetime-tzinfo:
1918
1919:class:`tzinfo` Objects
1920-----------------------
1921
Martin Panter16c7cfd2016-04-01 21:48:24 +00001922.. class:: tzinfo()
Georg Brandl116aa622007-08-15 14:28:22 +00001923
Martin Panter16c7cfd2016-04-01 21:48:24 +00001924 This is an abstract base class, meaning that this class should not be
Brad3fb13632019-09-11 05:19:05 -04001925 instantiated directly. Define a subclass of :class:`tzinfo` to capture
1926 information about a particular time zone.
Georg Brandl116aa622007-08-15 14:28:22 +00001927
Martin Panter16c7cfd2016-04-01 21:48:24 +00001928 An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1929 constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
1930 view their attributes as being in local time, and the :class:`tzinfo` object
1931 supports methods revealing offset of local time from UTC, the name of the time
1932 zone, and DST offset, all relative to a date or time object passed to them.
Georg Brandl116aa622007-08-15 14:28:22 +00001933
Brad3fb13632019-09-11 05:19:05 -04001934 You need to derive a concrete subclass, and (at least)
1935 supply implementations of the standard :class:`tzinfo` methods needed by the
1936 :class:`.datetime` methods you use. The :mod:`datetime` module provides
1937 :class:`timezone`, a simple concrete subclass of :class:`tzinfo` which can
1938 represent timezones with fixed offset from UTC such as UTC itself or North
1939 American EST and EDT.
1940
Martin Panter16c7cfd2016-04-01 21:48:24 +00001941 Special requirement for pickling: A :class:`tzinfo` subclass must have an
Brad3fb13632019-09-11 05:19:05 -04001942 :meth:`__init__` method that can be called with no arguments, otherwise it can be
1943 pickled but possibly not unpickled again. This is a technical requirement that
Martin Panter16c7cfd2016-04-01 21:48:24 +00001944 may be relaxed in the future.
1945
1946 A concrete subclass of :class:`tzinfo` may need to implement the following
Brad3fb13632019-09-11 05:19:05 -04001947 methods. Exactly which methods are needed depends on the uses made of aware
1948 :mod:`datetime` objects. If in doubt, simply implement all of them.
Georg Brandl116aa622007-08-15 14:28:22 +00001949
1950
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001951.. method:: tzinfo.utcoffset(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001952
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001953 Return offset of local time from UTC, as a :class:`timedelta` object that is
Brad3fb13632019-09-11 05:19:05 -04001954 positive east of UTC. If local time is west of UTC, this should be negative.
1955
1956 This represents the *total* offset from UTC; for example, if a
1957 :class:`tzinfo` object represents both time zone and DST adjustments,
1958 :meth:`utcoffset` should return their sum. If the UTC offset isn't known,
1959 return ``None``. Else the value returned must be a :class:`timedelta` object
1960 strictly between ``-timedelta(hours=24)`` and ``timedelta(hours=24)``
1961 (the magnitude of the offset must be less than one day). Most implementations
1962 of :meth:`utcoffset` will probably look like one of these two::
Georg Brandl116aa622007-08-15 14:28:22 +00001963
1964 return CONSTANT # fixed-offset class
1965 return CONSTANT + self.dst(dt) # daylight-aware class
1966
1967 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1968 ``None`` either.
1969
1970 The default implementation of :meth:`utcoffset` raises
1971 :exc:`NotImplementedError`.
1972
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001973 .. versionchanged:: 3.7
1974 The UTC offset is not restricted to a whole number of minutes.
1975
Georg Brandl116aa622007-08-15 14:28:22 +00001976
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001977.. method:: tzinfo.dst(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001978
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001979 Return the daylight saving time (DST) adjustment, as a :class:`timedelta`
1980 object or
Brad3fb13632019-09-11 05:19:05 -04001981 ``None`` if DST information isn't known.
1982
1983 Return ``timedelta(0)`` if DST is not in effect.
1984 If DST is in effect, return the offset as a :class:`timedelta` object
Georg Brandl116aa622007-08-15 14:28:22 +00001985 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1986 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1987 no need to consult :meth:`dst` unless you're interested in obtaining DST info
Brad3fb13632019-09-11 05:19:05 -04001988 separately. For example, :meth:`datetime.timetuple` calls its :attr:`~.datetime.tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -07001989 attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
1990 should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
1991 DST changes when crossing time zones.
Georg Brandl116aa622007-08-15 14:28:22 +00001992
1993 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1994 daylight times must be consistent in this sense:
1995
1996 ``tz.utcoffset(dt) - tz.dst(dt)``
1997
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001998 must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo ==
Georg Brandl116aa622007-08-15 14:28:22 +00001999 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
2000 zone's "standard offset", which should not depend on the date or the time, but
Brad3fb13632019-09-11 05:19:05 -04002001 only on geographic location. The implementation of :meth:`datetime.astimezone`
Georg Brandl116aa622007-08-15 14:28:22 +00002002 relies on this, but cannot detect violations; it's the programmer's
Brad3fb13632019-09-11 05:19:05 -04002003 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
Georg Brandl116aa622007-08-15 14:28:22 +00002004 this, it may be able to override the default implementation of
2005 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
2006
2007 Most implementations of :meth:`dst` will probably look like one of these two::
2008
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01002009 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00002010 # a fixed-offset class: doesn't account for DST
2011 return timedelta(0)
2012
Brad3fb13632019-09-11 05:19:05 -04002013 or::
Georg Brandl116aa622007-08-15 14:28:22 +00002014
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01002015 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00002016 # Code to set dston and dstoff to the time zone's DST
2017 # transition times based on the input dt.year, and expressed
Brad3fb13632019-09-11 05:19:05 -04002018 # in standard local time.
Georg Brandl116aa622007-08-15 14:28:22 +00002019
2020 if dston <= dt.replace(tzinfo=None) < dstoff:
2021 return timedelta(hours=1)
2022 else:
2023 return timedelta(0)
2024
2025 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
2026
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002027 .. versionchanged:: 3.7
2028 The DST offset is not restricted to a whole number of minutes.
2029
Georg Brandl116aa622007-08-15 14:28:22 +00002030
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002031.. method:: tzinfo.tzname(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00002032
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002033 Return the time zone name corresponding to the :class:`.datetime` object *dt*, as
Georg Brandl116aa622007-08-15 14:28:22 +00002034 a string. Nothing about string names is defined by the :mod:`datetime` module,
Brad3fb13632019-09-11 05:19:05 -04002035 and there's no requirement that it mean anything in particular. For example,
Georg Brandl116aa622007-08-15 14:28:22 +00002036 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
Brad3fb13632019-09-11 05:19:05 -04002037 valid replies. Return ``None`` if a string name isn't known. Note that this is
Georg Brandl116aa622007-08-15 14:28:22 +00002038 a method rather than a fixed string primarily because some :class:`tzinfo`
2039 subclasses will wish to return different names depending on the specific value
2040 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
2041 daylight time.
2042
2043 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
2044
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002045
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002046These methods are called by a :class:`.datetime` or :class:`.time` object, in
Brad3fb13632019-09-11 05:19:05 -04002047response to their methods of the same names. A :class:`.datetime` object passes
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002048itself as the argument, and a :class:`.time` object passes ``None`` as the
Brad3fb13632019-09-11 05:19:05 -04002049argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002050accept a *dt* argument of ``None``, or of class :class:`.datetime`.
Georg Brandl116aa622007-08-15 14:28:22 +00002051
2052When ``None`` is passed, it's up to the class designer to decide the best
Brad3fb13632019-09-11 05:19:05 -04002053response. For example, returning ``None`` is appropriate if the class wishes to
2054say that time objects don't participate in the :class:`tzinfo` protocols. It
Georg Brandl116aa622007-08-15 14:28:22 +00002055may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
2056there is no other convention for discovering the standard offset.
2057
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002058When a :class:`.datetime` object is passed in response to a :class:`.datetime`
Brad3fb13632019-09-11 05:19:05 -04002059method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
2060rely on this, unless user code calls :class:`tzinfo` methods directly. The
Georg Brandl116aa622007-08-15 14:28:22 +00002061intent is that the :class:`tzinfo` methods interpret *dt* as being in local
2062time, and not need worry about objects in other timezones.
2063
2064There is one more :class:`tzinfo` method that a subclass may wish to override:
2065
2066
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002067.. method:: tzinfo.fromutc(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00002068
Senthil Kumaran023c6f72011-07-17 19:01:14 +08002069 This is called from the default :class:`datetime.astimezone()`
Brad3fb13632019-09-11 05:19:05 -04002070 implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s
2071 date and time data are to be viewed as expressing a UTC time. The purpose
Senthil Kumaran023c6f72011-07-17 19:01:14 +08002072 of :meth:`fromutc` is to adjust the date and time data, returning an
Senthil Kumarana6bac952011-07-04 11:28:30 -07002073 equivalent datetime in *self*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00002074
2075 Most :class:`tzinfo` subclasses should be able to inherit the default
Brad3fb13632019-09-11 05:19:05 -04002076 :meth:`fromutc` implementation without problems. It's strong enough to handle
Georg Brandl116aa622007-08-15 14:28:22 +00002077 fixed-offset time zones, and time zones accounting for both standard and
2078 daylight time, and the latter even if the DST transition times differ in
Brad3fb13632019-09-11 05:19:05 -04002079 different years. An example of a time zone the default :meth:`fromutc`
Georg Brandl116aa622007-08-15 14:28:22 +00002080 implementation may not handle correctly in all cases is one where the standard
2081 offset (from UTC) depends on the specific date and time passed, which can happen
2082 for political reasons. The default implementations of :meth:`astimezone` and
2083 :meth:`fromutc` may not produce the result you want if the result is one of the
2084 hours straddling the moment the standard offset changes.
2085
2086 Skipping code for error cases, the default :meth:`fromutc` implementation acts
2087 like::
2088
2089 def fromutc(self, dt):
2090 # raise ValueError error if dt.tzinfo is not self
2091 dtoff = dt.utcoffset()
2092 dtdst = dt.dst()
2093 # raise ValueError if dtoff is None or dtdst is None
2094 delta = dtoff - dtdst # this is self's standard offset
2095 if delta:
2096 dt += delta # convert to standard local time
2097 dtdst = dt.dst()
2098 # raise ValueError if dtdst is None
2099 if dtdst:
2100 return dt + dtdst
2101 else:
2102 return dt
2103
Marco Buttu909a6f62017-03-18 17:59:33 +01002104In the following :download:`tzinfo_examples.py
2105<../includes/tzinfo_examples.py>` file there are some examples of
2106:class:`tzinfo` classes:
Georg Brandl116aa622007-08-15 14:28:22 +00002107
Marco Buttu909a6f62017-03-18 17:59:33 +01002108.. literalinclude:: ../includes/tzinfo_examples.py
Georg Brandl116aa622007-08-15 14:28:22 +00002109
Georg Brandl116aa622007-08-15 14:28:22 +00002110Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
2111subclass accounting for both standard and daylight time, at the DST transition
Brad3fb13632019-09-11 05:19:05 -04002112points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00002113minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
21141:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00002115
2116 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
2117 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
2118 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
2119
2120 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
2121
2122 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
2123
2124When DST starts (the "start" line), the local wall clock leaps from 1:59 to
Brad3fb13632019-09-11 05:19:05 -040021253:00. A wall time of the form 2:MM doesn't really make sense on that day, so
Georg Brandl116aa622007-08-15 14:28:22 +00002126``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
Brad3fb13632019-09-11 05:19:05 -04002127begins. For example, at the Spring forward transition of 2016, we get::
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04002128
Marco Buttu909a6f62017-03-18 17:59:33 +01002129 >>> from datetime import datetime, timezone
2130 >>> from tzinfo_examples import HOUR, Eastern
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04002131 >>> u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc)
2132 >>> for i in range(4):
2133 ... u = u0 + i*HOUR
2134 ... t = u.astimezone(Eastern)
2135 ... print(u.time(), 'UTC =', t.time(), t.tzname())
2136 ...
2137 05:00:00 UTC = 00:00:00 EST
2138 06:00:00 UTC = 01:00:00 EST
2139 07:00:00 UTC = 03:00:00 EDT
2140 08:00:00 UTC = 04:00:00 EDT
2141
Georg Brandl116aa622007-08-15 14:28:22 +00002142
2143When DST ends (the "end" line), there's a potentially worse problem: there's an
2144hour that can't be spelled unambiguously in local wall time: the last hour of
Brad3fb13632019-09-11 05:19:05 -04002145daylight time. In Eastern, that's times of the form 5:MM UTC on the day
2146daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
Georg Brandl116aa622007-08-15 14:28:22 +00002147to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
2148:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
Brad3fb13632019-09-11 05:19:05 -04002149hours into the same local hour then. In the Eastern example, UTC times of the
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04002150form 5:MM and 6:MM both map to 1:MM when converted to Eastern, but earlier times
2151have the :attr:`~datetime.fold` attribute set to 0 and the later times have it set to 1.
Brad3fb13632019-09-11 05:19:05 -04002152For example, at the Fall back transition of 2016, we get::
Georg Brandl116aa622007-08-15 14:28:22 +00002153
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04002154 >>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
2155 >>> for i in range(4):
2156 ... u = u0 + i*HOUR
2157 ... t = u.astimezone(Eastern)
2158 ... print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
2159 ...
2160 04:00:00 UTC = 00:00:00 EDT 0
2161 05:00:00 UTC = 01:00:00 EDT 0
2162 06:00:00 UTC = 01:00:00 EST 1
2163 07:00:00 UTC = 02:00:00 EST 0
2164
Brad3fb13632019-09-11 05:19:05 -04002165Note that the :class:`.datetime` instances that differ only by the value of the
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04002166:attr:`~datetime.fold` attribute are considered equal in comparisons.
2167
2168Applications that can't bear wall-time ambiguities should explicitly check the
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07002169value of the :attr:`~datetime.fold` attribute or avoid using hybrid
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002170:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`,
2171or any other fixed-offset :class:`tzinfo` subclass (such as a class representing
2172only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
2173
Sandro Tosid11d0d62012-04-24 19:46:06 +02002174.. seealso::
2175
wim glenn53f2af12017-06-06 12:54:41 -05002176 `dateutil.tz <https://dateutil.readthedocs.io/en/stable/tz.html>`_
Brad3fb13632019-09-11 05:19:05 -04002177 The :mod:`datetime` module has a basic :class:`timezone` class (for
2178 handling arbitrary fixed offsets from UTC) and its :attr:`timezone.utc`
2179 attribute (a UTC timezone instance).
Sandro Tosid11d0d62012-04-24 19:46:06 +02002180
Brad3fb13632019-09-11 05:19:05 -04002181 *dateutil.tz* library brings the *IANA timezone database*
2182 (also known as the Olson database) to Python, and its usage is
2183 recommended.
Sandro Tosi100b8892012-04-28 11:19:37 +02002184
Serhiy Storchaka6dff0202016-05-07 10:49:07 +03002185 `IANA timezone database <https://www.iana.org/time-zones>`_
Brad3fb13632019-09-11 05:19:05 -04002186 The Time Zone Database (often called tz, tzdata or zoneinfo) contains code
2187 and data that represent the history of local time for many representative
Sandro Tosi100b8892012-04-28 11:19:37 +02002188 locations around the globe. It is updated periodically to reflect changes
2189 made by political bodies to time zone boundaries, UTC offsets, and
2190 daylight-saving rules.
Sandro Tosid11d0d62012-04-24 19:46:06 +02002191
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002192
2193.. _datetime-timezone:
2194
2195:class:`timezone` Objects
2196--------------------------
2197
Alexander Belopolsky6d3c9a62011-05-04 10:28:26 -04002198The :class:`timezone` class is a subclass of :class:`tzinfo`, each
2199instance of which represents a timezone defined by a fixed offset from
Brad3fb13632019-09-11 05:19:05 -04002200UTC.
2201
2202Objects of this class cannot be used to represent timezone information in the
2203locations where different offsets are used in different days of the year or
2204where historical changes have been made to civil time.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002205
2206
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04002207.. class:: timezone(offset, name=None)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002208
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002209 The *offset* argument must be specified as a :class:`timedelta`
Brad3fb13632019-09-11 05:19:05 -04002210 object representing the difference between the local time and UTC. It must
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002211 be strictly between ``-timedelta(hours=24)`` and
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002212 ``timedelta(hours=24)``, otherwise :exc:`ValueError` is raised.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002213
Brad3fb13632019-09-11 05:19:05 -04002214 The *name* argument is optional. If specified it must be a string that
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04002215 will be used as the value returned by the :meth:`datetime.tzname` method.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002216
Benjamin Peterson9b29acd2014-06-22 16:26:39 -07002217 .. versionadded:: 3.2
2218
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002219 .. versionchanged:: 3.7
2220 The UTC offset is not restricted to a whole number of minutes.
2221
2222
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002223.. method:: timezone.utcoffset(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002224
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002225 Return the fixed value specified when the :class:`timezone` instance is
Brad3fb13632019-09-11 05:19:05 -04002226 constructed.
2227
2228 The *dt* argument is ignored. The return value is a :class:`timedelta`
2229 instance equal to the difference between the local time and UTC.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002230
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002231 .. versionchanged:: 3.7
2232 The UTC offset is not restricted to a whole number of minutes.
2233
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002234.. method:: timezone.tzname(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002235
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04002236 Return the fixed value specified when the :class:`timezone` instance
Brad3fb13632019-09-11 05:19:05 -04002237 is constructed.
2238
2239 If *name* is not provided in the constructor, the name returned by
2240 ``tzname(dt)`` is generated from the value of the ``offset`` as follows. If
2241 *offset* is ``timedelta(0)``, the name is "UTC", otherwise it is a string in
2242 the format ``UTC±HH:MM``, where ± is the sign of ``offset``, HH and MM are
2243 two digits of ``offset.hours`` and ``offset.minutes`` respectively.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002244
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04002245 .. versionchanged:: 3.6
Brad3fb13632019-09-11 05:19:05 -04002246 Name generated from ``offset=timedelta(0)`` is now plain `'UTC'`, not
2247 ``'UTC+00:00'``.
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04002248
2249
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002250.. method:: timezone.dst(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002251
2252 Always returns ``None``.
2253
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002254.. method:: timezone.fromutc(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002255
Brad3fb13632019-09-11 05:19:05 -04002256 Return ``dt + offset``. The *dt* argument must be an aware
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002257 :class:`.datetime` instance, with ``tzinfo`` set to ``self``.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002258
2259Class attributes:
2260
2261.. attribute:: timezone.utc
2262
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002263 The UTC timezone, ``timezone(timedelta(0))``.
Georg Brandl48310cd2009-01-03 21:18:54 +00002264
Georg Brandl116aa622007-08-15 14:28:22 +00002265
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03002266.. index::
Serhiy Storchaka913876d2018-10-28 13:41:26 +02002267 single: % (percent); datetime format
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03002268
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002269.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00002270
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002271:meth:`strftime` and :meth:`strptime` Behavior
2272----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00002273
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002274:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
Georg Brandl116aa622007-08-15 14:28:22 +00002275``strftime(format)`` method, to create a string representing the time under the
Brad3fb13632019-09-11 05:19:05 -04002276control of an explicit format string.
Georg Brandl116aa622007-08-15 14:28:22 +00002277
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002278Conversely, the :meth:`datetime.strptime` class method creates a
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002279:class:`.datetime` object from a string representing a date and time and a
Brad3fb13632019-09-11 05:19:05 -04002280corresponding format string.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002281
Brad3fb13632019-09-11 05:19:05 -04002282The table below provides a high-level comparison of :meth:`strftime`
2283versus :meth:`strptime`:
Georg Brandl116aa622007-08-15 14:28:22 +00002284
Brad3fb13632019-09-11 05:19:05 -04002285+----------------+--------------------------------------------------------+------------------------------------------------------------------------------+
2286| | ``strftime`` | ``strptime`` |
2287+================+========================================================+==============================================================================+
2288| Usage | Convert object to a string according to a given format | Parse a string into a :class:`.datetime` object given a corresponding format |
2289+----------------+--------------------------------------------------------+------------------------------------------------------------------------------+
2290| Type of method | Instance method | Class method |
2291+----------------+--------------------------------------------------------+------------------------------------------------------------------------------+
2292| Method of | :class:`date`; :class:`.datetime`; :class:`.time` | :class:`.datetime` |
2293+----------------+--------------------------------------------------------+------------------------------------------------------------------------------+
2294| Signature | ``strftime(format)`` | ``strptime(date_string, format)`` |
2295+----------------+--------------------------------------------------------+------------------------------------------------------------------------------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002296
Abhishek Kumar Singh56027cc2019-05-19 02:06:19 +05302297
Brad3fb13632019-09-11 05:19:05 -04002298:meth:`strftime` and :meth:`strptime` Format Codes
2299^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Christian Heimes895627f2007-12-08 17:28:33 +00002300
Brad3fb13632019-09-11 05:19:05 -04002301The following is a list of all the format codes that the 1989 C standard
2302requires, and these work on all platforms with a standard C implementation.
Georg Brandl116aa622007-08-15 14:28:22 +00002303
David Wolever569a5fa2013-08-12 16:56:02 -04002304+-----------+--------------------------------+------------------------+-------+
2305| Directive | Meaning | Example | Notes |
2306+===========+================================+========================+=======+
2307| ``%a`` | Weekday as locale's || Sun, Mon, ..., Sat | \(1) |
2308| | abbreviated name. | (en_US); | |
2309| | || So, Mo, ..., Sa | |
2310| | | (de_DE) | |
2311+-----------+--------------------------------+------------------------+-------+
2312| ``%A`` | Weekday as locale's full name. || Sunday, Monday, ..., | \(1) |
2313| | | Saturday (en_US); | |
2314| | || Sonntag, Montag, ..., | |
2315| | | Samstag (de_DE) | |
2316+-----------+--------------------------------+------------------------+-------+
2317| ``%w`` | Weekday as a decimal number, | 0, 1, ..., 6 | |
2318| | where 0 is Sunday and 6 is | | |
2319| | Saturday. | | |
2320+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002321| ``%d`` | Day of the month as a | 01, 02, ..., 31 | \(9) |
David Wolever569a5fa2013-08-12 16:56:02 -04002322| | zero-padded decimal number. | | |
2323+-----------+--------------------------------+------------------------+-------+
2324| ``%b`` | Month as locale's abbreviated || Jan, Feb, ..., Dec | \(1) |
2325| | name. | (en_US); | |
2326| | || Jan, Feb, ..., Dez | |
2327| | | (de_DE) | |
2328+-----------+--------------------------------+------------------------+-------+
2329| ``%B`` | Month as locale's full name. || January, February, | \(1) |
2330| | | ..., December (en_US);| |
2331| | || Januar, Februar, ..., | |
2332| | | Dezember (de_DE) | |
2333+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002334| ``%m`` | Month as a zero-padded | 01, 02, ..., 12 | \(9) |
David Wolever569a5fa2013-08-12 16:56:02 -04002335| | decimal number. | | |
2336+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002337| ``%y`` | Year without century as a | 00, 01, ..., 99 | \(9) |
David Wolever569a5fa2013-08-12 16:56:02 -04002338| | zero-padded decimal number. | | |
2339+-----------+--------------------------------+------------------------+-------+
2340| ``%Y`` | Year with century as a decimal | 0001, 0002, ..., 2013, | \(2) |
David Wolever5d07e702013-08-14 14:41:48 -04002341| | number. | 2014, ..., 9998, 9999 | |
David Wolever569a5fa2013-08-12 16:56:02 -04002342+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002343| ``%H`` | Hour (24-hour clock) as a | 00, 01, ..., 23 | \(9) |
David Wolever569a5fa2013-08-12 16:56:02 -04002344| | zero-padded decimal number. | | |
2345+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002346| ``%I`` | Hour (12-hour clock) as a | 01, 02, ..., 12 | \(9) |
David Wolever569a5fa2013-08-12 16:56:02 -04002347| | zero-padded decimal number. | | |
2348+-----------+--------------------------------+------------------------+-------+
2349| ``%p`` | Locale's equivalent of either || AM, PM (en_US); | \(1), |
2350| | AM or PM. || am, pm (de_DE) | \(3) |
2351+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002352| ``%M`` | Minute as a zero-padded | 00, 01, ..., 59 | \(9) |
David Wolever569a5fa2013-08-12 16:56:02 -04002353| | decimal number. | | |
2354+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002355| ``%S`` | Second as a zero-padded | 00, 01, ..., 59 | \(4), |
2356| | decimal number. | | \(9) |
David Wolever569a5fa2013-08-12 16:56:02 -04002357+-----------+--------------------------------+------------------------+-------+
2358| ``%f`` | Microsecond as a decimal | 000000, 000001, ..., | \(5) |
2359| | number, zero-padded on the | 999999 | |
2360| | left. | | |
2361+-----------+--------------------------------+------------------------+-------+
Christophe Nanteuil92878822018-10-06 00:57:02 +02002362| ``%z`` | UTC offset in the form | (empty), +0000, | \(6) |
Brad3fb13632019-09-11 05:19:05 -04002363| | ``±HHMM[SS[.ffffff]]`` (empty | -0400, +1030, | |
Christophe Nanteuil92878822018-10-06 00:57:02 +02002364| | string if the object is | +063415, | |
2365| | naive). | -030712.345216 | |
David Wolever569a5fa2013-08-12 16:56:02 -04002366+-----------+--------------------------------+------------------------+-------+
Karl Dubostbc441ed2019-11-27 01:38:41 +09002367| ``%Z`` | Time zone name (empty string | (empty), UTC, GMT | \(6) |
David Wolever569a5fa2013-08-12 16:56:02 -04002368| | if the object is naive). | | |
2369+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002370| ``%j`` | Day of the year as a | 001, 002, ..., 366 | \(9) |
David Wolever569a5fa2013-08-12 16:56:02 -04002371| | zero-padded decimal number. | | |
2372+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002373| ``%U`` | Week number of the year | 00, 01, ..., 53 | \(7), |
2374| | (Sunday as the first day of | | \(9) |
David Wolever569a5fa2013-08-12 16:56:02 -04002375| | the week) as a zero padded | | |
2376| | decimal number. All days in a | | |
2377| | new year preceding the first | | |
2378| | Sunday are considered to be in | | |
2379| | week 0. | | |
2380+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002381| ``%W`` | Week number of the year | 00, 01, ..., 53 | \(7), |
2382| | (Monday as the first day of | | \(9) |
David Wolever569a5fa2013-08-12 16:56:02 -04002383| | the week) as a decimal number. | | |
2384| | All days in a new year | | |
2385| | preceding the first Monday | | |
2386| | are considered to be in | | |
2387| | week 0. | | |
2388+-----------+--------------------------------+------------------------+-------+
2389| ``%c`` | Locale's appropriate date and || Tue Aug 16 21:30:00 | \(1) |
2390| | time representation. | 1988 (en_US); | |
2391| | || Di 16 Aug 21:30:00 | |
2392| | | 1988 (de_DE) | |
2393+-----------+--------------------------------+------------------------+-------+
2394| ``%x`` | Locale's appropriate date || 08/16/88 (None); | \(1) |
2395| | representation. || 08/16/1988 (en_US); | |
2396| | || 16.08.1988 (de_DE) | |
2397+-----------+--------------------------------+------------------------+-------+
2398| ``%X`` | Locale's appropriate time || 21:30:00 (en_US); | \(1) |
2399| | representation. || 21:30:00 (de_DE) | |
2400+-----------+--------------------------------+------------------------+-------+
2401| ``%%`` | A literal ``'%'`` character. | % | |
2402+-----------+--------------------------------+------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00002403
Alexander Belopolsky68713e42015-10-06 13:29:56 -04002404Several additional directives not required by the C89 standard are included for
Brad3fb13632019-09-11 05:19:05 -04002405convenience. These parameters all correspond to ISO 8601 date values.
Alexander Belopolsky68713e42015-10-06 13:29:56 -04002406
2407+-----------+--------------------------------+------------------------+-------+
2408| Directive | Meaning | Example | Notes |
2409+===========+================================+========================+=======+
2410| ``%G`` | ISO 8601 year with century | 0001, 0002, ..., 2013, | \(8) |
2411| | representing the year that | 2014, ..., 9998, 9999 | |
2412| | contains the greater part of | | |
2413| | the ISO week (``%V``). | | |
2414+-----------+--------------------------------+------------------------+-------+
2415| ``%u`` | ISO 8601 weekday as a decimal | 1, 2, ..., 7 | |
2416| | number where 1 is Monday. | | |
2417+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002418| ``%V`` | ISO 8601 week as a decimal | 01, 02, ..., 53 | \(8), |
2419| | number with Monday as | | \(9) |
Alexander Belopolsky68713e42015-10-06 13:29:56 -04002420| | the first day of the week. | | |
2421| | Week 01 is the week containing | | |
2422| | Jan 4. | | |
2423+-----------+--------------------------------+------------------------+-------+
2424
Brad3fb13632019-09-11 05:19:05 -04002425These may not be available on all platforms when used with the :meth:`strftime`
2426method. The ISO 8601 year and ISO 8601 week directives are not interchangeable
2427with the year and week number directives above. Calling :meth:`strptime` with
2428incomplete or ambiguous ISO 8601 directives will raise a :exc:`ValueError`.
2429
2430The full set of format codes supported varies across platforms, because Python
2431calls the platform C library's :func:`strftime` function, and platform
2432variations are common. To see the full set of format codes supported on your
2433platform, consult the :manpage:`strftime(3)` documentation.
2434
Alexander Belopolsky68713e42015-10-06 13:29:56 -04002435.. versionadded:: 3.6
2436 ``%G``, ``%u`` and ``%V`` were added.
2437
Brad3fb13632019-09-11 05:19:05 -04002438Technical Detail
2439^^^^^^^^^^^^^^^^
2440
2441Broadly speaking, ``d.strftime(fmt)`` acts like the :mod:`time` module's
2442``time.strftime(fmt, d.timetuple())`` although not all objects support a
2443:meth:`timetuple` method.
2444
2445For the :meth:`datetime.strptime` class method, the default value is
2446``1900-01-01T00:00:00.000``: any components not specified in the format string
2447will be pulled from the default value. [#]_
2448
2449Using ``datetime.strptime(date_string, format)`` is equivalent to::
2450
2451 datetime(*(time.strptime(date_string, format)[0:6]))
2452
2453except when the format includes sub-second components or timezone offset
2454information, which are supported in ``datetime.strptime`` but are discarded by
2455``time.strptime``.
2456
2457For :class:`.time` objects, the format codes for year, month, and day should not
2458be used, as :class:`time` objects have no such values. If they're used anyway,
2459``1900`` is substituted for the year, and ``1`` for the month and day.
2460
2461For :class:`date` objects, the format codes for hours, minutes, seconds, and
2462microseconds should not be used, as :class:`date` objects have no such
2463values. If they're used anyway, ``0`` is substituted for them.
2464
2465For the same reason, handling of format strings containing Unicode code points
2466that can't be represented in the charset of the current locale is also
2467platform-dependent. On some platforms such code points are preserved intact in
2468the output, while on others ``strftime`` may raise :exc:`UnicodeError` or return
2469an empty string instead.
2470
Christian Heimes895627f2007-12-08 17:28:33 +00002471Notes:
2472
2473(1)
David Wolever569a5fa2013-08-12 16:56:02 -04002474 Because the format depends on the current locale, care should be taken when
2475 making assumptions about the output value. Field orderings will vary (for
2476 example, "month/day/year" versus "day/month/year"), and the output may
2477 contain Unicode characters encoded using the locale's default encoding (for
Georg Brandlad321532013-10-29 08:05:10 +01002478 example, if the current locale is ``ja_JP``, the default encoding could be
David Wolever569a5fa2013-08-12 16:56:02 -04002479 any one of ``eucJP``, ``SJIS``, or ``utf-8``; use :meth:`locale.getlocale`
2480 to determine the current locale's encoding).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002481
2482(2)
David Wolever569a5fa2013-08-12 16:56:02 -04002483 The :meth:`strptime` method can parse years in the full [1, 9999] range, but
2484 years < 1000 must be zero-filled to 4-digit width.
Alexander Belopolsky085556a2011-01-10 23:28:33 +00002485
2486 .. versionchanged:: 3.2
2487 In previous versions, :meth:`strftime` method was restricted to
2488 years >= 1900.
2489
Alexander Belopolsky5611a1c2011-05-02 14:14:48 -04002490 .. versionchanged:: 3.3
2491 In version 3.2, :meth:`strftime` method was restricted to
2492 years >= 1000.
2493
David Wolever569a5fa2013-08-12 16:56:02 -04002494(3)
2495 When used with the :meth:`strptime` method, the ``%p`` directive only affects
2496 the output hour field if the ``%I`` directive is used to parse the hour.
Alexander Belopolskyca94f552010-06-17 18:30:34 +00002497
David Wolever569a5fa2013-08-12 16:56:02 -04002498(4)
2499 Unlike the :mod:`time` module, the :mod:`datetime` module does not support
2500 leap seconds.
2501
2502(5)
2503 When used with the :meth:`strptime` method, the ``%f`` directive
Brad3fb13632019-09-11 05:19:05 -04002504 accepts from one to six digits and zero pads on the right. ``%f`` is
David Wolever569a5fa2013-08-12 16:56:02 -04002505 an extension to the set of format characters in the C standard (but
2506 implemented separately in datetime objects, and therefore always
2507 available).
2508
2509(6)
2510 For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
2511 strings.
2512
2513 For an aware object:
2514
2515 ``%z``
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002516 :meth:`utcoffset` is transformed into a string of the form
Brad3fb13632019-09-11 05:19:05 -04002517 ``±HHMM[SS[.ffffff]]``, where ``HH`` is a 2-digit string giving the number
2518 of UTC offset hours, ``MM`` is a 2-digit string giving the number of UTC
cocoatomo068768f2019-12-23 02:46:45 +09002519 offset minutes, ``SS`` is a 2-digit string giving the number of UTC offset
Brad3fb13632019-09-11 05:19:05 -04002520 seconds and ``ffffff`` is a 6-digit string giving the number of UTC
2521 offset microseconds. The ``ffffff`` part is omitted when the offset is a
2522 whole number of seconds and both the ``ffffff`` and the ``SS`` part is
2523 omitted when the offset is a whole number of minutes. For example, if
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002524 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
2525 replaced with the string ``'-0330'``.
2526
2527 .. versionchanged:: 3.7
2528 The UTC offset is not restricted to a whole number of minutes.
David Wolever569a5fa2013-08-12 16:56:02 -04002529
Mario Corchero32318932017-10-26 01:35:41 +01002530 .. versionchanged:: 3.7
2531 When the ``%z`` directive is provided to the :meth:`strptime` method,
2532 the UTC offsets can have a colon as a separator between hours, minutes
2533 and seconds.
2534 For example, ``'+01:00:00'`` will be parsed as an offset of one hour.
2535 In addition, providing ``'Z'`` is identical to ``'+00:00'``.
2536
David Wolever569a5fa2013-08-12 16:56:02 -04002537 ``%Z``
Karl Dubostbc441ed2019-11-27 01:38:41 +09002538 In :meth:`strftime`, ``%Z`` is replaced by an empty string if
2539 :meth:`tzname` returns ``None``; otherwise ``%Z`` is replaced by the
2540 returned value, which must be a string.
2541
2542 :meth:`strptime` only accepts certain values for ``%Z``:
2543
2544 1. any value in ``time.tzname`` for your machine's locale
2545 2. the hard-coded values ``UTC`` and ``GMT``
2546
2547 So someone living in Japan may have ``JST``, ``UTC``, and ``GMT`` as
2548 valid values, but probably not ``EST``. It will raise ``ValueError`` for
2549 invalid values.
David Wolever569a5fa2013-08-12 16:56:02 -04002550
2551 .. versionchanged:: 3.2
2552 When the ``%z`` directive is provided to the :meth:`strptime` method, an
Brad3fb13632019-09-11 05:19:05 -04002553 aware :class:`.datetime` object will be produced. The ``tzinfo`` of the
David Wolever569a5fa2013-08-12 16:56:02 -04002554 result will be set to a :class:`timezone` instance.
2555
2556(7)
2557 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used
Alexander Belopolsky68713e42015-10-06 13:29:56 -04002558 in calculations when the day of the week and the calendar year (``%Y``)
2559 are specified.
2560
2561(8)
2562 Similar to ``%U`` and ``%W``, ``%V`` is only used in calculations when the
2563 day of the week and the ISO year (``%G``) are specified in a
2564 :meth:`strptime` format string. Also note that ``%G`` and ``%Y`` are not
Martin Panterf1579822016-05-26 06:03:33 +00002565 interchangeable.
R David Murray9075d8b2012-05-14 22:14:46 -04002566
Mike Gleen6b9c2042019-06-18 19:14:57 +01002567(9)
2568 When used with the :meth:`strptime` method, the leading zero is optional
2569 for formats ``%d``, ``%m``, ``%H``, ``%I``, ``%M``, ``%S``, ``%J``, ``%U``,
2570 ``%W``, and ``%V``. Format ``%y`` does require a leading zero.
2571
R David Murray9075d8b2012-05-14 22:14:46 -04002572.. rubric:: Footnotes
2573
2574.. [#] If, that is, we ignore the effects of Relativity
Brad3fb13632019-09-11 05:19:05 -04002575
2576.. [#] This matches the definition of the "proleptic Gregorian" calendar in
2577 Dershowitz and Reingold's book *Calendrical Calculations*,
2578 where it's the base calendar for all computations. See the book for
2579 algorithms for converting between proleptic Gregorian ordinals and
2580 many other calendar systems.
2581
2582.. [#] See R. H. van Gent's `guide to the mathematics of the ISO 8601 calendar
2583 <https://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm>`_
2584 for a good explanation.
2585
Abhishek Kumar Singh56027cc2019-05-19 02:06:19 +05302586.. [#] Passing ``datetime.strptime('Feb 29', '%b %d')`` will fail since ``1900`` is not a leap year.