blob: 508bc88e7f4b8a3ef76d14d7a24f1cc8e9f09cb8 [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
Miss Islington (bot)c1d77682020-05-22 15:30:47 -070038Date and time objects may be categorized as "aware" or "naive" depending on
39whether or not they include timezone information.
Brad3fb13632019-09-11 05:19:05 -040040
41With sufficient knowledge of applicable algorithmic and political time
42adjustments, such as time zone and daylight saving time information,
43an **aware** object can locate itself relative to other aware objects.
44An aware object represents a specific moment in time that is not open to
45interpretation. [#]_
46
47A **naive** object does not contain enough information to unambiguously locate
48itself relative to other date/time objects. Whether a naive object represents
R David Murray539f2392012-05-14 22:17:23 -040049Coordinated Universal Time (UTC), local time, or time in some other timezone is
50purely up to the program, just like it is up to the program whether a
Brad3fb13632019-09-11 05:19:05 -040051particular number represents metres, miles, or mass. Naive objects are easy to
R David Murray539f2392012-05-14 22:17:23 -040052understand and to work with, at the cost of ignoring some aspects of reality.
Georg Brandl116aa622007-08-15 14:28:22 +000053
R David Murray539f2392012-05-14 22:17:23 -040054For applications requiring aware objects, :class:`.datetime` and :class:`.time`
Martin Panter16c7cfd2016-04-01 21:48:24 +000055objects have an optional time zone information attribute, :attr:`!tzinfo`, that
R David Murray539f2392012-05-14 22:17:23 -040056can be set to an instance of a subclass of the abstract :class:`tzinfo` class.
57These :class:`tzinfo` objects capture information about the offset from UTC
Brad3fb13632019-09-11 05:19:05 -040058time, the time zone name, and whether daylight saving time is in effect.
59
60Only one concrete :class:`tzinfo` class, the :class:`timezone` class, is
61supplied by the :mod:`datetime` module. The :class:`timezone` class can
62represent simple timezones with fixed offsets from UTC, such as UTC itself or
63North American EST and EDT timezones. Supporting timezones at deeper levels of
64detail is up to the application. The rules for time adjustment across the
Alexander Belopolsky4e749a12010-06-14 14:15:50 +000065world are more political than rational, change frequently, and there is no
66standard suitable for every application aside from UTC.
Georg Brandl116aa622007-08-15 14:28:22 +000067
Brad3fb13632019-09-11 05:19:05 -040068Constants
69---------
70
Georg Brandl116aa622007-08-15 14:28:22 +000071The :mod:`datetime` module exports the following constants:
72
Georg Brandl116aa622007-08-15 14:28:22 +000073.. data:: MINYEAR
74
Ezio Melotti35ec7f72011-10-02 12:44:50 +030075 The smallest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl116aa622007-08-15 14:28:22 +000076 :const:`MINYEAR` is ``1``.
77
78
79.. data:: MAXYEAR
80
Ezio Melotti35ec7f72011-10-02 12:44:50 +030081 The largest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl116aa622007-08-15 14:28:22 +000082 :const:`MAXYEAR` is ``9999``.
83
Georg Brandl116aa622007-08-15 14:28:22 +000084Available Types
85---------------
86
Georg Brandl116aa622007-08-15 14:28:22 +000087.. class:: date
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000088 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000089
90 An idealized naive date, assuming the current Gregorian calendar always was, and
91 always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and
92 :attr:`day`.
93
94
95.. class:: time
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000096 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000097
98 An idealized time, independent of any particular day, assuming that every day
Brad3fb13632019-09-11 05:19:05 -040099 has exactly 24\*60\*60 seconds. (There is no notion of "leap seconds" here.)
Georg Brandl116aa622007-08-15 14:28:22 +0000100 Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
Martin Panter16c7cfd2016-04-01 21:48:24 +0000101 and :attr:`.tzinfo`.
Georg Brandl116aa622007-08-15 14:28:22 +0000102
103
104.. class:: datetime
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000105 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000106
107 A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`,
108 :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
Martin Panter16c7cfd2016-04-01 21:48:24 +0000109 and :attr:`.tzinfo`.
Georg Brandl116aa622007-08-15 14:28:22 +0000110
111
112.. class:: timedelta
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000113 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000114
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300115 A duration expressing the difference between two :class:`date`, :class:`.time`,
116 or :class:`.datetime` instances to microsecond resolution.
Georg Brandl116aa622007-08-15 14:28:22 +0000117
118
119.. class:: tzinfo
Martin Panter16c7cfd2016-04-01 21:48:24 +0000120 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000121
Brad3fb13632019-09-11 05:19:05 -0400122 An abstract base class for time zone information objects. These are used by the
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300123 :class:`.datetime` and :class:`.time` classes to provide a customizable notion of
Georg Brandl116aa622007-08-15 14:28:22 +0000124 time adjustment (for example, to account for time zone and/or daylight saving
125 time).
126
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000127.. class:: timezone
Martin Panter16c7cfd2016-04-01 21:48:24 +0000128 :noindex:
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000129
130 A class that implements the :class:`tzinfo` abstract base class as a
131 fixed offset from the UTC.
132
133 .. versionadded:: 3.2
134
Georg Brandl116aa622007-08-15 14:28:22 +0000135Objects of these types are immutable.
136
Georg Brandl116aa622007-08-15 14:28:22 +0000137Subclass relationships::
138
139 object
140 timedelta
141 tzinfo
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000142 timezone
Georg Brandl116aa622007-08-15 14:28:22 +0000143 time
144 date
145 datetime
146
Brad3fb13632019-09-11 05:19:05 -0400147Common Properties
148^^^^^^^^^^^^^^^^^
149
150The :class:`date`, :class:`.datetime`, :class:`.time`, and :class:`timezone` types
151share these common features:
152
153- Objects of these types are immutable.
154- Objects of these types are hashable, meaning that they can be used as
155 dictionary keys.
156- Objects of these types support efficient pickling via the :mod:`pickle` module.
157
158Determining if an Object is Aware or Naive
159^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
160
161Objects of the :class:`date` type are always naive.
162
163An object of type :class:`.time` or :class:`.datetime` may be aware or naive.
164
165A :class:`.datetime` object *d* is aware if both of the following hold:
166
1671. ``d.tzinfo`` is not ``None``
1682. ``d.tzinfo.utcoffset(d)`` does not return ``None``
169
170Otherwise, *d* is naive.
171
172A :class:`.time` object *t* is aware if both of the following hold:
173
1741. ``t.tzinfo`` is not ``None``
1752. ``t.tzinfo.utcoffset(None)`` does not return ``None``.
176
177Otherwise, *t* is naive.
178
179The distinction between aware and naive doesn't apply to :class:`timedelta`
180objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000181
182.. _datetime-timedelta:
183
184:class:`timedelta` Objects
185--------------------------
186
187A :class:`timedelta` object represents a duration, the difference between two
188dates or times.
189
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000190.. class:: timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000191
Brad3fb13632019-09-11 05:19:05 -0400192 All arguments are optional and default to ``0``. Arguments may be integers
Georg Brandl116aa622007-08-15 14:28:22 +0000193 or floats, and may be positive or negative.
194
Brad3fb13632019-09-11 05:19:05 -0400195 Only *days*, *seconds* and *microseconds* are stored internally.
196 Arguments are converted to those units:
Georg Brandl116aa622007-08-15 14:28:22 +0000197
198 * A millisecond is converted to 1000 microseconds.
199 * A minute is converted to 60 seconds.
200 * An hour is converted to 3600 seconds.
201 * A week is converted to 7 days.
202
203 and days, seconds and microseconds are then normalized so that the
204 representation is unique, with
205
206 * ``0 <= microseconds < 1000000``
207 * ``0 <= seconds < 3600*24`` (the number of seconds in one day)
208 * ``-999999999 <= days <= 999999999``
209
Brad3fb13632019-09-11 05:19:05 -0400210 The following example illustrates how any arguments besides
211 *days*, *seconds* and *microseconds* are "merged" and normalized into those
212 three resulting attributes::
213
214 >>> from datetime import timedelta
215 >>> delta = timedelta(
216 ... days=50,
217 ... seconds=27,
218 ... microseconds=10,
219 ... milliseconds=29000,
220 ... minutes=5,
221 ... hours=8,
222 ... weeks=2
223 ... )
224 >>> # Only days, seconds, and microseconds remain
225 >>> delta
226 datetime.timedelta(days=64, seconds=29156, microseconds=10)
227
Alexander Belopolsky790d2692013-08-04 14:51:35 -0400228 If any argument is a float and there are fractional microseconds,
229 the fractional microseconds left over from all arguments are
230 combined and their sum is rounded to the nearest microsecond using
Brad3fb13632019-09-11 05:19:05 -0400231 round-half-to-even tiebreaker. If no argument is a float, the
Alexander Belopolsky790d2692013-08-04 14:51:35 -0400232 conversion and normalization processes are exact (no information is
233 lost).
Georg Brandl116aa622007-08-15 14:28:22 +0000234
235 If the normalized value of days lies outside the indicated range,
236 :exc:`OverflowError` is raised.
237
238 Note that normalization of negative values may be surprising at first. For
Brad3fb13632019-09-11 05:19:05 -0400239 example::
Georg Brandl116aa622007-08-15 14:28:22 +0000240
Christian Heimes895627f2007-12-08 17:28:33 +0000241 >>> from datetime import timedelta
Georg Brandl116aa622007-08-15 14:28:22 +0000242 >>> d = timedelta(microseconds=-1)
243 >>> (d.days, d.seconds, d.microseconds)
244 (-1, 86399, 999999)
245
Georg Brandl116aa622007-08-15 14:28:22 +0000246
Brad3fb13632019-09-11 05:19:05 -0400247Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000248
249.. attribute:: timedelta.min
250
251 The most negative :class:`timedelta` object, ``timedelta(-999999999)``.
252
253
254.. attribute:: timedelta.max
255
256 The most positive :class:`timedelta` object, ``timedelta(days=999999999,
257 hours=23, minutes=59, seconds=59, microseconds=999999)``.
258
259
260.. attribute:: timedelta.resolution
261
262 The smallest possible difference between non-equal :class:`timedelta` objects,
263 ``timedelta(microseconds=1)``.
264
265Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``.
266``-timedelta.max`` is not representable as a :class:`timedelta` object.
267
268Instance attributes (read-only):
269
270+------------------+--------------------------------------------+
271| Attribute | Value |
272+==================+============================================+
273| ``days`` | Between -999999999 and 999999999 inclusive |
274+------------------+--------------------------------------------+
275| ``seconds`` | Between 0 and 86399 inclusive |
276+------------------+--------------------------------------------+
277| ``microseconds`` | Between 0 and 999999 inclusive |
278+------------------+--------------------------------------------+
279
280Supported operations:
281
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000282.. XXX this table is too wide!
Georg Brandl116aa622007-08-15 14:28:22 +0000283
284+--------------------------------+-----------------------------------------------+
285| Operation | Result |
286+================================+===============================================+
287| ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == |
288| | *t3* and *t1*-*t3* == *t2* are true. (1) |
289+--------------------------------+-----------------------------------------------+
290| ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* |
291| | == *t2* - *t3* and *t2* == *t1* + *t3* are |
Farhaan Bukhsh5b6e49a2018-07-05 00:12:05 +0530292| | true. (1)(6) |
Georg Brandl116aa622007-08-15 14:28:22 +0000293+--------------------------------+-----------------------------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000294| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer. |
Georg Brandl116aa622007-08-15 14:28:22 +0000295| | Afterwards *t1* // i == *t2* is true, |
296| | provided ``i != 0``. |
297+--------------------------------+-----------------------------------------------+
298| | In general, *t1* \* i == *t1* \* (i-1) + *t1* |
299| | is true. (1) |
300+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000301| ``t1 = t2 * f or t1 = f * t2`` | Delta multiplied by a float. The result is |
302| | rounded to the nearest multiple of |
303| | timedelta.resolution using round-half-to-even.|
304+--------------------------------+-----------------------------------------------+
Yasser Af40b4a02019-03-15 23:56:58 -0400305| ``f = t2 / t3`` | Division (3) of overall duration *t2* by |
306| | interval unit *t3*. Returns a :class:`float` |
307| | object. |
Mark Dickinson7c186e22010-04-20 22:32:49 +0000308+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000309| ``t1 = t2 / f or t1 = t2 / i`` | Delta divided by a float or an int. The result|
310| | is rounded to the nearest multiple of |
311| | timedelta.resolution using round-half-to-even.|
312+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000313| ``t1 = t2 // i`` or | The floor is computed and the remainder (if |
Brad3fb13632019-09-11 05:19:05 -0400314| ``t1 = t2 // t3`` | any) is thrown away. In the second case, an |
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000315| | integer is returned. (3) |
Mark Dickinson7c186e22010-04-20 22:32:49 +0000316+--------------------------------+-----------------------------------------------+
317| ``t1 = t2 % t3`` | The remainder is computed as a |
318| | :class:`timedelta` object. (3) |
319+--------------------------------+-----------------------------------------------+
320| ``q, r = divmod(t1, t2)`` | Computes the quotient and the remainder: |
321| | ``q = t1 // t2`` (3) and ``r = t1 % t2``. |
322| | q is an integer and r is a :class:`timedelta` |
323| | object. |
Georg Brandl116aa622007-08-15 14:28:22 +0000324+--------------------------------+-----------------------------------------------+
325| ``+t1`` | Returns a :class:`timedelta` object with the |
326| | same value. (2) |
327+--------------------------------+-----------------------------------------------+
Serhiy Storchaka3f819ca2018-10-31 02:26:06 +0200328| ``-t1`` | equivalent to |
329| | :class:`timedelta`\ (-*t1.days*, |
330| | -*t1.seconds*, -*t1.microseconds*), |
331| | and to *t1*\* -1. (1)(4) |
Georg Brandl116aa622007-08-15 14:28:22 +0000332+--------------------------------+-----------------------------------------------+
Brad3fb13632019-09-11 05:19:05 -0400333| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, |
334| | and to -*t* when ``t.days < 0``. (2) |
Georg Brandl116aa622007-08-15 14:28:22 +0000335+--------------------------------+-----------------------------------------------+
Georg Brandlf55c3152010-07-31 11:40:07 +0000336| ``str(t)`` | Returns a string in the form |
337| | ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D |
338| | is negative for negative ``t``. (5) |
339+--------------------------------+-----------------------------------------------+
Utkarsh Upadhyaycc5a65c2017-07-25 23:51:33 +0200340| ``repr(t)`` | Returns a string representation of the |
341| | :class:`timedelta` object as a constructor |
342| | call with canonical attribute values. |
Georg Brandlf55c3152010-07-31 11:40:07 +0000343+--------------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000344
Utkarsh Upadhyaycc5a65c2017-07-25 23:51:33 +0200345
Georg Brandl116aa622007-08-15 14:28:22 +0000346Notes:
347
348(1)
Brad3fb13632019-09-11 05:19:05 -0400349 This is exact but may overflow.
Georg Brandl116aa622007-08-15 14:28:22 +0000350
351(2)
Brad3fb13632019-09-11 05:19:05 -0400352 This is exact and cannot overflow.
Georg Brandl116aa622007-08-15 14:28:22 +0000353
354(3)
355 Division by 0 raises :exc:`ZeroDivisionError`.
356
357(4)
358 -*timedelta.max* is not representable as a :class:`timedelta` object.
359
Georg Brandlf55c3152010-07-31 11:40:07 +0000360(5)
Brad3fb13632019-09-11 05:19:05 -0400361 String representations of :class:`timedelta` objects are normalized
362 similarly to their internal representation. This leads to somewhat
363 unusual results for negative timedeltas. For example::
Georg Brandlf55c3152010-07-31 11:40:07 +0000364
Brad3fb13632019-09-11 05:19:05 -0400365 >>> timedelta(hours=-5)
366 datetime.timedelta(days=-1, seconds=68400)
367 >>> print(_)
368 -1 day, 19:00:00
Georg Brandlf55c3152010-07-31 11:40:07 +0000369
Farhaan Bukhsh5b6e49a2018-07-05 00:12:05 +0530370(6)
371 The expression ``t2 - t3`` will always be equal to the expression ``t2 + (-t3)`` except
372 when t3 is equal to ``timedelta.max``; in that case the former will produce a result
373 while the latter will overflow.
374
Brad3fb13632019-09-11 05:19:05 -0400375In addition to the operations listed above, :class:`timedelta` objects support
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300376certain additions and subtractions with :class:`date` and :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +0000377objects (see below).
378
Georg Brandl67b21b72010-08-17 15:07:14 +0000379.. versionchanged:: 3.2
380 Floor division and true division of a :class:`timedelta` object by another
381 :class:`timedelta` object are now supported, as are remainder operations and
Brad3fb13632019-09-11 05:19:05 -0400382 the :func:`divmod` function. True division and multiplication of a
Georg Brandl67b21b72010-08-17 15:07:14 +0000383 :class:`timedelta` object by a :class:`float` object are now supported.
Mark Dickinson7c186e22010-04-20 22:32:49 +0000384
385
Brad3fb13632019-09-11 05:19:05 -0400386Comparisons of :class:`timedelta` objects are supported, with some caveats.
Georg Brandl116aa622007-08-15 14:28:22 +0000387
Brad3fb13632019-09-11 05:19:05 -0400388The comparisons ``==`` or ``!=`` *always* return a :class:`bool`, no matter
389the type of the compared object::
390
391 >>> from datetime import timedelta
392 >>> delta1 = timedelta(seconds=57)
393 >>> delta2 = timedelta(hours=25, seconds=2)
394 >>> delta2 != delta1
395 True
396 >>> delta2 == 5
397 False
398
399For all other comparisons (such as ``<`` and ``>``), when a :class:`timedelta`
400object is compared to an object of a different type, :exc:`TypeError`
401is raised::
402
403 >>> delta2 > delta1
404 True
405 >>> delta2 > 5
406 Traceback (most recent call last):
407 File "<stdin>", line 1, in <module>
408 TypeError: '>' not supported between instances of 'datetime.timedelta' and 'int'
409
410In Boolean contexts, a :class:`timedelta` object is
Georg Brandl116aa622007-08-15 14:28:22 +0000411considered to be true if and only if it isn't equal to ``timedelta(0)``.
412
Antoine Pitroube6859d2009-11-25 23:02:32 +0000413Instance methods:
414
415.. method:: timedelta.total_seconds()
416
417 Return the total number of seconds contained in the duration. Equivalent to
Yasser Af40b4a02019-03-15 23:56:58 -0400418 ``td / timedelta(seconds=1)``. For interval units other than seconds, use the
419 division form directly (e.g. ``td / timedelta(microseconds=1)``).
Mark Dickinson0381e3f2010-05-08 14:35:02 +0000420
421 Note that for very large time intervals (greater than 270 years on
422 most platforms) this method will lose microsecond accuracy.
Antoine Pitroube6859d2009-11-25 23:02:32 +0000423
424 .. versionadded:: 3.2
425
Brad3fb13632019-09-11 05:19:05 -0400426Examples of usage: :class:`timedelta`
427^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Antoine Pitroube6859d2009-11-25 23:02:32 +0000428
Brad3fb13632019-09-11 05:19:05 -0400429An additional example of normalization::
Georg Brandl48310cd2009-01-03 21:18:54 +0000430
Brad3fb13632019-09-11 05:19:05 -0400431 >>> # Components of another_year add up to exactly 365 days
Christian Heimes895627f2007-12-08 17:28:33 +0000432 >>> from datetime import timedelta
433 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000434 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Brad3fb13632019-09-11 05:19:05 -0400435 ... minutes=50, seconds=600)
Christian Heimes895627f2007-12-08 17:28:33 +0000436 >>> year == another_year
437 True
Brad3fb13632019-09-11 05:19:05 -0400438 >>> year.total_seconds()
439 31536000.0
440
441Examples of :class:`timedelta` arithmetic::
442
443 >>> from datetime import timedelta
444 >>> year = timedelta(days=365)
Christian Heimes895627f2007-12-08 17:28:33 +0000445 >>> ten_years = 10 * year
Brad3fb13632019-09-11 05:19:05 -0400446 >>> ten_years
447 datetime.timedelta(days=3650)
448 >>> ten_years.days // 365
449 10
Christian Heimes895627f2007-12-08 17:28:33 +0000450 >>> nine_years = ten_years - year
Brad3fb13632019-09-11 05:19:05 -0400451 >>> nine_years
452 datetime.timedelta(days=3285)
delirious-lettucec7b3f0f2017-05-18 19:01:00 -0600453 >>> three_years = nine_years // 3
Christian Heimes895627f2007-12-08 17:28:33 +0000454 >>> three_years, three_years.days // 365
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +0200455 (datetime.timedelta(days=1095), 3)
Georg Brandl116aa622007-08-15 14:28:22 +0000456
457.. _datetime-date:
458
459:class:`date` Objects
460---------------------
461
462A :class:`date` object represents a date (year, month and day) in an idealized
463calendar, the current Gregorian calendar indefinitely extended in both
Brad3fb13632019-09-11 05:19:05 -0400464directions.
Georg Brandl116aa622007-08-15 14:28:22 +0000465
Brad3fb13632019-09-11 05:19:05 -0400466January 1 of year 1 is called day number 1, January 2 of year 1 is
467called day number 2, and so on. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +0000468
469.. class:: date(year, month, day)
470
Brad3fb13632019-09-11 05:19:05 -0400471 All arguments are required. Arguments must be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000472 ranges:
473
474 * ``MINYEAR <= year <= MAXYEAR``
475 * ``1 <= month <= 12``
476 * ``1 <= day <= number of days in the given month and year``
477
478 If an argument outside those ranges is given, :exc:`ValueError` is raised.
479
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000480
Georg Brandl116aa622007-08-15 14:28:22 +0000481Other constructors, all class methods:
482
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000483.. classmethod:: date.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000484
Brad3fb13632019-09-11 05:19:05 -0400485 Return the current local date.
Georg Brandl116aa622007-08-15 14:28:22 +0000486
Brad3fb13632019-09-11 05:19:05 -0400487 This is equivalent to ``date.fromtimestamp(time.time())``.
Georg Brandl116aa622007-08-15 14:28:22 +0000488
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000489.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000490
Brad3fb13632019-09-11 05:19:05 -0400491 Return the local date corresponding to the POSIX timestamp, such as is
492 returned by :func:`time.time`.
493
494 This may raise :exc:`OverflowError`, if the timestamp is out
495 of the range of values supported by the platform C :c:func:`localtime`
496 function, and :exc:`OSError` on :c:func:`localtime` failure.
497 It's common for this to be restricted to years from 1970 through 2038. Note
Georg Brandl116aa622007-08-15 14:28:22 +0000498 that on non-POSIX systems that include leap seconds in their notion of a
499 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
500
Victor Stinner5d272cc2012-03-13 13:35:55 +0100501 .. versionchanged:: 3.3
502 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
503 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100504 :c:func:`localtime` function. Raise :exc:`OSError` instead of
505 :exc:`ValueError` on :c:func:`localtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100506
Georg Brandl116aa622007-08-15 14:28:22 +0000507
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000508.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000509
Brad3fb13632019-09-11 05:19:05 -0400510 Return the date corresponding to the proleptic Gregorian ordinal, where
511 January 1 of year 1 has ordinal 1.
512
513 :exc:`ValueError` is raised unless ``1 <= ordinal <=
514 date.max.toordinal()``. For any date *d*,
515 ``date.fromordinal(d.toordinal()) == d``.
Georg Brandl116aa622007-08-15 14:28:22 +0000516
Georg Brandl116aa622007-08-15 14:28:22 +0000517
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500518.. classmethod:: date.fromisoformat(date_string)
519
Brad3fb13632019-09-11 05:19:05 -0400520 Return a :class:`date` corresponding to a *date_string* given in the format
521 ``YYYY-MM-DD``::
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500522
Brad3fb13632019-09-11 05:19:05 -0400523 >>> from datetime import date
524 >>> date.fromisoformat('2019-12-04')
525 datetime.date(2019, 12, 4)
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500526
Brad3fb13632019-09-11 05:19:05 -0400527 This is the inverse of :meth:`date.isoformat`. It only supports the format
528 ``YYYY-MM-DD``.
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500529
Brad3fb13632019-09-11 05:19:05 -0400530 .. versionadded:: 3.7
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500531
532
Paul Ganssle88c09372019-04-29 09:22:03 -0400533.. classmethod:: date.fromisocalendar(year, week, day)
534
535 Return a :class:`date` corresponding to the ISO calendar date specified by
536 year, week and day. This is the inverse of the function :meth:`date.isocalendar`.
537
538 .. versionadded:: 3.8
539
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500540
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000541Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000542
543.. attribute:: date.min
544
545 The earliest representable date, ``date(MINYEAR, 1, 1)``.
546
547
548.. attribute:: date.max
549
550 The latest representable date, ``date(MAXYEAR, 12, 31)``.
551
552
553.. attribute:: date.resolution
554
555 The smallest possible difference between non-equal date objects,
556 ``timedelta(days=1)``.
557
Georg Brandl116aa622007-08-15 14:28:22 +0000558
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000559Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000560
561.. attribute:: date.year
562
563 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
564
565
566.. attribute:: date.month
567
568 Between 1 and 12 inclusive.
569
570
571.. attribute:: date.day
572
573 Between 1 and the number of days in the given month of the given year.
574
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000575
Georg Brandl116aa622007-08-15 14:28:22 +0000576Supported operations:
577
578+-------------------------------+----------------------------------------------+
579| Operation | Result |
580+===============================+==============================================+
581| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
Brad3fb13632019-09-11 05:19:05 -0400582| | from *date1*. (1) |
Georg Brandl116aa622007-08-15 14:28:22 +0000583+-------------------------------+----------------------------------------------+
584| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
585| | timedelta == date1``. (2) |
586+-------------------------------+----------------------------------------------+
587| ``timedelta = date1 - date2`` | \(3) |
588+-------------------------------+----------------------------------------------+
589| ``date1 < date2`` | *date1* is considered less than *date2* when |
590| | *date1* precedes *date2* in time. (4) |
591+-------------------------------+----------------------------------------------+
592
593Notes:
594
595(1)
596 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
Brad3fb13632019-09-11 05:19:05 -0400597 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
Georg Brandl116aa622007-08-15 14:28:22 +0000598 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
599 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
600 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
601
602(2)
Georg Brandl116aa622007-08-15 14:28:22 +0000603 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
604
605(3)
Brad3fb13632019-09-11 05:19:05 -0400606 This is exact, and cannot overflow. timedelta.seconds and
Georg Brandl116aa622007-08-15 14:28:22 +0000607 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
608
609(4)
610 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
Danish Prakash9c223792018-09-12 02:29:23 +0530611 date2.toordinal()``. Date comparison raises :exc:`TypeError` if
612 the other comparand isn't also a :class:`date` object. However,
613 ``NotImplemented`` is returned instead if the other comparand has a
Brad3fb13632019-09-11 05:19:05 -0400614 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
Georg Brandl116aa622007-08-15 14:28:22 +0000615 chance at implementing mixed-type comparison. If not, when a :class:`date`
616 object is compared to an object of a different type, :exc:`TypeError` is raised
Brad3fb13632019-09-11 05:19:05 -0400617 unless the comparison is ``==`` or ``!=``. The latter cases return
Georg Brandl116aa622007-08-15 14:28:22 +0000618 :const:`False` or :const:`True`, respectively.
619
Brad3fb13632019-09-11 05:19:05 -0400620In Boolean contexts, all :class:`date` objects are considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +0000621
622Instance methods:
623
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400624.. method:: date.replace(year=self.year, month=self.month, day=self.day)
Georg Brandl116aa622007-08-15 14:28:22 +0000625
Senthil Kumarana6bac952011-07-04 11:28:30 -0700626 Return a date with the same value, except for those parameters given new
Brad3fb13632019-09-11 05:19:05 -0400627 values by whichever keyword arguments are specified.
628
629 Example::
630
631 >>> from datetime import date
632 >>> d = date(2002, 12, 31)
633 >>> d.replace(day=26)
634 datetime.date(2002, 12, 26)
Georg Brandl116aa622007-08-15 14:28:22 +0000635
636
637.. method:: date.timetuple()
638
639 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
Brad3fb13632019-09-11 05:19:05 -0400640
641 The hours, minutes and seconds are 0, and the DST flag is -1.
642
643 ``d.timetuple()`` is equivalent to::
644
645 time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1))
646
647 where ``yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1``
648 is the day number within the current year starting with ``1`` for January 1st.
Georg Brandl116aa622007-08-15 14:28:22 +0000649
650
651.. method:: date.toordinal()
652
653 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
Brad3fb13632019-09-11 05:19:05 -0400654 has ordinal 1. For any :class:`date` object *d*,
Georg Brandl116aa622007-08-15 14:28:22 +0000655 ``date.fromordinal(d.toordinal()) == d``.
656
657
658.. method:: date.weekday()
659
660 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
661 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
662 :meth:`isoweekday`.
663
664
665.. method:: date.isoweekday()
666
667 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
668 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
669 :meth:`weekday`, :meth:`isocalendar`.
670
671
672.. method:: date.isocalendar()
673
Paul Ganssle1b97b9b2020-05-16 10:02:59 -0400674 Return a :term:`named tuple` object with three components: ``year``,
675 ``week`` and ``weekday``.
Georg Brandl116aa622007-08-15 14:28:22 +0000676
Brad3fb13632019-09-11 05:19:05 -0400677 The ISO calendar is a widely used variant of the Gregorian calendar. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +0000678
679 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
Brad3fb13632019-09-11 05:19:05 -0400680 Monday and ends on a Sunday. The first week of an ISO year is the first
Georg Brandl116aa622007-08-15 14:28:22 +0000681 (Gregorian) calendar week of a year containing a Thursday. This is called week
682 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
683
684 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
Brad3fb13632019-09-11 05:19:05 -0400685 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004::
Georg Brandl116aa622007-08-15 14:28:22 +0000686
Paul Ganssle1b97b9b2020-05-16 10:02:59 -0400687 >>> from datetime import date
688 >>> date(2003, 12, 29).isocalendar()
689 datetime.IsoCalendarDate(year=2004, week=1, weekday=1)
690 >>> date(2004, 1, 4).isocalendar()
691 datetime.IsoCalendarDate(year=2004, week=1, weekday=7)
692
693 .. versionchanged:: 3.9
694 Result changed from a tuple to a :term:`named tuple`.
Georg Brandl116aa622007-08-15 14:28:22 +0000695
696.. method:: date.isoformat()
697
Brad3fb13632019-09-11 05:19:05 -0400698 Return a string representing the date in ISO 8601 format, ``YYYY-MM-DD``::
Georg Brandl116aa622007-08-15 14:28:22 +0000699
Brad3fb13632019-09-11 05:19:05 -0400700 >>> from datetime import date
701 >>> date(2002, 12, 4).isoformat()
702 '2002-12-04'
703
704 This is the inverse of :meth:`date.fromisoformat`.
Georg Brandl116aa622007-08-15 14:28:22 +0000705
706.. method:: date.__str__()
707
708 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
709
710
711.. method:: date.ctime()
712
Brad3fb13632019-09-11 05:19:05 -0400713 Return a string representing the date::
714
715 >>> from datetime import date
716 >>> date(2002, 12, 4).ctime()
717 'Wed Dec 4 00:00:00 2002'
718
719 ``d.ctime()`` is equivalent to::
720
721 time.ctime(time.mktime(d.timetuple()))
722
723 on platforms where the native C
Georg Brandl60203b42010-10-06 10:11:56 +0000724 :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +0000725 :meth:`date.ctime` does not invoke) conforms to the C standard.
726
727
728.. method:: date.strftime(format)
729
730 Return a string representing the date, controlled by an explicit format string.
David Wolever569a5fa2013-08-12 16:56:02 -0400731 Format codes referring to hours, minutes or seconds will see 0 values. For a
732 complete list of formatting directives, see
733 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000734
Georg Brandl116aa622007-08-15 14:28:22 +0000735
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300736.. method:: date.__format__(format)
737
Martin Panterd5db1472016-02-08 01:34:09 +0000738 Same as :meth:`.date.strftime`. This makes it possible to specify a format
Martin Panterbc1ee462016-02-13 00:41:37 +0000739 string for a :class:`.date` object in :ref:`formatted string
740 literals <f-strings>` and when using :meth:`str.format`. For a
David Wolever569a5fa2013-08-12 16:56:02 -0400741 complete list of formatting directives, see
742 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300743
Brad3fb13632019-09-11 05:19:05 -0400744Examples of Usage: :class:`date`
745^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300746
Christian Heimes895627f2007-12-08 17:28:33 +0000747Example of counting days to an event::
748
749 >>> import time
750 >>> from datetime import date
751 >>> today = date.today()
752 >>> today
753 datetime.date(2007, 12, 5)
754 >>> today == date.fromtimestamp(time.time())
755 True
756 >>> my_birthday = date(today.year, 6, 24)
757 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000758 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000759 >>> my_birthday
760 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000761 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000762 >>> time_to_birthday.days
763 202
764
Brad3fb13632019-09-11 05:19:05 -0400765More examples of working with :class:`date`:
Christian Heimesfe337bf2008-03-23 21:54:12 +0000766
767.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000768
769 >>> from datetime import date
770 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
771 >>> d
772 datetime.date(2002, 3, 11)
Brad3fb13632019-09-11 05:19:05 -0400773
774 >>> # Methods related to formatting string output
775 >>> d.isoformat()
776 '2002-03-11'
777 >>> d.strftime("%d/%m/%y")
778 '11/03/02'
779 >>> d.strftime("%A %d. %B %Y")
780 'Monday 11. March 2002'
781 >>> d.ctime()
782 'Mon Mar 11 00:00:00 2002'
783 >>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")
784 'The day is 11, the month is March.'
785
786 >>> # Methods for to extracting 'components' under different calendars
Christian Heimes895627f2007-12-08 17:28:33 +0000787 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000788 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000789 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000790 2002 # year
791 3 # month
792 11 # day
793 0
794 0
795 0
796 0 # weekday (0 = Monday)
797 70 # 70th day in the year
798 -1
799 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000800 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000801 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000802 2002 # ISO year
803 11 # ISO week number
804 1 # ISO day number ( 1 = Monday )
Brad3fb13632019-09-11 05:19:05 -0400805
806 >>> # A date object is immutable; all operations produce a new object
807 >>> d.replace(year=2005)
808 datetime.date(2005, 3, 11)
Christian Heimes895627f2007-12-08 17:28:33 +0000809
Georg Brandl116aa622007-08-15 14:28:22 +0000810
811.. _datetime-datetime:
812
Benjamin Petersond87dd432015-04-25 14:15:16 -0400813:class:`.datetime` Objects
814--------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000815
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300816A :class:`.datetime` object is a single object containing all the information
Brad3fb13632019-09-11 05:19:05 -0400817from a :class:`date` object and a :class:`.time` object.
818
819Like a :class:`date` object, :class:`.datetime` assumes the current Gregorian
820calendar extended in both directions; like a :class:`.time` object,
821:class:`.datetime` assumes there are exactly 3600\*24 seconds in every day.
Georg Brandl116aa622007-08-15 14:28:22 +0000822
823Constructor:
824
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400825.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000826
Brad3fb13632019-09-11 05:19:05 -0400827 The *year*, *month* and *day* arguments are required. *tzinfo* may be ``None``, or an
828 instance of a :class:`tzinfo` subclass. The remaining arguments must be integers
Georg Brandl5c106642007-11-29 17:41:05 +0000829 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000830
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400831 * ``MINYEAR <= year <= MAXYEAR``,
832 * ``1 <= month <= 12``,
833 * ``1 <= day <= number of days in the given month and year``,
834 * ``0 <= hour < 24``,
835 * ``0 <= minute < 60``,
836 * ``0 <= second < 60``,
837 * ``0 <= microsecond < 1000000``,
838 * ``fold in [0, 1]``.
Georg Brandl116aa622007-08-15 14:28:22 +0000839
840 If an argument outside those ranges is given, :exc:`ValueError` is raised.
841
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400842 .. versionadded:: 3.6
843 Added the ``fold`` argument.
844
Georg Brandl116aa622007-08-15 14:28:22 +0000845Other constructors, all class methods:
846
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000847.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000848
Brad3fb13632019-09-11 05:19:05 -0400849 Return the current local datetime, with :attr:`.tzinfo` ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000850
Brad3fb13632019-09-11 05:19:05 -0400851 Equivalent to::
852
853 datetime.fromtimestamp(time.time())
854
855 See also :meth:`now`, :meth:`fromtimestamp`.
856
857 This method is functionally equivalent to :meth:`now`, but without a
858 ``tz`` parameter.
Georg Brandl116aa622007-08-15 14:28:22 +0000859
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000860.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000861
Brad3fb13632019-09-11 05:19:05 -0400862 Return the current local date and time.
863
864 If optional argument *tz* is ``None``
Georg Brandl116aa622007-08-15 14:28:22 +0000865 or not specified, this is like :meth:`today`, but, if possible, supplies more
866 precision than can be gotten from going through a :func:`time.time` timestamp
867 (for example, this may be possible on platforms supplying the C
Georg Brandl60203b42010-10-06 10:11:56 +0000868 :c:func:`gettimeofday` function).
Georg Brandl116aa622007-08-15 14:28:22 +0000869
Joannah Nanjekye1a53c782019-09-11 14:58:42 +0100870 If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` subclass,
871 and the current date and time are converted to *tz*’s time zone.
Brad3fb13632019-09-11 05:19:05 -0400872
Joannah Nanjekye1a53c782019-09-11 14:58:42 +0100873 This function is preferred over :meth:`today` and :meth:`utcnow`.
Georg Brandl116aa622007-08-15 14:28:22 +0000874
875
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000876.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000877
Brad3fb13632019-09-11 05:19:05 -0400878 Return the current UTC date and time, with :attr:`.tzinfo` ``None``.
879
880 This is like :meth:`now`, but returns the current UTC date and time, as a naive
881 :class:`.datetime` object. An aware current UTC datetime can be obtained by
882 calling ``datetime.now(timezone.utc)``. See also :meth:`now`.
Georg Brandl116aa622007-08-15 14:28:22 +0000883
Joannah Nanjekye1a53c782019-09-11 14:58:42 +0100884 .. warning::
885
886 Because naive ``datetime`` objects are treated by many ``datetime`` methods
887 as local times, it is preferred to use aware datetimes to represent times
888 in UTC. As such, the recommended way to create an object representing the
Ofek Lev575d0b42019-12-01 00:44:21 -0500889 current time in UTC is by calling ``datetime.now(timezone.utc)``.
Joannah Nanjekye1a53c782019-09-11 14:58:42 +0100890
891
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000892.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000893
894 Return the local date and time corresponding to the POSIX timestamp, such as is
895 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
896 specified, the timestamp is converted to the platform's local date and time, and
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300897 the returned :class:`.datetime` object is naive.
Georg Brandl116aa622007-08-15 14:28:22 +0000898
Martin Panter16c7cfd2016-04-01 21:48:24 +0000899 If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` subclass, and the
Brad3fb13632019-09-11 05:19:05 -0400900 timestamp is converted to *tz*’s time zone.
901
Victor Stinnerecc6e662012-03-14 00:39:29 +0100902 :meth:`fromtimestamp` may raise :exc:`OverflowError`, if the timestamp is out of
Georg Brandl60203b42010-10-06 10:11:56 +0000903 the range of values supported by the platform C :c:func:`localtime` or
Victor Stinnerecc6e662012-03-14 00:39:29 +0100904 :c:func:`gmtime` functions, and :exc:`OSError` on :c:func:`localtime` or
905 :c:func:`gmtime` failure.
906 It's common for this to be restricted to years in
Georg Brandl116aa622007-08-15 14:28:22 +0000907 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
908 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
909 and then it's possible to have two timestamps differing by a second that yield
Joannah Nanjekye1a53c782019-09-11 14:58:42 +0100910 identical :class:`.datetime` objects. This method is preferred over
911 :meth:`utcfromtimestamp`.
Georg Brandl116aa622007-08-15 14:28:22 +0000912
Victor Stinner5d272cc2012-03-13 13:35:55 +0100913 .. versionchanged:: 3.3
914 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
915 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100916 :c:func:`localtime` or :c:func:`gmtime` functions. Raise :exc:`OSError`
917 instead of :exc:`ValueError` on :c:func:`localtime` or :c:func:`gmtime`
918 failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100919
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400920 .. versionchanged:: 3.6
921 :meth:`fromtimestamp` may return instances with :attr:`.fold` set to 1.
Georg Brandl116aa622007-08-15 14:28:22 +0000922
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000923.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000924
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300925 Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with
Brad3fb13632019-09-11 05:19:05 -0400926 :attr:`.tzinfo` ``None``. (The resulting object is naive.)
927
928 This may raise :exc:`OverflowError`, if the timestamp is
Victor Stinnerecc6e662012-03-14 00:39:29 +0100929 out of the range of values supported by the platform C :c:func:`gmtime` function,
930 and :exc:`OSError` on :c:func:`gmtime` failure.
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500931 It's common for this to be restricted to years in 1970 through 2038.
Georg Brandl116aa622007-08-15 14:28:22 +0000932
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500933 To get an aware :class:`.datetime` object, call :meth:`fromtimestamp`::
Alexander Belopolsky54afa552011-04-25 13:00:40 -0400934
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500935 datetime.fromtimestamp(timestamp, timezone.utc)
936
937 On the POSIX compliant platforms, it is equivalent to the following
938 expression::
939
940 datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)
941
942 except the latter formula always supports the full years range: between
943 :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
Alexander Belopolsky54afa552011-04-25 13:00:40 -0400944
Joannah Nanjekye1a53c782019-09-11 14:58:42 +0100945 .. warning::
946
947 Because naive ``datetime`` objects are treated by many ``datetime`` methods
948 as local times, it is preferred to use aware datetimes to represent times
949 in UTC. As such, the recommended way to create an object representing a
Ofek Lev575d0b42019-12-01 00:44:21 -0500950 specific timestamp in UTC is by calling
Joannah Nanjekye1a53c782019-09-11 14:58:42 +0100951 ``datetime.fromtimestamp(timestamp, tz=timezone.utc)``.
952
Victor Stinner5d272cc2012-03-13 13:35:55 +0100953 .. versionchanged:: 3.3
954 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
955 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100956 :c:func:`gmtime` function. Raise :exc:`OSError` instead of
957 :exc:`ValueError` on :c:func:`gmtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100958
Georg Brandl116aa622007-08-15 14:28:22 +0000959
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000960.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000961
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300962 Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal,
Georg Brandl116aa622007-08-15 14:28:22 +0000963 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
Brad3fb13632019-09-11 05:19:05 -0400964 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
Martin Panter16c7cfd2016-04-01 21:48:24 +0000965 microsecond of the result are all 0, and :attr:`.tzinfo` is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000966
967
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400968.. classmethod:: datetime.combine(date, time, tzinfo=self.tzinfo)
Georg Brandl116aa622007-08-15 14:28:22 +0000969
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300970 Return a new :class:`.datetime` object whose date components are equal to the
Alexander Belopolsky43746c32016-08-02 17:49:30 -0400971 given :class:`date` object's, and whose time components
Brad3fb13632019-09-11 05:19:05 -0400972 are equal to the given :class:`.time` object's. If the *tzinfo*
Alexander Belopolsky43746c32016-08-02 17:49:30 -0400973 argument is provided, its value is used to set the :attr:`.tzinfo` attribute
974 of the result, otherwise the :attr:`~.time.tzinfo` attribute of the *time* argument
975 is used.
976
977 For any :class:`.datetime` object *d*,
Brad3fb13632019-09-11 05:19:05 -0400978 ``d == datetime.combine(d.date(), d.time(), d.tzinfo)``. If date is a
Martin Panter16c7cfd2016-04-01 21:48:24 +0000979 :class:`.datetime` object, its time components and :attr:`.tzinfo` attributes
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800980 are ignored.
Georg Brandl116aa622007-08-15 14:28:22 +0000981
Alexander Belopolsky43746c32016-08-02 17:49:30 -0400982 .. versionchanged:: 3.6
983 Added the *tzinfo* argument.
984
Georg Brandl116aa622007-08-15 14:28:22 +0000985
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500986.. classmethod:: datetime.fromisoformat(date_string)
987
Brad3fb13632019-09-11 05:19:05 -0400988 Return a :class:`.datetime` corresponding to a *date_string* in one of the
989 formats emitted by :meth:`date.isoformat` and :meth:`datetime.isoformat`.
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500990
Brad3fb13632019-09-11 05:19:05 -0400991 Specifically, this function supports strings in the format:
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500992
Brad3fb13632019-09-11 05:19:05 -0400993 .. code-block:: none
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500994
Brad3fb13632019-09-11 05:19:05 -0400995 YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]]
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500996
Brad3fb13632019-09-11 05:19:05 -0400997 where ``*`` can match any single character.
998
999 .. caution::
1000
1001 This does *not* support parsing arbitrary ISO 8601 strings - it is only intended
1002 as the inverse operation of :meth:`datetime.isoformat`. A more full-featured
1003 ISO 8601 parser, ``dateutil.parser.isoparse`` is available in the third-party package
1004 `dateutil <https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.isoparse>`__.
Brad3fb13632019-09-11 05:19:05 -04001005
1006 Examples::
1007
1008 >>> from datetime import datetime
1009 >>> datetime.fromisoformat('2011-11-04')
1010 datetime.datetime(2011, 11, 4, 0, 0)
1011 >>> datetime.fromisoformat('2011-11-04T00:05:23')
1012 datetime.datetime(2011, 11, 4, 0, 5, 23)
1013 >>> datetime.fromisoformat('2011-11-04 00:05:23.283')
1014 datetime.datetime(2011, 11, 4, 0, 5, 23, 283000)
1015 >>> datetime.fromisoformat('2011-11-04 00:05:23.283+00:00')
1016 datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.timezone.utc)
1017 >>> datetime.fromisoformat('2011-11-04T00:05:23+04:00') # doctest: +NORMALIZE_WHITESPACE
1018 datetime.datetime(2011, 11, 4, 0, 5, 23,
1019 tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))
1020
1021 .. versionadded:: 3.7
Paul Ganssle88c09372019-04-29 09:22:03 -04001022
1023.. classmethod:: datetime.fromisocalendar(year, week, day)
1024
Brad3fb13632019-09-11 05:19:05 -04001025 Return a :class:`.datetime` corresponding to the ISO calendar date specified
Paul Ganssle88c09372019-04-29 09:22:03 -04001026 by year, week and day. The non-date components of the datetime are populated
1027 with their normal default values. This is the inverse of the function
1028 :meth:`datetime.isocalendar`.
1029
1030 .. versionadded:: 3.8
1031
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001032.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +00001033
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001034 Return a :class:`.datetime` corresponding to *date_string*, parsed according to
Brad3fb13632019-09-11 05:19:05 -04001035 *format*.
1036
1037 This is equivalent to::
1038
1039 datetime(*(time.strptime(date_string, format)[0:6]))
1040
1041 :exc:`ValueError` is raised if the date_string and format
Georg Brandl116aa622007-08-15 14:28:22 +00001042 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 -04001043 time tuple. For a complete list of formatting directives, see
1044 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001045
Georg Brandl116aa622007-08-15 14:28:22 +00001046
Georg Brandl116aa622007-08-15 14:28:22 +00001047
1048Class attributes:
1049
Georg Brandl116aa622007-08-15 14:28:22 +00001050.. attribute:: datetime.min
1051
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001052 The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1,
Georg Brandl116aa622007-08-15 14:28:22 +00001053 tzinfo=None)``.
1054
1055
1056.. attribute:: datetime.max
1057
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001058 The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
Georg Brandl116aa622007-08-15 14:28:22 +00001059 59, 999999, tzinfo=None)``.
1060
1061
1062.. attribute:: datetime.resolution
1063
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001064 The smallest possible difference between non-equal :class:`.datetime` objects,
Georg Brandl116aa622007-08-15 14:28:22 +00001065 ``timedelta(microseconds=1)``.
1066
Georg Brandl116aa622007-08-15 14:28:22 +00001067
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001068Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001069
1070.. attribute:: datetime.year
1071
1072 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
1073
1074
1075.. attribute:: datetime.month
1076
1077 Between 1 and 12 inclusive.
1078
1079
1080.. attribute:: datetime.day
1081
1082 Between 1 and the number of days in the given month of the given year.
1083
1084
1085.. attribute:: datetime.hour
1086
1087 In ``range(24)``.
1088
1089
1090.. attribute:: datetime.minute
1091
1092 In ``range(60)``.
1093
1094
1095.. attribute:: datetime.second
1096
1097 In ``range(60)``.
1098
1099
1100.. attribute:: datetime.microsecond
1101
1102 In ``range(1000000)``.
1103
1104
1105.. attribute:: datetime.tzinfo
1106
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001107 The object passed as the *tzinfo* argument to the :class:`.datetime` constructor,
Georg Brandl116aa622007-08-15 14:28:22 +00001108 or ``None`` if none was passed.
1109
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001110
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001111.. attribute:: datetime.fold
1112
Brad3fb13632019-09-11 05:19:05 -04001113 In ``[0, 1]``. Used to disambiguate wall times during a repeated interval. (A
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001114 repeated interval occurs when clocks are rolled back at the end of daylight saving
1115 time or when the UTC offset for the current zone is decreased for political reasons.)
1116 The value 0 (1) represents the earlier (later) of the two moments with the same wall
1117 time representation.
1118
1119 .. versionadded:: 3.6
1120
Georg Brandl116aa622007-08-15 14:28:22 +00001121Supported operations:
1122
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001123+---------------------------------------+--------------------------------+
1124| Operation | Result |
1125+=======================================+================================+
1126| ``datetime2 = datetime1 + timedelta`` | \(1) |
1127+---------------------------------------+--------------------------------+
1128| ``datetime2 = datetime1 - timedelta`` | \(2) |
1129+---------------------------------------+--------------------------------+
1130| ``timedelta = datetime1 - datetime2`` | \(3) |
1131+---------------------------------------+--------------------------------+
1132| ``datetime1 < datetime2`` | Compares :class:`.datetime` to |
1133| | :class:`.datetime`. (4) |
1134+---------------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001135
1136(1)
1137 datetime2 is a duration of timedelta removed from datetime1, moving forward in
Brad3fb13632019-09-11 05:19:05 -04001138 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
Martin Panter16c7cfd2016-04-01 21:48:24 +00001139 result has the same :attr:`~.datetime.tzinfo` attribute as the input datetime, and
Senthil Kumarana6bac952011-07-04 11:28:30 -07001140 datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
1141 datetime2.year would be smaller than :const:`MINYEAR` or larger than
1142 :const:`MAXYEAR`. Note that no time zone adjustments are done even if the
1143 input is an aware object.
Georg Brandl116aa622007-08-15 14:28:22 +00001144
1145(2)
1146 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
Martin Panter16c7cfd2016-04-01 21:48:24 +00001147 addition, the result has the same :attr:`~.datetime.tzinfo` attribute as the input
Senthil Kumarana6bac952011-07-04 11:28:30 -07001148 datetime, and no time zone adjustments are done even if the input is aware.
Georg Brandl116aa622007-08-15 14:28:22 +00001149
1150(3)
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001151 Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if
Brad3fb13632019-09-11 05:19:05 -04001152 both operands are naive, or if both are aware. If one is aware and the other is
Georg Brandl116aa622007-08-15 14:28:22 +00001153 naive, :exc:`TypeError` is raised.
1154
Martin Panter16c7cfd2016-04-01 21:48:24 +00001155 If both are naive, or both are aware and have the same :attr:`~.datetime.tzinfo` attribute,
1156 the :attr:`~.datetime.tzinfo` attributes are ignored, and the result is a :class:`timedelta`
Brad3fb13632019-09-11 05:19:05 -04001157 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
Georg Brandl116aa622007-08-15 14:28:22 +00001158 are done in this case.
1159
Martin Panter16c7cfd2016-04-01 21:48:24 +00001160 If both are aware and have different :attr:`~.datetime.tzinfo` attributes, ``a-b`` acts
Brad3fb13632019-09-11 05:19:05 -04001161 as if *a* and *b* were first converted to naive UTC datetimes first. The
Senthil Kumarana6bac952011-07-04 11:28:30 -07001162 result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
1163 - b.utcoffset())`` except that the implementation never overflows.
Georg Brandl116aa622007-08-15 14:28:22 +00001164
1165(4)
1166 *datetime1* is considered less than *datetime2* when *datetime1* precedes
1167 *datetime2* in time.
1168
Alexander Belopolsky08313822012-06-15 20:19:47 -04001169 If one comparand is naive and the other is aware, :exc:`TypeError`
Brad3fb13632019-09-11 05:19:05 -04001170 is raised if an order comparison is attempted. For equality
Alexander Belopolsky08313822012-06-15 20:19:47 -04001171 comparisons, naive instances are never equal to aware instances.
1172
Martin Panter16c7cfd2016-04-01 21:48:24 +00001173 If both comparands are aware, and have the same :attr:`~.datetime.tzinfo` attribute, the
1174 common :attr:`~.datetime.tzinfo` attribute is ignored and the base datetimes are
Brad3fb13632019-09-11 05:19:05 -04001175 compared. If both comparands are aware and have different :attr:`~.datetime.tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -07001176 attributes, the comparands are first adjusted by subtracting their UTC
1177 offsets (obtained from ``self.utcoffset()``).
Georg Brandl116aa622007-08-15 14:28:22 +00001178
Alexander Belopolsky08313822012-06-15 20:19:47 -04001179 .. versionchanged:: 3.3
Brad3fb13632019-09-11 05:19:05 -04001180 Equality comparisons between aware and naive :class:`.datetime`
Éric Araujob0f08952012-06-24 16:22:09 -04001181 instances don't raise :exc:`TypeError`.
Alexander Belopolsky08313822012-06-15 20:19:47 -04001182
Georg Brandl116aa622007-08-15 14:28:22 +00001183 .. note::
1184
1185 In order to stop comparison from falling back to the default scheme of comparing
1186 object addresses, datetime comparison normally raises :exc:`TypeError` if the
Brad3fb13632019-09-11 05:19:05 -04001187 other comparand isn't also a :class:`.datetime` object. However,
Georg Brandl116aa622007-08-15 14:28:22 +00001188 ``NotImplemented`` is returned instead if the other comparand has a
Brad3fb13632019-09-11 05:19:05 -04001189 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
1190 chance at implementing mixed-type comparison. If not, when a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +00001191 object is compared to an object of a different type, :exc:`TypeError` is raised
Brad3fb13632019-09-11 05:19:05 -04001192 unless the comparison is ``==`` or ``!=``. The latter cases return
Georg Brandl116aa622007-08-15 14:28:22 +00001193 :const:`False` or :const:`True`, respectively.
1194
Georg Brandl116aa622007-08-15 14:28:22 +00001195Instance methods:
1196
Georg Brandl116aa622007-08-15 14:28:22 +00001197.. method:: datetime.date()
1198
1199 Return :class:`date` object with same year, month and day.
1200
1201
1202.. method:: datetime.time()
1203
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001204 Return :class:`.time` object with same hour, minute, second, microsecond and fold.
Brad3fb13632019-09-11 05:19:05 -04001205 :attr:`.tzinfo` is ``None``. See also method :meth:`timetz`.
Georg Brandl116aa622007-08-15 14:28:22 +00001206
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001207 .. versionchanged:: 3.6
1208 The fold value is copied to the returned :class:`.time` object.
1209
Georg Brandl116aa622007-08-15 14:28:22 +00001210
1211.. method:: datetime.timetz()
1212
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001213 Return :class:`.time` object with same hour, minute, second, microsecond, fold, and
Brad3fb13632019-09-11 05:19:05 -04001214 tzinfo attributes. See also method :meth:`time`.
Georg Brandl116aa622007-08-15 14:28:22 +00001215
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001216 .. versionchanged:: 3.6
1217 The fold value is copied to the returned :class:`.time` object.
Georg Brandl116aa622007-08-15 14:28:22 +00001218
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001219
1220.. method:: datetime.replace(year=self.year, month=self.month, day=self.day, \
1221 hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, \
1222 tzinfo=self.tzinfo, * fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001223
Senthil Kumarana6bac952011-07-04 11:28:30 -07001224 Return a datetime with the same attributes, except for those attributes given
Brad3fb13632019-09-11 05:19:05 -04001225 new values by whichever keyword arguments are specified. Note that
Senthil Kumarana6bac952011-07-04 11:28:30 -07001226 ``tzinfo=None`` can be specified to create a naive datetime from an aware
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001227 datetime with no conversion of date and time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001228
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001229 .. versionadded:: 3.6
1230 Added the ``fold`` argument.
1231
Georg Brandl116aa622007-08-15 14:28:22 +00001232
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001233.. method:: datetime.astimezone(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001234
Martin Panter16c7cfd2016-04-01 21:48:24 +00001235 Return a :class:`.datetime` object with new :attr:`.tzinfo` attribute *tz*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001236 adjusting the date and time data so the result is the same UTC time as
Senthil Kumarana6bac952011-07-04 11:28:30 -07001237 *self*, but in *tz*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00001238
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001239 If provided, *tz* must be an instance of a :class:`tzinfo` subclass, and its
Brad3fb13632019-09-11 05:19:05 -04001240 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. If *self*
Alexander Belopolsky877b2322018-06-10 17:02:58 -04001241 is naive, it is presumed to represent time in the system timezone.
Georg Brandl116aa622007-08-15 14:28:22 +00001242
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001243 If called without arguments (or with ``tz=None``) the system local
Brad3fb13632019-09-11 05:19:05 -04001244 timezone is assumed for the target timezone. The ``.tzinfo`` attribute of the converted
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001245 datetime instance will be set to an instance of :class:`timezone`
1246 with the zone name and offset obtained from the OS.
1247
Georg Brandl116aa622007-08-15 14:28:22 +00001248 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001249 adjustment of date or time data is performed. Else the result is local
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001250 time in the timezone *tz*, representing the same UTC time as *self*: after
1251 ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will have
1252 the same date and time data as ``dt - dt.utcoffset()``.
Georg Brandl116aa622007-08-15 14:28:22 +00001253
1254 If you merely want to attach a time zone object *tz* to a datetime *dt* without
Brad3fb13632019-09-11 05:19:05 -04001255 adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you
Georg Brandl116aa622007-08-15 14:28:22 +00001256 merely want to remove the time zone object from an aware datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001257 conversion of date and time data, use ``dt.replace(tzinfo=None)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001258
1259 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
1260 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
1261 Ignoring error cases, :meth:`astimezone` acts like::
1262
1263 def astimezone(self, tz):
1264 if self.tzinfo is tz:
1265 return self
1266 # Convert self to UTC, and attach the new time zone object.
1267 utc = (self - self.utcoffset()).replace(tzinfo=tz)
1268 # Convert from UTC to tz's local time.
1269 return tz.fromutc(utc)
1270
Georg Brandlee0be402012-06-26 09:14:40 +02001271 .. versionchanged:: 3.3
1272 *tz* now can be omitted.
1273
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001274 .. versionchanged:: 3.6
1275 The :meth:`astimezone` method can now be called on naive instances that
1276 are presumed to represent system local time.
1277
Georg Brandl116aa622007-08-15 14:28:22 +00001278
1279.. method:: datetime.utcoffset()
1280
Martin Panter16c7cfd2016-04-01 21:48:24 +00001281 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001282 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001283 return ``None`` or a :class:`timedelta` object with magnitude less than one day.
1284
1285 .. versionchanged:: 3.7
1286 The UTC offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001287
1288
1289.. method:: datetime.dst()
1290
Martin Panter16c7cfd2016-04-01 21:48:24 +00001291 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001292 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001293 ``None`` or a :class:`timedelta` object with magnitude less than one day.
1294
1295 .. versionchanged:: 3.7
1296 The DST offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001297
1298
1299.. method:: datetime.tzname()
1300
Martin Panter16c7cfd2016-04-01 21:48:24 +00001301 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001302 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
1303 ``None`` or a string object,
1304
1305
1306.. method:: datetime.timetuple()
1307
1308 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
Brad3fb13632019-09-11 05:19:05 -04001309
1310 ``d.timetuple()`` is equivalent to::
1311
1312 time.struct_time((d.year, d.month, d.day,
1313 d.hour, d.minute, d.second,
1314 d.weekday(), yday, dst))
1315
1316 where ``yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1``
1317 is the day number within the current year starting with ``1`` for January
1318 1st. The :attr:`tm_isdst` flag of the result is set according to the
1319 :meth:`dst` method: :attr:`.tzinfo` is ``None`` or :meth:`dst` returns
1320 ``None``, :attr:`tm_isdst` is set to ``-1``; else if :meth:`dst` returns a
1321 non-zero value, :attr:`tm_isdst` is set to ``1``; else :attr:`tm_isdst` is
1322 set to ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +00001323
1324
1325.. method:: datetime.utctimetuple()
1326
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001327 If :class:`.datetime` instance *d* is naive, this is the same as
Georg Brandl116aa622007-08-15 14:28:22 +00001328 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
Brad3fb13632019-09-11 05:19:05 -04001329 ``d.dst()`` returns. DST is never in effect for a UTC time.
Georg Brandl116aa622007-08-15 14:28:22 +00001330
1331 If *d* is aware, *d* is normalized to UTC time, by subtracting
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00001332 ``d.utcoffset()``, and a :class:`time.struct_time` for the
Brad3fb13632019-09-11 05:19:05 -04001333 normalized time is returned. :attr:`tm_isdst` is forced to 0. Note
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00001334 that an :exc:`OverflowError` may be raised if *d*.year was
1335 ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
Georg Brandl116aa622007-08-15 14:28:22 +00001336 boundary.
1337
Joannah Nanjekye1a53c782019-09-11 14:58:42 +01001338 .. warning::
1339
1340 Because naive ``datetime`` objects are treated by many ``datetime`` methods
1341 as local times, it is preferred to use aware datetimes to represent times
1342 in UTC; as a result, using ``utcfromtimetuple`` may give misleading
1343 results. If you have a naive ``datetime`` representing UTC, use
1344 ``datetime.replace(tzinfo=timezone.utc)`` to make it aware, at which point
1345 you can use :meth:`.datetime.timetuple`.
Georg Brandl116aa622007-08-15 14:28:22 +00001346
1347.. method:: datetime.toordinal()
1348
Brad3fb13632019-09-11 05:19:05 -04001349 Return the proleptic Gregorian ordinal of the date. The same as
Georg Brandl116aa622007-08-15 14:28:22 +00001350 ``self.date().toordinal()``.
1351
Alexander Belopolskya4415142012-06-08 12:33:09 -04001352.. method:: datetime.timestamp()
1353
Martin Panter16c7cfd2016-04-01 21:48:24 +00001354 Return POSIX timestamp corresponding to the :class:`.datetime`
Brad3fb13632019-09-11 05:19:05 -04001355 instance. The return value is a :class:`float` similar to that
Alexander Belopolskya4415142012-06-08 12:33:09 -04001356 returned by :func:`time.time`.
1357
Martin Panter16c7cfd2016-04-01 21:48:24 +00001358 Naive :class:`.datetime` instances are assumed to represent local
Alexander Belopolskya4415142012-06-08 12:33:09 -04001359 time and this method relies on the platform C :c:func:`mktime`
Brad3fb13632019-09-11 05:19:05 -04001360 function to perform the conversion. Since :class:`.datetime`
Alexander Belopolskya4415142012-06-08 12:33:09 -04001361 supports wider range of values than :c:func:`mktime` on many
1362 platforms, this method may raise :exc:`OverflowError` for times far
1363 in the past or far in the future.
1364
Martin Panter16c7cfd2016-04-01 21:48:24 +00001365 For aware :class:`.datetime` instances, the return value is computed
Alexander Belopolskya4415142012-06-08 12:33:09 -04001366 as::
1367
1368 (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
1369
1370 .. versionadded:: 3.3
1371
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001372 .. versionchanged:: 3.6
1373 The :meth:`timestamp` method uses the :attr:`.fold` attribute to
1374 disambiguate the times during a repeated interval.
1375
Alexander Belopolskya4415142012-06-08 12:33:09 -04001376 .. note::
1377
1378 There is no method to obtain the POSIX timestamp directly from a
Brad3fb13632019-09-11 05:19:05 -04001379 naive :class:`.datetime` instance representing UTC time. If your
Alexander Belopolskya4415142012-06-08 12:33:09 -04001380 application uses this convention and your system timezone is not
1381 set to UTC, you can obtain the POSIX timestamp by supplying
1382 ``tzinfo=timezone.utc``::
1383
1384 timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
1385
1386 or by calculating the timestamp directly::
1387
1388 timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001389
1390.. method:: datetime.weekday()
1391
1392 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
1393 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
1394
1395
1396.. method:: datetime.isoweekday()
1397
1398 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
1399 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
1400 :meth:`isocalendar`.
1401
1402
1403.. method:: datetime.isocalendar()
1404
Paul Ganssle1b97b9b2020-05-16 10:02:59 -04001405 Return a :term:`named tuple` with three components: ``year``, ``week``
1406 and ``weekday``. The same as ``self.date().isocalendar()``.
Georg Brandl116aa622007-08-15 14:28:22 +00001407
1408
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001409.. method:: datetime.isoformat(sep='T', timespec='auto')
Georg Brandl116aa622007-08-15 14:28:22 +00001410
Brad3fb13632019-09-11 05:19:05 -04001411 Return a string representing the date and time in ISO 8601 format:
1412
1413 - ``YYYY-MM-DDTHH:MM:SS.ffffff``, if :attr:`microsecond` is not 0
1414 - ``YYYY-MM-DDTHH:MM:SS``, if :attr:`microsecond` is 0
Georg Brandl116aa622007-08-15 14:28:22 +00001415
Christophe Nanteuil92878822018-10-06 00:57:02 +02001416 If :meth:`utcoffset` does not return ``None``, a string is
1417 appended, giving the UTC offset:
Brad3fb13632019-09-11 05:19:05 -04001418
1419 - ``YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]``, if :attr:`microsecond`
1420 is not 0
1421 - ``YYYY-MM-DDTHH:MM:SS+HH:MM[:SS[.ffffff]]``, if :attr:`microsecond` is 0
1422
1423 Examples::
1424
1425 >>> from datetime import datetime, timezone
1426 >>> datetime(2019, 5, 18, 15, 17, 8, 132263).isoformat()
1427 '2019-05-18T15:17:08.132263'
1428 >>> datetime(2019, 5, 18, 15, 17, tzinfo=timezone.utc).isoformat()
1429 '2019-05-18T15:17:00+00:00'
Georg Brandl116aa622007-08-15 14:28:22 +00001430
1431 The optional argument *sep* (default ``'T'``) is a one-character separator,
Brad3fb13632019-09-11 05:19:05 -04001432 placed between the date and time portions of the result. For example::
Georg Brandl116aa622007-08-15 14:28:22 +00001433
1434 >>> from datetime import tzinfo, timedelta, datetime
1435 >>> class TZ(tzinfo):
Brad3fb13632019-09-11 05:19:05 -04001436 ... """A time zone with an arbitrary, constant -06:39 offset."""
1437 ... def utcoffset(self, dt):
1438 ... return timedelta(hours=-6, minutes=-39)
Georg Brandl116aa622007-08-15 14:28:22 +00001439 ...
1440 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1441 '2002-12-25 00:00:00-06:39'
Brad3fb13632019-09-11 05:19:05 -04001442 >>> datetime(2009, 11, 27, microsecond=100, tzinfo=TZ()).isoformat()
1443 '2009-11-27T00:00:00.000100-06:39'
Georg Brandl116aa622007-08-15 14:28:22 +00001444
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001445 The optional argument *timespec* specifies the number of additional
1446 components of the time to include (the default is ``'auto'``).
1447 It can be one of the following:
1448
1449 - ``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0,
1450 same as ``'microseconds'`` otherwise.
Brad3fb13632019-09-11 05:19:05 -04001451 - ``'hours'``: Include the :attr:`hour` in the two-digit ``HH`` format.
1452 - ``'minutes'``: Include :attr:`hour` and :attr:`minute` in ``HH:MM`` format.
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001453 - ``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second`
Brad3fb13632019-09-11 05:19:05 -04001454 in ``HH:MM:SS`` format.
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001455 - ``'milliseconds'``: Include full time, but truncate fractional second
Brad3fb13632019-09-11 05:19:05 -04001456 part to milliseconds. ``HH:MM:SS.sss`` format.
1457 - ``'microseconds'``: Include full time in ``HH:MM:SS.ffffff`` format.
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001458
1459 .. note::
1460
1461 Excluded time components are truncated, not rounded.
1462
Brad3fb13632019-09-11 05:19:05 -04001463 :exc:`ValueError` will be raised on an invalid *timespec* argument::
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001464
1465
1466 >>> from datetime import datetime
Marco Buttu909a6f62017-03-18 17:59:33 +01001467 >>> datetime.now().isoformat(timespec='minutes') # doctest: +SKIP
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001468 '2002-12-25T00:00'
1469 >>> dt = datetime(2015, 1, 1, 12, 30, 59, 0)
1470 >>> dt.isoformat(timespec='microseconds')
1471 '2015-01-01T12:30:59.000000'
1472
1473 .. versionadded:: 3.6
1474 Added the *timespec* argument.
1475
Georg Brandl116aa622007-08-15 14:28:22 +00001476
1477.. method:: datetime.__str__()
1478
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001479 For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to
Georg Brandl116aa622007-08-15 14:28:22 +00001480 ``d.isoformat(' ')``.
1481
1482
1483.. method:: datetime.ctime()
1484
Brad3fb13632019-09-11 05:19:05 -04001485 Return a string representing the date and time::
Georg Brandl116aa622007-08-15 14:28:22 +00001486
Brad3fb13632019-09-11 05:19:05 -04001487 >>> from datetime import datetime
1488 >>> datetime(2002, 12, 4, 20, 30, 40).ctime()
1489 'Wed Dec 4 20:30:40 2002'
1490
1491 The output string will *not* include time zone information, regardless
1492 of whether the input is aware or naive.
1493
1494 ``d.ctime()`` is equivalent to::
1495
1496 time.ctime(time.mktime(d.timetuple()))
1497
1498 on platforms where the native C :c:func:`ctime` function
1499 (which :func:`time.ctime` invokes, but which
1500 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
Georg Brandl116aa622007-08-15 14:28:22 +00001501
1502.. method:: datetime.strftime(format)
1503
1504 Return a string representing the date and time, controlled by an explicit format
Brad3fb13632019-09-11 05:19:05 -04001505 string. For a complete list of formatting directives, see
David Wolever569a5fa2013-08-12 16:56:02 -04001506 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001507
Georg Brandl116aa622007-08-15 14:28:22 +00001508
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001509.. method:: datetime.__format__(format)
1510
Brad3fb13632019-09-11 05:19:05 -04001511 Same as :meth:`.datetime.strftime`. This makes it possible to specify a format
Martin Panterbc1ee462016-02-13 00:41:37 +00001512 string for a :class:`.datetime` object in :ref:`formatted string
Brad3fb13632019-09-11 05:19:05 -04001513 literals <f-strings>` and when using :meth:`str.format`. For a
David Wolever569a5fa2013-08-12 16:56:02 -04001514 complete list of formatting directives, see
1515 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001516
Brad3fb13632019-09-11 05:19:05 -04001517Examples of Usage: :class:`.datetime`
1518^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001519
Brad3fb13632019-09-11 05:19:05 -04001520Examples of working with :class:`~datetime.datetime` objects:
Christian Heimesfe337bf2008-03-23 21:54:12 +00001521
1522.. doctest::
1523
Joannah Nanjekye1a53c782019-09-11 14:58:42 +01001524 >>> from datetime import datetime, date, time, timezone
Brad3fb13632019-09-11 05:19:05 -04001525
Christian Heimes895627f2007-12-08 17:28:33 +00001526 >>> # Using datetime.combine()
1527 >>> d = date(2005, 7, 14)
1528 >>> t = time(12, 30)
1529 >>> datetime.combine(d, t)
1530 datetime.datetime(2005, 7, 14, 12, 30)
Brad3fb13632019-09-11 05:19:05 -04001531
Joannah Nanjekye1a53c782019-09-11 14:58:42 +01001532 >>> # Using datetime.now()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001533 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001534 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Joannah Nanjekye1a53c782019-09-11 14:58:42 +01001535 >>> datetime.now(timezone.utc) # doctest: +SKIP
1536 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060, tzinfo=datetime.timezone.utc)
Brad3fb13632019-09-11 05:19:05 -04001537
Christian Heimes895627f2007-12-08 17:28:33 +00001538 >>> # Using datetime.strptime()
1539 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1540 >>> dt
1541 datetime.datetime(2006, 11, 21, 16, 30)
Brad3fb13632019-09-11 05:19:05 -04001542
Christian Heimes895627f2007-12-08 17:28:33 +00001543 >>> # Using datetime.timetuple() to get tuple of all attributes
1544 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001545 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001546 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001547 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001548 2006 # year
1549 11 # month
1550 21 # day
1551 16 # hour
1552 30 # minute
1553 0 # second
1554 1 # weekday (0 = Monday)
1555 325 # number of days since 1st January
1556 -1 # dst - method tzinfo.dst() returned None
Brad3fb13632019-09-11 05:19:05 -04001557
Christian Heimes895627f2007-12-08 17:28:33 +00001558 >>> # Date in ISO format
1559 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001560 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001561 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001562 ...
1563 2006 # ISO year
1564 47 # ISO week
1565 2 # ISO weekday
Brad3fb13632019-09-11 05:19:05 -04001566
1567 >>> # Formatting a datetime
Christian Heimes895627f2007-12-08 17:28:33 +00001568 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1569 'Tuesday, 21. November 2006 04:30PM'
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001570 >>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
1571 'The day is 21, the month is November, the time is 04:30PM.'
Christian Heimes895627f2007-12-08 17:28:33 +00001572
Brad3fb13632019-09-11 05:19:05 -04001573The example below defines a :class:`tzinfo` subclass capturing time zone
1574information for Kabul, Afghanistan, which used +4 UTC until 1945
1575and then +4:30 UTC thereafter::
Christian Heimes895627f2007-12-08 17:28:33 +00001576
Brad3fb13632019-09-11 05:19:05 -04001577 from datetime import timedelta, datetime, tzinfo, timezone
Georg Brandl48310cd2009-01-03 21:18:54 +00001578
Brad3fb13632019-09-11 05:19:05 -04001579 class KabulTz(tzinfo):
1580 # Kabul used +4 until 1945, when they moved to +4:30
1581 UTC_MOVE_DATE = datetime(1944, 12, 31, 20, tzinfo=timezone.utc)
Christian Heimes895627f2007-12-08 17:28:33 +00001582
Brad3fb13632019-09-11 05:19:05 -04001583 def utcoffset(self, dt):
1584 if dt.year < 1945:
1585 return timedelta(hours=4)
1586 elif (1945, 1, 1, 0, 0) <= dt.timetuple()[:5] < (1945, 1, 1, 0, 30):
1587 # An ambiguous ("imaginary") half-hour range representing
1588 # a 'fold' in time due to the shift from +4 to +4:30.
1589 # If dt falls in the imaginary range, use fold to decide how
1590 # to resolve. See PEP495.
1591 return timedelta(hours=4, minutes=(30 if dt.fold else 0))
1592 else:
1593 return timedelta(hours=4, minutes=30)
1594
1595 def fromutc(self, dt):
1596 # Follow same validations as in datetime.tzinfo
1597 if not isinstance(dt, datetime):
1598 raise TypeError("fromutc() requires a datetime argument")
1599 if dt.tzinfo is not self:
1600 raise ValueError("dt.tzinfo is not self")
1601
1602 # A custom implementation is required for fromutc as
1603 # the input to this function is a datetime with utc values
1604 # but with a tzinfo set to self.
1605 # See datetime.astimezone or fromtimestamp.
1606 if dt.replace(tzinfo=timezone.utc) >= self.UTC_MOVE_DATE:
1607 return dt + timedelta(hours=4, minutes=30)
1608 else:
1609 return dt + timedelta(hours=4)
1610
1611 def dst(self, dt):
1612 # Kabul does not observe daylight saving time.
1613 return timedelta(0)
1614
1615 def tzname(self, dt):
1616 if dt >= self.UTC_MOVE_DATE:
1617 return "+04:30"
1618 return "+04"
1619
1620Usage of ``KabulTz`` from above::
1621
1622 >>> tz1 = KabulTz()
1623
1624 >>> # Datetime before the change
1625 >>> dt1 = datetime(1900, 11, 21, 16, 30, tzinfo=tz1)
1626 >>> print(dt1.utcoffset())
1627 4:00:00
1628
1629 >>> # Datetime after the change
1630 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=tz1)
1631 >>> print(dt2.utcoffset())
1632 4:30:00
1633
1634 >>> # Convert datetime to another time zone
1635 >>> dt3 = dt2.astimezone(timezone.utc)
1636 >>> dt3
1637 datetime.datetime(2006, 6, 14, 8, 30, tzinfo=datetime.timezone.utc)
1638 >>> dt2
1639 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=KabulTz())
Joannah Nanjekye1a53c782019-09-11 14:58:42 +01001640 >>> dt2 == dt3
Brad3fb13632019-09-11 05:19:05 -04001641 True
Georg Brandl116aa622007-08-15 14:28:22 +00001642
1643.. _datetime-time:
1644
Serhiy Storchakaee1b01a2016-12-02 23:13:53 +02001645:class:`.time` Objects
1646----------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001647
Brad3fb13632019-09-11 05:19:05 -04001648A :class:`time` object represents a (local) time of day, independent of any particular
Georg Brandl116aa622007-08-15 14:28:22 +00001649day, and subject to adjustment via a :class:`tzinfo` object.
1650
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001651.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001652
Brad3fb13632019-09-11 05:19:05 -04001653 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
1654 :class:`tzinfo` subclass. The remaining arguments must be integers in the
Georg Brandl116aa622007-08-15 14:28:22 +00001655 following ranges:
1656
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001657 * ``0 <= hour < 24``,
1658 * ``0 <= minute < 60``,
1659 * ``0 <= second < 60``,
1660 * ``0 <= microsecond < 1000000``,
1661 * ``fold in [0, 1]``.
Georg Brandl116aa622007-08-15 14:28:22 +00001662
Brad3fb13632019-09-11 05:19:05 -04001663 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
Georg Brandl116aa622007-08-15 14:28:22 +00001664 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1665
1666Class attributes:
1667
1668
1669.. attribute:: time.min
1670
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001671 The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001672
1673
1674.. attribute:: time.max
1675
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001676 The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001677
1678
1679.. attribute:: time.resolution
1680
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001681 The smallest possible difference between non-equal :class:`.time` objects,
1682 ``timedelta(microseconds=1)``, although note that arithmetic on
1683 :class:`.time` objects is not supported.
Georg Brandl116aa622007-08-15 14:28:22 +00001684
Georg Brandl116aa622007-08-15 14:28:22 +00001685
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001686Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001687
1688.. attribute:: time.hour
1689
1690 In ``range(24)``.
1691
1692
1693.. attribute:: time.minute
1694
1695 In ``range(60)``.
1696
1697
1698.. attribute:: time.second
1699
1700 In ``range(60)``.
1701
1702
1703.. attribute:: time.microsecond
1704
1705 In ``range(1000000)``.
1706
1707
1708.. attribute:: time.tzinfo
1709
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001710 The object passed as the tzinfo argument to the :class:`.time` constructor, or
Georg Brandl116aa622007-08-15 14:28:22 +00001711 ``None`` if none was passed.
1712
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001713
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001714.. attribute:: time.fold
1715
Brad3fb13632019-09-11 05:19:05 -04001716 In ``[0, 1]``. Used to disambiguate wall times during a repeated interval. (A
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001717 repeated interval occurs when clocks are rolled back at the end of daylight saving
1718 time or when the UTC offset for the current zone is decreased for political reasons.)
1719 The value 0 (1) represents the earlier (later) of the two moments with the same wall
1720 time representation.
1721
1722 .. versionadded:: 3.6
1723
Brad3fb13632019-09-11 05:19:05 -04001724:class:`.time` objects support comparison of :class:`.time` to :class:`.time`,
1725where *a* is considered less
1726than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1727is aware, :exc:`TypeError` is raised if an order comparison is attempted. For equality
1728comparisons, naive instances are never equal to aware instances.
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001729
Brad3fb13632019-09-11 05:19:05 -04001730If both comparands are aware, and have
1731the same :attr:`~time.tzinfo` attribute, the common :attr:`~time.tzinfo` attribute is
1732ignored and the base times are compared. If both comparands are aware and
1733have different :attr:`~time.tzinfo` attributes, the comparands are first adjusted by
1734subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
1735to stop mixed-type comparisons from falling back to the default comparison by
1736object address, when a :class:`.time` object is compared to an object of a
1737different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
1738``!=``. The latter cases return :const:`False` or :const:`True`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +00001739
Brad3fb13632019-09-11 05:19:05 -04001740.. versionchanged:: 3.3
1741 Equality comparisons between aware and naive :class:`~datetime.time` instances
1742 don't raise :exc:`TypeError`.
Alexander Belopolsky08313822012-06-15 20:19:47 -04001743
Brad3fb13632019-09-11 05:19:05 -04001744In Boolean contexts, a :class:`.time` object is always considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +00001745
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05001746.. versionchanged:: 3.5
1747 Before Python 3.5, a :class:`.time` object was considered to be false if it
Brad3fb13632019-09-11 05:19:05 -04001748 represented midnight in UTC. This behavior was considered obscure and
1749 error-prone and has been removed in Python 3.5. See :issue:`13936` for full
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05001750 details.
Georg Brandl116aa622007-08-15 14:28:22 +00001751
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001752
1753Other constructor:
1754
1755.. classmethod:: time.fromisoformat(time_string)
1756
Brad3fb13632019-09-11 05:19:05 -04001757 Return a :class:`.time` corresponding to a *time_string* in one of the
1758 formats emitted by :meth:`time.isoformat`. Specifically, this function supports
1759 strings in the format:
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001760
Brad3fb13632019-09-11 05:19:05 -04001761 .. code-block:: none
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001762
Brad3fb13632019-09-11 05:19:05 -04001763 HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001764
Brad3fb13632019-09-11 05:19:05 -04001765 .. caution::
1766
1767 This does *not* support parsing arbitrary ISO 8601 strings. It is only
1768 intended as the inverse operation of :meth:`time.isoformat`.
1769
1770 Examples::
1771
1772 >>> from datetime import time
1773 >>> time.fromisoformat('04:23:01')
1774 datetime.time(4, 23, 1)
1775 >>> time.fromisoformat('04:23:01.000384')
1776 datetime.time(4, 23, 1, 384)
1777 >>> time.fromisoformat('04:23:01+04:00')
1778 datetime.time(4, 23, 1, tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))
1779
1780 .. versionadded:: 3.7
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001781
1782
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001783Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001784
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001785.. method:: time.replace(hour=self.hour, minute=self.minute, second=self.second, \
1786 microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001787
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001788 Return a :class:`.time` with the same value, except for those attributes given
Brad3fb13632019-09-11 05:19:05 -04001789 new values by whichever keyword arguments are specified. Note that
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001790 ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
1791 aware :class:`.time`, without conversion of the time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001792
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001793 .. versionadded:: 3.6
1794 Added the ``fold`` argument.
1795
Georg Brandl116aa622007-08-15 14:28:22 +00001796
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001797.. method:: time.isoformat(timespec='auto')
Georg Brandl116aa622007-08-15 14:28:22 +00001798
Brad3fb13632019-09-11 05:19:05 -04001799 Return a string representing the time in ISO 8601 format, one of:
1800
1801 - ``HH:MM:SS.ffffff``, if :attr:`microsecond` is not 0
1802 - ``HH:MM:SS``, if :attr:`microsecond` is 0
1803 - ``HH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]``, if :meth:`utcoffset` does not return ``None``
1804 - ``HH:MM:SS+HH:MM[:SS[.ffffff]]``, if :attr:`microsecond` is 0 and :meth:`utcoffset` does not return ``None``
Georg Brandl116aa622007-08-15 14:28:22 +00001805
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001806 The optional argument *timespec* specifies the number of additional
1807 components of the time to include (the default is ``'auto'``).
1808 It can be one of the following:
1809
1810 - ``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0,
1811 same as ``'microseconds'`` otherwise.
Brad3fb13632019-09-11 05:19:05 -04001812 - ``'hours'``: Include the :attr:`hour` in the two-digit ``HH`` format.
1813 - ``'minutes'``: Include :attr:`hour` and :attr:`minute` in ``HH:MM`` format.
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001814 - ``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second`
Brad3fb13632019-09-11 05:19:05 -04001815 in ``HH:MM:SS`` format.
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001816 - ``'milliseconds'``: Include full time, but truncate fractional second
Brad3fb13632019-09-11 05:19:05 -04001817 part to milliseconds. ``HH:MM:SS.sss`` format.
1818 - ``'microseconds'``: Include full time in ``HH:MM:SS.ffffff`` format.
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001819
1820 .. note::
1821
1822 Excluded time components are truncated, not rounded.
1823
1824 :exc:`ValueError` will be raised on an invalid *timespec* argument.
1825
Brad3fb13632019-09-11 05:19:05 -04001826 Example::
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001827
1828 >>> from datetime import time
Berker Peksag94f89a62016-06-04 21:36:53 -07001829 >>> time(hour=12, minute=34, second=56, microsecond=123456).isoformat(timespec='minutes')
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001830 '12:34'
Berker Peksag94f89a62016-06-04 21:36:53 -07001831 >>> dt = time(hour=12, minute=34, second=56, microsecond=0)
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001832 >>> dt.isoformat(timespec='microseconds')
1833 '12:34:56.000000'
1834 >>> dt.isoformat(timespec='auto')
1835 '12:34:56'
1836
1837 .. versionadded:: 3.6
1838 Added the *timespec* argument.
1839
Georg Brandl116aa622007-08-15 14:28:22 +00001840
1841.. method:: time.__str__()
1842
1843 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1844
1845
1846.. method:: time.strftime(format)
1847
David Wolever569a5fa2013-08-12 16:56:02 -04001848 Return a string representing the time, controlled by an explicit format
Brad3fb13632019-09-11 05:19:05 -04001849 string. For a complete list of formatting directives, see
David Woleverbbf4a462013-08-12 17:15:36 -04001850 :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001851
1852
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001853.. method:: time.__format__(format)
1854
Martin Panterd5db1472016-02-08 01:34:09 +00001855 Same as :meth:`.time.strftime`. This makes it possible to specify a format string
Martin Panterbc1ee462016-02-13 00:41:37 +00001856 for a :class:`.time` object in :ref:`formatted string
Brad3fb13632019-09-11 05:19:05 -04001857 literals <f-strings>` and when using :meth:`str.format`. For a
David Wolever569a5fa2013-08-12 16:56:02 -04001858 complete list of formatting directives, see
1859 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001860
1861
Georg Brandl116aa622007-08-15 14:28:22 +00001862.. method:: time.utcoffset()
1863
Martin Panter16c7cfd2016-04-01 21:48:24 +00001864 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001865 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001866 return ``None`` or a :class:`timedelta` object with magnitude less than one day.
1867
1868 .. versionchanged:: 3.7
1869 The UTC offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001870
1871
1872.. method:: time.dst()
1873
Martin Panter16c7cfd2016-04-01 21:48:24 +00001874 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001875 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001876 ``None``, or a :class:`timedelta` object with magnitude less than one day.
Georg Brandl116aa622007-08-15 14:28:22 +00001877
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001878 .. versionchanged:: 3.7
1879 The DST offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001880
1881.. method:: time.tzname()
1882
Martin Panter16c7cfd2016-04-01 21:48:24 +00001883 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001884 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1885 return ``None`` or a string object.
1886
Brad3fb13632019-09-11 05:19:05 -04001887Examples of Usage: :class:`.time`
1888^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1889
1890Examples of working with a :class:`.time` object::
Georg Brandl48310cd2009-01-03 21:18:54 +00001891
Xiang Zhang6721c7c2016-12-27 12:23:59 +08001892 >>> from datetime import time, tzinfo, timedelta
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001893 >>> class TZ1(tzinfo):
Christian Heimes895627f2007-12-08 17:28:33 +00001894 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001895 ... return timedelta(hours=1)
1896 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001897 ... return timedelta(0)
1898 ... def tzname(self,dt):
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001899 ... return "+01:00"
1900 ... def __repr__(self):
1901 ... return f"{self.__class__.__name__}()"
Christian Heimes895627f2007-12-08 17:28:33 +00001902 ...
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001903 >>> t = time(12, 10, 30, tzinfo=TZ1())
1904 >>> t
1905 datetime.time(12, 10, 30, tzinfo=TZ1())
Christian Heimes895627f2007-12-08 17:28:33 +00001906 >>> t.isoformat()
1907 '12:10:30+01:00'
1908 >>> t.dst()
1909 datetime.timedelta(0)
1910 >>> t.tzname()
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001911 '+01:00'
Christian Heimes895627f2007-12-08 17:28:33 +00001912 >>> t.strftime("%H:%M:%S %Z")
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001913 '12:10:30 +01:00'
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001914 >>> 'The {} is {:%H:%M}.'.format("time", t)
1915 'The time is 12:10.'
Christian Heimes895627f2007-12-08 17:28:33 +00001916
Georg Brandl116aa622007-08-15 14:28:22 +00001917
1918.. _datetime-tzinfo:
1919
1920:class:`tzinfo` Objects
1921-----------------------
1922
Martin Panter16c7cfd2016-04-01 21:48:24 +00001923.. class:: tzinfo()
Georg Brandl116aa622007-08-15 14:28:22 +00001924
Martin Panter16c7cfd2016-04-01 21:48:24 +00001925 This is an abstract base class, meaning that this class should not be
Brad3fb13632019-09-11 05:19:05 -04001926 instantiated directly. Define a subclass of :class:`tzinfo` to capture
1927 information about a particular time zone.
Georg Brandl116aa622007-08-15 14:28:22 +00001928
Martin Panter16c7cfd2016-04-01 21:48:24 +00001929 An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1930 constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
1931 view their attributes as being in local time, and the :class:`tzinfo` object
1932 supports methods revealing offset of local time from UTC, the name of the time
1933 zone, and DST offset, all relative to a date or time object passed to them.
Georg Brandl116aa622007-08-15 14:28:22 +00001934
Brad3fb13632019-09-11 05:19:05 -04001935 You need to derive a concrete subclass, and (at least)
1936 supply implementations of the standard :class:`tzinfo` methods needed by the
1937 :class:`.datetime` methods you use. The :mod:`datetime` module provides
1938 :class:`timezone`, a simple concrete subclass of :class:`tzinfo` which can
1939 represent timezones with fixed offset from UTC such as UTC itself or North
1940 American EST and EDT.
1941
Martin Panter16c7cfd2016-04-01 21:48:24 +00001942 Special requirement for pickling: A :class:`tzinfo` subclass must have an
Brad3fb13632019-09-11 05:19:05 -04001943 :meth:`__init__` method that can be called with no arguments, otherwise it can be
1944 pickled but possibly not unpickled again. This is a technical requirement that
Martin Panter16c7cfd2016-04-01 21:48:24 +00001945 may be relaxed in the future.
1946
1947 A concrete subclass of :class:`tzinfo` may need to implement the following
Brad3fb13632019-09-11 05:19:05 -04001948 methods. Exactly which methods are needed depends on the uses made of aware
1949 :mod:`datetime` objects. If in doubt, simply implement all of them.
Georg Brandl116aa622007-08-15 14:28:22 +00001950
1951
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001952.. method:: tzinfo.utcoffset(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001953
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001954 Return offset of local time from UTC, as a :class:`timedelta` object that is
Brad3fb13632019-09-11 05:19:05 -04001955 positive east of UTC. If local time is west of UTC, this should be negative.
1956
1957 This represents the *total* offset from UTC; for example, if a
1958 :class:`tzinfo` object represents both time zone and DST adjustments,
1959 :meth:`utcoffset` should return their sum. If the UTC offset isn't known,
1960 return ``None``. Else the value returned must be a :class:`timedelta` object
1961 strictly between ``-timedelta(hours=24)`` and ``timedelta(hours=24)``
1962 (the magnitude of the offset must be less than one day). Most implementations
1963 of :meth:`utcoffset` will probably look like one of these two::
Georg Brandl116aa622007-08-15 14:28:22 +00001964
1965 return CONSTANT # fixed-offset class
1966 return CONSTANT + self.dst(dt) # daylight-aware class
1967
1968 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1969 ``None`` either.
1970
1971 The default implementation of :meth:`utcoffset` raises
1972 :exc:`NotImplementedError`.
1973
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001974 .. versionchanged:: 3.7
1975 The UTC offset is not restricted to a whole number of minutes.
1976
Georg Brandl116aa622007-08-15 14:28:22 +00001977
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001978.. method:: tzinfo.dst(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001979
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001980 Return the daylight saving time (DST) adjustment, as a :class:`timedelta`
1981 object or
Brad3fb13632019-09-11 05:19:05 -04001982 ``None`` if DST information isn't known.
1983
1984 Return ``timedelta(0)`` if DST is not in effect.
1985 If DST is in effect, return the offset as a :class:`timedelta` object
Georg Brandl116aa622007-08-15 14:28:22 +00001986 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1987 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1988 no need to consult :meth:`dst` unless you're interested in obtaining DST info
Brad3fb13632019-09-11 05:19:05 -04001989 separately. For example, :meth:`datetime.timetuple` calls its :attr:`~.datetime.tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -07001990 attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
1991 should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
1992 DST changes when crossing time zones.
Georg Brandl116aa622007-08-15 14:28:22 +00001993
1994 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1995 daylight times must be consistent in this sense:
1996
1997 ``tz.utcoffset(dt) - tz.dst(dt)``
1998
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001999 must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo ==
Georg Brandl116aa622007-08-15 14:28:22 +00002000 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
2001 zone's "standard offset", which should not depend on the date or the time, but
Brad3fb13632019-09-11 05:19:05 -04002002 only on geographic location. The implementation of :meth:`datetime.astimezone`
Georg Brandl116aa622007-08-15 14:28:22 +00002003 relies on this, but cannot detect violations; it's the programmer's
Brad3fb13632019-09-11 05:19:05 -04002004 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
Georg Brandl116aa622007-08-15 14:28:22 +00002005 this, it may be able to override the default implementation of
2006 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
2007
2008 Most implementations of :meth:`dst` will probably look like one of these two::
2009
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01002010 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00002011 # a fixed-offset class: doesn't account for DST
2012 return timedelta(0)
2013
Brad3fb13632019-09-11 05:19:05 -04002014 or::
Georg Brandl116aa622007-08-15 14:28:22 +00002015
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01002016 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00002017 # Code to set dston and dstoff to the time zone's DST
2018 # transition times based on the input dt.year, and expressed
Brad3fb13632019-09-11 05:19:05 -04002019 # in standard local time.
Georg Brandl116aa622007-08-15 14:28:22 +00002020
2021 if dston <= dt.replace(tzinfo=None) < dstoff:
2022 return timedelta(hours=1)
2023 else:
2024 return timedelta(0)
2025
2026 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
2027
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002028 .. versionchanged:: 3.7
2029 The DST offset is not restricted to a whole number of minutes.
2030
Georg Brandl116aa622007-08-15 14:28:22 +00002031
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002032.. method:: tzinfo.tzname(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00002033
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002034 Return the time zone name corresponding to the :class:`.datetime` object *dt*, as
Georg Brandl116aa622007-08-15 14:28:22 +00002035 a string. Nothing about string names is defined by the :mod:`datetime` module,
Brad3fb13632019-09-11 05:19:05 -04002036 and there's no requirement that it mean anything in particular. For example,
Georg Brandl116aa622007-08-15 14:28:22 +00002037 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
Brad3fb13632019-09-11 05:19:05 -04002038 valid replies. Return ``None`` if a string name isn't known. Note that this is
Georg Brandl116aa622007-08-15 14:28:22 +00002039 a method rather than a fixed string primarily because some :class:`tzinfo`
2040 subclasses will wish to return different names depending on the specific value
2041 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
2042 daylight time.
2043
2044 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
2045
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002046
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002047These methods are called by a :class:`.datetime` or :class:`.time` object, in
Brad3fb13632019-09-11 05:19:05 -04002048response to their methods of the same names. A :class:`.datetime` object passes
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002049itself as the argument, and a :class:`.time` object passes ``None`` as the
Brad3fb13632019-09-11 05:19:05 -04002050argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002051accept a *dt* argument of ``None``, or of class :class:`.datetime`.
Georg Brandl116aa622007-08-15 14:28:22 +00002052
2053When ``None`` is passed, it's up to the class designer to decide the best
Brad3fb13632019-09-11 05:19:05 -04002054response. For example, returning ``None`` is appropriate if the class wishes to
2055say that time objects don't participate in the :class:`tzinfo` protocols. It
Georg Brandl116aa622007-08-15 14:28:22 +00002056may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
2057there is no other convention for discovering the standard offset.
2058
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002059When a :class:`.datetime` object is passed in response to a :class:`.datetime`
Brad3fb13632019-09-11 05:19:05 -04002060method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
2061rely on this, unless user code calls :class:`tzinfo` methods directly. The
Georg Brandl116aa622007-08-15 14:28:22 +00002062intent is that the :class:`tzinfo` methods interpret *dt* as being in local
2063time, and not need worry about objects in other timezones.
2064
2065There is one more :class:`tzinfo` method that a subclass may wish to override:
2066
2067
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002068.. method:: tzinfo.fromutc(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00002069
Senthil Kumaran023c6f72011-07-17 19:01:14 +08002070 This is called from the default :class:`datetime.astimezone()`
Brad3fb13632019-09-11 05:19:05 -04002071 implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s
2072 date and time data are to be viewed as expressing a UTC time. The purpose
Senthil Kumaran023c6f72011-07-17 19:01:14 +08002073 of :meth:`fromutc` is to adjust the date and time data, returning an
Senthil Kumarana6bac952011-07-04 11:28:30 -07002074 equivalent datetime in *self*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00002075
2076 Most :class:`tzinfo` subclasses should be able to inherit the default
Brad3fb13632019-09-11 05:19:05 -04002077 :meth:`fromutc` implementation without problems. It's strong enough to handle
Georg Brandl116aa622007-08-15 14:28:22 +00002078 fixed-offset time zones, and time zones accounting for both standard and
2079 daylight time, and the latter even if the DST transition times differ in
Brad3fb13632019-09-11 05:19:05 -04002080 different years. An example of a time zone the default :meth:`fromutc`
Georg Brandl116aa622007-08-15 14:28:22 +00002081 implementation may not handle correctly in all cases is one where the standard
2082 offset (from UTC) depends on the specific date and time passed, which can happen
2083 for political reasons. The default implementations of :meth:`astimezone` and
2084 :meth:`fromutc` may not produce the result you want if the result is one of the
2085 hours straddling the moment the standard offset changes.
2086
2087 Skipping code for error cases, the default :meth:`fromutc` implementation acts
2088 like::
2089
2090 def fromutc(self, dt):
2091 # raise ValueError error if dt.tzinfo is not self
2092 dtoff = dt.utcoffset()
2093 dtdst = dt.dst()
2094 # raise ValueError if dtoff is None or dtdst is None
2095 delta = dtoff - dtdst # this is self's standard offset
2096 if delta:
2097 dt += delta # convert to standard local time
2098 dtdst = dt.dst()
2099 # raise ValueError if dtdst is None
2100 if dtdst:
2101 return dt + dtdst
2102 else:
2103 return dt
2104
Marco Buttu909a6f62017-03-18 17:59:33 +01002105In the following :download:`tzinfo_examples.py
2106<../includes/tzinfo_examples.py>` file there are some examples of
2107:class:`tzinfo` classes:
Georg Brandl116aa622007-08-15 14:28:22 +00002108
Marco Buttu909a6f62017-03-18 17:59:33 +01002109.. literalinclude:: ../includes/tzinfo_examples.py
Georg Brandl116aa622007-08-15 14:28:22 +00002110
Georg Brandl116aa622007-08-15 14:28:22 +00002111Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
2112subclass accounting for both standard and daylight time, at the DST transition
Brad3fb13632019-09-11 05:19:05 -04002113points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00002114minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
21151:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00002116
2117 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
2118 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
2119 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
2120
2121 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
2122
2123 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
2124
2125When DST starts (the "start" line), the local wall clock leaps from 1:59 to
Brad3fb13632019-09-11 05:19:05 -040021263: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 +00002127``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
Brad3fb13632019-09-11 05:19:05 -04002128begins. For example, at the Spring forward transition of 2016, we get::
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04002129
Marco Buttu909a6f62017-03-18 17:59:33 +01002130 >>> from datetime import datetime, timezone
2131 >>> from tzinfo_examples import HOUR, Eastern
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04002132 >>> u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc)
2133 >>> for i in range(4):
2134 ... u = u0 + i*HOUR
2135 ... t = u.astimezone(Eastern)
2136 ... print(u.time(), 'UTC =', t.time(), t.tzname())
2137 ...
2138 05:00:00 UTC = 00:00:00 EST
2139 06:00:00 UTC = 01:00:00 EST
2140 07:00:00 UTC = 03:00:00 EDT
2141 08:00:00 UTC = 04:00:00 EDT
2142
Georg Brandl116aa622007-08-15 14:28:22 +00002143
2144When DST ends (the "end" line), there's a potentially worse problem: there's an
2145hour that can't be spelled unambiguously in local wall time: the last hour of
Brad3fb13632019-09-11 05:19:05 -04002146daylight time. In Eastern, that's times of the form 5:MM UTC on the day
2147daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
Georg Brandl116aa622007-08-15 14:28:22 +00002148to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
2149:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
Brad3fb13632019-09-11 05:19:05 -04002150hours into the same local hour then. In the Eastern example, UTC times of the
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04002151form 5:MM and 6:MM both map to 1:MM when converted to Eastern, but earlier times
2152have the :attr:`~datetime.fold` attribute set to 0 and the later times have it set to 1.
Brad3fb13632019-09-11 05:19:05 -04002153For example, at the Fall back transition of 2016, we get::
Georg Brandl116aa622007-08-15 14:28:22 +00002154
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04002155 >>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
2156 >>> for i in range(4):
2157 ... u = u0 + i*HOUR
2158 ... t = u.astimezone(Eastern)
2159 ... print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
2160 ...
2161 04:00:00 UTC = 00:00:00 EDT 0
2162 05:00:00 UTC = 01:00:00 EDT 0
2163 06:00:00 UTC = 01:00:00 EST 1
2164 07:00:00 UTC = 02:00:00 EST 0
2165
Brad3fb13632019-09-11 05:19:05 -04002166Note that the :class:`.datetime` instances that differ only by the value of the
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04002167:attr:`~datetime.fold` attribute are considered equal in comparisons.
2168
2169Applications that can't bear wall-time ambiguities should explicitly check the
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07002170value of the :attr:`~datetime.fold` attribute or avoid using hybrid
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002171:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`,
2172or any other fixed-offset :class:`tzinfo` subclass (such as a class representing
2173only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
2174
Sandro Tosid11d0d62012-04-24 19:46:06 +02002175.. seealso::
2176
wim glenn53f2af12017-06-06 12:54:41 -05002177 `dateutil.tz <https://dateutil.readthedocs.io/en/stable/tz.html>`_
Brad3fb13632019-09-11 05:19:05 -04002178 The :mod:`datetime` module has a basic :class:`timezone` class (for
2179 handling arbitrary fixed offsets from UTC) and its :attr:`timezone.utc`
2180 attribute (a UTC timezone instance).
Sandro Tosid11d0d62012-04-24 19:46:06 +02002181
Brad3fb13632019-09-11 05:19:05 -04002182 *dateutil.tz* library brings the *IANA timezone database*
2183 (also known as the Olson database) to Python, and its usage is
2184 recommended.
Sandro Tosi100b8892012-04-28 11:19:37 +02002185
Serhiy Storchaka6dff0202016-05-07 10:49:07 +03002186 `IANA timezone database <https://www.iana.org/time-zones>`_
Brad3fb13632019-09-11 05:19:05 -04002187 The Time Zone Database (often called tz, tzdata or zoneinfo) contains code
2188 and data that represent the history of local time for many representative
Sandro Tosi100b8892012-04-28 11:19:37 +02002189 locations around the globe. It is updated periodically to reflect changes
2190 made by political bodies to time zone boundaries, UTC offsets, and
2191 daylight-saving rules.
Sandro Tosid11d0d62012-04-24 19:46:06 +02002192
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002193
2194.. _datetime-timezone:
2195
2196:class:`timezone` Objects
2197--------------------------
2198
Alexander Belopolsky6d3c9a62011-05-04 10:28:26 -04002199The :class:`timezone` class is a subclass of :class:`tzinfo`, each
2200instance of which represents a timezone defined by a fixed offset from
Brad3fb13632019-09-11 05:19:05 -04002201UTC.
2202
2203Objects of this class cannot be used to represent timezone information in the
2204locations where different offsets are used in different days of the year or
2205where historical changes have been made to civil time.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002206
2207
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04002208.. class:: timezone(offset, name=None)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002209
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002210 The *offset* argument must be specified as a :class:`timedelta`
Brad3fb13632019-09-11 05:19:05 -04002211 object representing the difference between the local time and UTC. It must
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002212 be strictly between ``-timedelta(hours=24)`` and
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002213 ``timedelta(hours=24)``, otherwise :exc:`ValueError` is raised.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002214
Brad3fb13632019-09-11 05:19:05 -04002215 The *name* argument is optional. If specified it must be a string that
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04002216 will be used as the value returned by the :meth:`datetime.tzname` method.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002217
Benjamin Peterson9b29acd2014-06-22 16:26:39 -07002218 .. versionadded:: 3.2
2219
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002220 .. versionchanged:: 3.7
2221 The UTC offset is not restricted to a whole number of minutes.
2222
2223
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002224.. method:: timezone.utcoffset(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002225
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002226 Return the fixed value specified when the :class:`timezone` instance is
Brad3fb13632019-09-11 05:19:05 -04002227 constructed.
2228
2229 The *dt* argument is ignored. The return value is a :class:`timedelta`
2230 instance equal to the difference between the local time and UTC.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002231
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002232 .. versionchanged:: 3.7
2233 The UTC offset is not restricted to a whole number of minutes.
2234
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002235.. method:: timezone.tzname(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002236
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04002237 Return the fixed value specified when the :class:`timezone` instance
Brad3fb13632019-09-11 05:19:05 -04002238 is constructed.
2239
2240 If *name* is not provided in the constructor, the name returned by
2241 ``tzname(dt)`` is generated from the value of the ``offset`` as follows. If
2242 *offset* is ``timedelta(0)``, the name is "UTC", otherwise it is a string in
2243 the format ``UTC±HH:MM``, where ± is the sign of ``offset``, HH and MM are
2244 two digits of ``offset.hours`` and ``offset.minutes`` respectively.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002245
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04002246 .. versionchanged:: 3.6
Brad3fb13632019-09-11 05:19:05 -04002247 Name generated from ``offset=timedelta(0)`` is now plain `'UTC'`, not
2248 ``'UTC+00:00'``.
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04002249
2250
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002251.. method:: timezone.dst(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002252
2253 Always returns ``None``.
2254
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002255.. method:: timezone.fromutc(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002256
Brad3fb13632019-09-11 05:19:05 -04002257 Return ``dt + offset``. The *dt* argument must be an aware
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002258 :class:`.datetime` instance, with ``tzinfo`` set to ``self``.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002259
2260Class attributes:
2261
2262.. attribute:: timezone.utc
2263
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002264 The UTC timezone, ``timezone(timedelta(0))``.
Georg Brandl48310cd2009-01-03 21:18:54 +00002265
Georg Brandl116aa622007-08-15 14:28:22 +00002266
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03002267.. index::
Serhiy Storchaka913876d2018-10-28 13:41:26 +02002268 single: % (percent); datetime format
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03002269
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002270.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00002271
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002272:meth:`strftime` and :meth:`strptime` Behavior
2273----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00002274
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002275:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
Georg Brandl116aa622007-08-15 14:28:22 +00002276``strftime(format)`` method, to create a string representing the time under the
Brad3fb13632019-09-11 05:19:05 -04002277control of an explicit format string.
Georg Brandl116aa622007-08-15 14:28:22 +00002278
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002279Conversely, the :meth:`datetime.strptime` class method creates a
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002280:class:`.datetime` object from a string representing a date and time and a
Brad3fb13632019-09-11 05:19:05 -04002281corresponding format string.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002282
Brad3fb13632019-09-11 05:19:05 -04002283The table below provides a high-level comparison of :meth:`strftime`
2284versus :meth:`strptime`:
Georg Brandl116aa622007-08-15 14:28:22 +00002285
Brad3fb13632019-09-11 05:19:05 -04002286+----------------+--------------------------------------------------------+------------------------------------------------------------------------------+
2287| | ``strftime`` | ``strptime`` |
2288+================+========================================================+==============================================================================+
2289| Usage | Convert object to a string according to a given format | Parse a string into a :class:`.datetime` object given a corresponding format |
2290+----------------+--------------------------------------------------------+------------------------------------------------------------------------------+
2291| Type of method | Instance method | Class method |
2292+----------------+--------------------------------------------------------+------------------------------------------------------------------------------+
2293| Method of | :class:`date`; :class:`.datetime`; :class:`.time` | :class:`.datetime` |
2294+----------------+--------------------------------------------------------+------------------------------------------------------------------------------+
2295| Signature | ``strftime(format)`` | ``strptime(date_string, format)`` |
2296+----------------+--------------------------------------------------------+------------------------------------------------------------------------------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002297
Abhishek Kumar Singh56027cc2019-05-19 02:06:19 +05302298
Brad3fb13632019-09-11 05:19:05 -04002299:meth:`strftime` and :meth:`strptime` Format Codes
2300^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Christian Heimes895627f2007-12-08 17:28:33 +00002301
Brad3fb13632019-09-11 05:19:05 -04002302The following is a list of all the format codes that the 1989 C standard
2303requires, and these work on all platforms with a standard C implementation.
Georg Brandl116aa622007-08-15 14:28:22 +00002304
David Wolever569a5fa2013-08-12 16:56:02 -04002305+-----------+--------------------------------+------------------------+-------+
2306| Directive | Meaning | Example | Notes |
2307+===========+================================+========================+=======+
2308| ``%a`` | Weekday as locale's || Sun, Mon, ..., Sat | \(1) |
2309| | abbreviated name. | (en_US); | |
2310| | || So, Mo, ..., Sa | |
2311| | | (de_DE) | |
2312+-----------+--------------------------------+------------------------+-------+
2313| ``%A`` | Weekday as locale's full name. || Sunday, Monday, ..., | \(1) |
2314| | | Saturday (en_US); | |
2315| | || Sonntag, Montag, ..., | |
2316| | | Samstag (de_DE) | |
2317+-----------+--------------------------------+------------------------+-------+
2318| ``%w`` | Weekday as a decimal number, | 0, 1, ..., 6 | |
2319| | where 0 is Sunday and 6 is | | |
2320| | Saturday. | | |
2321+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002322| ``%d`` | Day of the month as a | 01, 02, ..., 31 | \(9) |
David Wolever569a5fa2013-08-12 16:56:02 -04002323| | zero-padded decimal number. | | |
2324+-----------+--------------------------------+------------------------+-------+
2325| ``%b`` | Month as locale's abbreviated || Jan, Feb, ..., Dec | \(1) |
2326| | name. | (en_US); | |
2327| | || Jan, Feb, ..., Dez | |
2328| | | (de_DE) | |
2329+-----------+--------------------------------+------------------------+-------+
2330| ``%B`` | Month as locale's full name. || January, February, | \(1) |
2331| | | ..., December (en_US);| |
2332| | || Januar, Februar, ..., | |
2333| | | Dezember (de_DE) | |
2334+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002335| ``%m`` | Month as a zero-padded | 01, 02, ..., 12 | \(9) |
David Wolever569a5fa2013-08-12 16:56:02 -04002336| | decimal number. | | |
2337+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002338| ``%y`` | Year without century as a | 00, 01, ..., 99 | \(9) |
David Wolever569a5fa2013-08-12 16:56:02 -04002339| | zero-padded decimal number. | | |
2340+-----------+--------------------------------+------------------------+-------+
2341| ``%Y`` | Year with century as a decimal | 0001, 0002, ..., 2013, | \(2) |
David Wolever5d07e702013-08-14 14:41:48 -04002342| | number. | 2014, ..., 9998, 9999 | |
David Wolever569a5fa2013-08-12 16:56:02 -04002343+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002344| ``%H`` | Hour (24-hour clock) as a | 00, 01, ..., 23 | \(9) |
David Wolever569a5fa2013-08-12 16:56:02 -04002345| | zero-padded decimal number. | | |
2346+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002347| ``%I`` | Hour (12-hour clock) as a | 01, 02, ..., 12 | \(9) |
David Wolever569a5fa2013-08-12 16:56:02 -04002348| | zero-padded decimal number. | | |
2349+-----------+--------------------------------+------------------------+-------+
2350| ``%p`` | Locale's equivalent of either || AM, PM (en_US); | \(1), |
2351| | AM or PM. || am, pm (de_DE) | \(3) |
2352+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002353| ``%M`` | Minute as a zero-padded | 00, 01, ..., 59 | \(9) |
David Wolever569a5fa2013-08-12 16:56:02 -04002354| | decimal number. | | |
2355+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002356| ``%S`` | Second as a zero-padded | 00, 01, ..., 59 | \(4), |
2357| | decimal number. | | \(9) |
David Wolever569a5fa2013-08-12 16:56:02 -04002358+-----------+--------------------------------+------------------------+-------+
2359| ``%f`` | Microsecond as a decimal | 000000, 000001, ..., | \(5) |
2360| | number, zero-padded on the | 999999 | |
2361| | left. | | |
2362+-----------+--------------------------------+------------------------+-------+
Christophe Nanteuil92878822018-10-06 00:57:02 +02002363| ``%z`` | UTC offset in the form | (empty), +0000, | \(6) |
Brad3fb13632019-09-11 05:19:05 -04002364| | ``±HHMM[SS[.ffffff]]`` (empty | -0400, +1030, | |
Christophe Nanteuil92878822018-10-06 00:57:02 +02002365| | string if the object is | +063415, | |
2366| | naive). | -030712.345216 | |
David Wolever569a5fa2013-08-12 16:56:02 -04002367+-----------+--------------------------------+------------------------+-------+
Karl Dubostbc441ed2019-11-27 01:38:41 +09002368| ``%Z`` | Time zone name (empty string | (empty), UTC, GMT | \(6) |
David Wolever569a5fa2013-08-12 16:56:02 -04002369| | if the object is naive). | | |
2370+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002371| ``%j`` | Day of the year as a | 001, 002, ..., 366 | \(9) |
David Wolever569a5fa2013-08-12 16:56:02 -04002372| | zero-padded decimal number. | | |
2373+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002374| ``%U`` | Week number of the year | 00, 01, ..., 53 | \(7), |
2375| | (Sunday as the first day of | | \(9) |
David Wolever569a5fa2013-08-12 16:56:02 -04002376| | the week) as a zero padded | | |
2377| | decimal number. All days in a | | |
2378| | new year preceding the first | | |
2379| | Sunday are considered to be in | | |
2380| | week 0. | | |
2381+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002382| ``%W`` | Week number of the year | 00, 01, ..., 53 | \(7), |
2383| | (Monday as the first day of | | \(9) |
David Wolever569a5fa2013-08-12 16:56:02 -04002384| | the week) as a decimal number. | | |
2385| | All days in a new year | | |
2386| | preceding the first Monday | | |
2387| | are considered to be in | | |
2388| | week 0. | | |
2389+-----------+--------------------------------+------------------------+-------+
2390| ``%c`` | Locale's appropriate date and || Tue Aug 16 21:30:00 | \(1) |
2391| | time representation. | 1988 (en_US); | |
2392| | || Di 16 Aug 21:30:00 | |
2393| | | 1988 (de_DE) | |
2394+-----------+--------------------------------+------------------------+-------+
2395| ``%x`` | Locale's appropriate date || 08/16/88 (None); | \(1) |
2396| | representation. || 08/16/1988 (en_US); | |
2397| | || 16.08.1988 (de_DE) | |
2398+-----------+--------------------------------+------------------------+-------+
2399| ``%X`` | Locale's appropriate time || 21:30:00 (en_US); | \(1) |
2400| | representation. || 21:30:00 (de_DE) | |
2401+-----------+--------------------------------+------------------------+-------+
2402| ``%%`` | A literal ``'%'`` character. | % | |
2403+-----------+--------------------------------+------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00002404
Alexander Belopolsky68713e42015-10-06 13:29:56 -04002405Several additional directives not required by the C89 standard are included for
Brad3fb13632019-09-11 05:19:05 -04002406convenience. These parameters all correspond to ISO 8601 date values.
Alexander Belopolsky68713e42015-10-06 13:29:56 -04002407
2408+-----------+--------------------------------+------------------------+-------+
2409| Directive | Meaning | Example | Notes |
2410+===========+================================+========================+=======+
2411| ``%G`` | ISO 8601 year with century | 0001, 0002, ..., 2013, | \(8) |
2412| | representing the year that | 2014, ..., 9998, 9999 | |
2413| | contains the greater part of | | |
2414| | the ISO week (``%V``). | | |
2415+-----------+--------------------------------+------------------------+-------+
2416| ``%u`` | ISO 8601 weekday as a decimal | 1, 2, ..., 7 | |
2417| | number where 1 is Monday. | | |
2418+-----------+--------------------------------+------------------------+-------+
Mike Gleen6b9c2042019-06-18 19:14:57 +01002419| ``%V`` | ISO 8601 week as a decimal | 01, 02, ..., 53 | \(8), |
2420| | number with Monday as | | \(9) |
Alexander Belopolsky68713e42015-10-06 13:29:56 -04002421| | the first day of the week. | | |
2422| | Week 01 is the week containing | | |
2423| | Jan 4. | | |
2424+-----------+--------------------------------+------------------------+-------+
2425
Brad3fb13632019-09-11 05:19:05 -04002426These may not be available on all platforms when used with the :meth:`strftime`
2427method. The ISO 8601 year and ISO 8601 week directives are not interchangeable
2428with the year and week number directives above. Calling :meth:`strptime` with
2429incomplete or ambiguous ISO 8601 directives will raise a :exc:`ValueError`.
2430
2431The full set of format codes supported varies across platforms, because Python
2432calls the platform C library's :func:`strftime` function, and platform
2433variations are common. To see the full set of format codes supported on your
2434platform, consult the :manpage:`strftime(3)` documentation.
2435
Alexander Belopolsky68713e42015-10-06 13:29:56 -04002436.. versionadded:: 3.6
2437 ``%G``, ``%u`` and ``%V`` were added.
2438
Brad3fb13632019-09-11 05:19:05 -04002439Technical Detail
2440^^^^^^^^^^^^^^^^
2441
2442Broadly speaking, ``d.strftime(fmt)`` acts like the :mod:`time` module's
2443``time.strftime(fmt, d.timetuple())`` although not all objects support a
2444:meth:`timetuple` method.
2445
2446For the :meth:`datetime.strptime` class method, the default value is
2447``1900-01-01T00:00:00.000``: any components not specified in the format string
2448will be pulled from the default value. [#]_
2449
2450Using ``datetime.strptime(date_string, format)`` is equivalent to::
2451
2452 datetime(*(time.strptime(date_string, format)[0:6]))
2453
2454except when the format includes sub-second components or timezone offset
2455information, which are supported in ``datetime.strptime`` but are discarded by
2456``time.strptime``.
2457
2458For :class:`.time` objects, the format codes for year, month, and day should not
2459be used, as :class:`time` objects have no such values. If they're used anyway,
2460``1900`` is substituted for the year, and ``1`` for the month and day.
2461
2462For :class:`date` objects, the format codes for hours, minutes, seconds, and
2463microseconds should not be used, as :class:`date` objects have no such
2464values. If they're used anyway, ``0`` is substituted for them.
2465
2466For the same reason, handling of format strings containing Unicode code points
2467that can't be represented in the charset of the current locale is also
2468platform-dependent. On some platforms such code points are preserved intact in
2469the output, while on others ``strftime`` may raise :exc:`UnicodeError` or return
2470an empty string instead.
2471
Christian Heimes895627f2007-12-08 17:28:33 +00002472Notes:
2473
2474(1)
David Wolever569a5fa2013-08-12 16:56:02 -04002475 Because the format depends on the current locale, care should be taken when
2476 making assumptions about the output value. Field orderings will vary (for
2477 example, "month/day/year" versus "day/month/year"), and the output may
2478 contain Unicode characters encoded using the locale's default encoding (for
Georg Brandlad321532013-10-29 08:05:10 +01002479 example, if the current locale is ``ja_JP``, the default encoding could be
David Wolever569a5fa2013-08-12 16:56:02 -04002480 any one of ``eucJP``, ``SJIS``, or ``utf-8``; use :meth:`locale.getlocale`
2481 to determine the current locale's encoding).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002482
2483(2)
David Wolever569a5fa2013-08-12 16:56:02 -04002484 The :meth:`strptime` method can parse years in the full [1, 9999] range, but
2485 years < 1000 must be zero-filled to 4-digit width.
Alexander Belopolsky085556a2011-01-10 23:28:33 +00002486
2487 .. versionchanged:: 3.2
2488 In previous versions, :meth:`strftime` method was restricted to
2489 years >= 1900.
2490
Alexander Belopolsky5611a1c2011-05-02 14:14:48 -04002491 .. versionchanged:: 3.3
2492 In version 3.2, :meth:`strftime` method was restricted to
2493 years >= 1000.
2494
David Wolever569a5fa2013-08-12 16:56:02 -04002495(3)
2496 When used with the :meth:`strptime` method, the ``%p`` directive only affects
2497 the output hour field if the ``%I`` directive is used to parse the hour.
Alexander Belopolskyca94f552010-06-17 18:30:34 +00002498
David Wolever569a5fa2013-08-12 16:56:02 -04002499(4)
2500 Unlike the :mod:`time` module, the :mod:`datetime` module does not support
2501 leap seconds.
2502
2503(5)
2504 When used with the :meth:`strptime` method, the ``%f`` directive
Brad3fb13632019-09-11 05:19:05 -04002505 accepts from one to six digits and zero pads on the right. ``%f`` is
David Wolever569a5fa2013-08-12 16:56:02 -04002506 an extension to the set of format characters in the C standard (but
2507 implemented separately in datetime objects, and therefore always
2508 available).
2509
2510(6)
2511 For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
2512 strings.
2513
2514 For an aware object:
2515
2516 ``%z``
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002517 :meth:`utcoffset` is transformed into a string of the form
Brad3fb13632019-09-11 05:19:05 -04002518 ``±HHMM[SS[.ffffff]]``, where ``HH`` is a 2-digit string giving the number
2519 of UTC offset hours, ``MM`` is a 2-digit string giving the number of UTC
cocoatomo068768f2019-12-23 02:46:45 +09002520 offset minutes, ``SS`` is a 2-digit string giving the number of UTC offset
Brad3fb13632019-09-11 05:19:05 -04002521 seconds and ``ffffff`` is a 6-digit string giving the number of UTC
2522 offset microseconds. The ``ffffff`` part is omitted when the offset is a
2523 whole number of seconds and both the ``ffffff`` and the ``SS`` part is
2524 omitted when the offset is a whole number of minutes. For example, if
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002525 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
2526 replaced with the string ``'-0330'``.
2527
2528 .. versionchanged:: 3.7
2529 The UTC offset is not restricted to a whole number of minutes.
David Wolever569a5fa2013-08-12 16:56:02 -04002530
Mario Corchero32318932017-10-26 01:35:41 +01002531 .. versionchanged:: 3.7
2532 When the ``%z`` directive is provided to the :meth:`strptime` method,
2533 the UTC offsets can have a colon as a separator between hours, minutes
2534 and seconds.
2535 For example, ``'+01:00:00'`` will be parsed as an offset of one hour.
2536 In addition, providing ``'Z'`` is identical to ``'+00:00'``.
2537
David Wolever569a5fa2013-08-12 16:56:02 -04002538 ``%Z``
Karl Dubostbc441ed2019-11-27 01:38:41 +09002539 In :meth:`strftime`, ``%Z`` is replaced by an empty string if
2540 :meth:`tzname` returns ``None``; otherwise ``%Z`` is replaced by the
2541 returned value, which must be a string.
2542
2543 :meth:`strptime` only accepts certain values for ``%Z``:
2544
2545 1. any value in ``time.tzname`` for your machine's locale
2546 2. the hard-coded values ``UTC`` and ``GMT``
2547
2548 So someone living in Japan may have ``JST``, ``UTC``, and ``GMT`` as
2549 valid values, but probably not ``EST``. It will raise ``ValueError`` for
2550 invalid values.
David Wolever569a5fa2013-08-12 16:56:02 -04002551
2552 .. versionchanged:: 3.2
2553 When the ``%z`` directive is provided to the :meth:`strptime` method, an
Brad3fb13632019-09-11 05:19:05 -04002554 aware :class:`.datetime` object will be produced. The ``tzinfo`` of the
David Wolever569a5fa2013-08-12 16:56:02 -04002555 result will be set to a :class:`timezone` instance.
2556
2557(7)
2558 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used
Alexander Belopolsky68713e42015-10-06 13:29:56 -04002559 in calculations when the day of the week and the calendar year (``%Y``)
2560 are specified.
2561
2562(8)
2563 Similar to ``%U`` and ``%W``, ``%V`` is only used in calculations when the
2564 day of the week and the ISO year (``%G``) are specified in a
2565 :meth:`strptime` format string. Also note that ``%G`` and ``%Y`` are not
Martin Panterf1579822016-05-26 06:03:33 +00002566 interchangeable.
R David Murray9075d8b2012-05-14 22:14:46 -04002567
Mike Gleen6b9c2042019-06-18 19:14:57 +01002568(9)
2569 When used with the :meth:`strptime` method, the leading zero is optional
2570 for formats ``%d``, ``%m``, ``%H``, ``%I``, ``%M``, ``%S``, ``%J``, ``%U``,
2571 ``%W``, and ``%V``. Format ``%y`` does require a leading zero.
2572
R David Murray9075d8b2012-05-14 22:14:46 -04002573.. rubric:: Footnotes
2574
2575.. [#] If, that is, we ignore the effects of Relativity
Brad3fb13632019-09-11 05:19:05 -04002576
2577.. [#] This matches the definition of the "proleptic Gregorian" calendar in
2578 Dershowitz and Reingold's book *Calendrical Calculations*,
2579 where it's the base calendar for all computations. See the book for
2580 algorithms for converting between proleptic Gregorian ordinals and
2581 many other calendar systems.
2582
2583.. [#] See R. H. van Gent's `guide to the mathematics of the ISO 8601 calendar
2584 <https://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm>`_
2585 for a good explanation.
2586
Abhishek Kumar Singh56027cc2019-05-19 02:06:19 +05302587.. [#] Passing ``datetime.strptime('Feb 29', '%b %d')`` will fail since ``1900`` is not a leap year.