blob: 1ee23c2175a27d6acc7765f94714002c9e11cffb [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
Georg Brandl116aa622007-08-15 14:28:22 +000017The :mod:`datetime` module supplies classes for manipulating dates and times in
18both simple and complex ways. While date and time arithmetic is supported, the
Senthil Kumarana6bac952011-07-04 11:28:30 -070019focus of the implementation is on efficient attribute extraction for output
R David Murray539f2392012-05-14 22:17:23 -040020formatting and manipulation. For related functionality, see also the
21:mod:`time` and :mod:`calendar` modules.
Georg Brandl116aa622007-08-15 14:28:22 +000022
R David Murray9075d8b2012-05-14 22:14:46 -040023There are two kinds of date and time objects: "naive" and "aware".
Georg Brandl116aa622007-08-15 14:28:22 +000024
R David Murray9075d8b2012-05-14 22:14:46 -040025An aware object has sufficient knowledge of applicable algorithmic and
26political time adjustments, such as time zone and daylight saving time
27information, to locate itself relative to other aware objects. An aware object
28is used to represent a specific moment in time that is not open to
29interpretation [#]_.
30
31A naive object does not contain enough information to unambiguously locate
32itself relative to other date/time objects. Whether a naive object represents
R David Murray539f2392012-05-14 22:17:23 -040033Coordinated Universal Time (UTC), local time, or time in some other timezone is
34purely up to the program, just like it is up to the program whether a
35particular number represents metres, miles, or mass. Naive objects are easy to
36understand and to work with, at the cost of ignoring some aspects of reality.
Georg Brandl116aa622007-08-15 14:28:22 +000037
R David Murray539f2392012-05-14 22:17:23 -040038For applications requiring aware objects, :class:`.datetime` and :class:`.time`
Martin Panter16c7cfd2016-04-01 21:48:24 +000039objects have an optional time zone information attribute, :attr:`!tzinfo`, that
R David Murray539f2392012-05-14 22:17:23 -040040can be set to an instance of a subclass of the abstract :class:`tzinfo` class.
41These :class:`tzinfo` objects capture information about the offset from UTC
42time, the time zone name, and whether Daylight Saving Time is in effect. Note
43that only one concrete :class:`tzinfo` class, the :class:`timezone` class, is
44supplied by the :mod:`datetime` module. The :class:`timezone` class can
45represent simple timezones with fixed offset from UTC, such as UTC itself or
46North American EST and EDT timezones. Supporting timezones at deeper levels of
47detail is up to the application. The rules for time adjustment across the
Alexander Belopolsky4e749a12010-06-14 14:15:50 +000048world are more political than rational, change frequently, and there is no
49standard suitable for every application aside from UTC.
Georg Brandl116aa622007-08-15 14:28:22 +000050
51The :mod:`datetime` module exports the following constants:
52
Georg Brandl116aa622007-08-15 14:28:22 +000053.. data:: MINYEAR
54
Ezio Melotti35ec7f72011-10-02 12:44:50 +030055 The smallest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl116aa622007-08-15 14:28:22 +000056 :const:`MINYEAR` is ``1``.
57
58
59.. data:: MAXYEAR
60
Ezio Melotti35ec7f72011-10-02 12:44:50 +030061 The largest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl116aa622007-08-15 14:28:22 +000062 :const:`MAXYEAR` is ``9999``.
63
64
65.. seealso::
66
67 Module :mod:`calendar`
68 General calendar related functions.
69
70 Module :mod:`time`
71 Time access and conversions.
72
73
74Available Types
75---------------
76
Georg Brandl116aa622007-08-15 14:28:22 +000077.. class:: date
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000078 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000079
80 An idealized naive date, assuming the current Gregorian calendar always was, and
81 always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and
82 :attr:`day`.
83
84
85.. class:: time
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000086 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000087
88 An idealized time, independent of any particular day, assuming that every day
89 has exactly 24\*60\*60 seconds (there is no notion of "leap seconds" here).
90 Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
Martin Panter16c7cfd2016-04-01 21:48:24 +000091 and :attr:`.tzinfo`.
Georg Brandl116aa622007-08-15 14:28:22 +000092
93
94.. class:: datetime
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000095 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000096
97 A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`,
98 :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
Martin Panter16c7cfd2016-04-01 21:48:24 +000099 and :attr:`.tzinfo`.
Georg Brandl116aa622007-08-15 14:28:22 +0000100
101
102.. class:: timedelta
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000103 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000104
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300105 A duration expressing the difference between two :class:`date`, :class:`.time`,
106 or :class:`.datetime` instances to microsecond resolution.
Georg Brandl116aa622007-08-15 14:28:22 +0000107
108
109.. class:: tzinfo
Martin Panter16c7cfd2016-04-01 21:48:24 +0000110 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000111
112 An abstract base class for time zone information objects. These are used by the
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300113 :class:`.datetime` and :class:`.time` classes to provide a customizable notion of
Georg Brandl116aa622007-08-15 14:28:22 +0000114 time adjustment (for example, to account for time zone and/or daylight saving
115 time).
116
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000117.. class:: timezone
Martin Panter16c7cfd2016-04-01 21:48:24 +0000118 :noindex:
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000119
120 A class that implements the :class:`tzinfo` abstract base class as a
121 fixed offset from the UTC.
122
123 .. versionadded:: 3.2
124
125
Georg Brandl116aa622007-08-15 14:28:22 +0000126Objects of these types are immutable.
127
128Objects of the :class:`date` type are always naive.
129
R David Murray9075d8b2012-05-14 22:14:46 -0400130An object of type :class:`.time` or :class:`.datetime` may be naive or aware.
131A :class:`.datetime` object *d* is aware if ``d.tzinfo`` is not ``None`` and
132``d.tzinfo.utcoffset(d)`` does not return ``None``. If ``d.tzinfo`` is
133``None``, or if ``d.tzinfo`` is not ``None`` but ``d.tzinfo.utcoffset(d)``
134returns ``None``, *d* is naive. A :class:`.time` object *t* is aware
135if ``t.tzinfo`` is not ``None`` and ``t.tzinfo.utcoffset(None)`` does not return
136``None``. Otherwise, *t* is naive.
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138The distinction between naive and aware doesn't apply to :class:`timedelta`
139objects.
140
141Subclass relationships::
142
143 object
144 timedelta
145 tzinfo
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000146 timezone
Georg Brandl116aa622007-08-15 14:28:22 +0000147 time
148 date
149 datetime
150
151
152.. _datetime-timedelta:
153
154:class:`timedelta` Objects
155--------------------------
156
157A :class:`timedelta` object represents a duration, the difference between two
158dates or times.
159
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000160.. class:: timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000161
Georg Brandl5c106642007-11-29 17:41:05 +0000162 All arguments are optional and default to ``0``. Arguments may be integers
Georg Brandl116aa622007-08-15 14:28:22 +0000163 or floats, and may be positive or negative.
164
165 Only *days*, *seconds* and *microseconds* are stored internally. Arguments are
166 converted to those units:
167
168 * A millisecond is converted to 1000 microseconds.
169 * A minute is converted to 60 seconds.
170 * An hour is converted to 3600 seconds.
171 * A week is converted to 7 days.
172
173 and days, seconds and microseconds are then normalized so that the
174 representation is unique, with
175
176 * ``0 <= microseconds < 1000000``
177 * ``0 <= seconds < 3600*24`` (the number of seconds in one day)
178 * ``-999999999 <= days <= 999999999``
179
Alexander Belopolsky790d2692013-08-04 14:51:35 -0400180 If any argument is a float and there are fractional microseconds,
181 the fractional microseconds left over from all arguments are
182 combined and their sum is rounded to the nearest microsecond using
183 round-half-to-even tiebreaker. If no argument is a float, the
184 conversion and normalization processes are exact (no information is
185 lost).
Georg Brandl116aa622007-08-15 14:28:22 +0000186
187 If the normalized value of days lies outside the indicated range,
188 :exc:`OverflowError` is raised.
189
190 Note that normalization of negative values may be surprising at first. For
Christian Heimesfe337bf2008-03-23 21:54:12 +0000191 example,
Georg Brandl116aa622007-08-15 14:28:22 +0000192
Christian Heimes895627f2007-12-08 17:28:33 +0000193 >>> from datetime import timedelta
Georg Brandl116aa622007-08-15 14:28:22 +0000194 >>> d = timedelta(microseconds=-1)
195 >>> (d.days, d.seconds, d.microseconds)
196 (-1, 86399, 999999)
197
Georg Brandl116aa622007-08-15 14:28:22 +0000198
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000199Class attributes are:
Georg Brandl116aa622007-08-15 14:28:22 +0000200
201.. attribute:: timedelta.min
202
203 The most negative :class:`timedelta` object, ``timedelta(-999999999)``.
204
205
206.. attribute:: timedelta.max
207
208 The most positive :class:`timedelta` object, ``timedelta(days=999999999,
209 hours=23, minutes=59, seconds=59, microseconds=999999)``.
210
211
212.. attribute:: timedelta.resolution
213
214 The smallest possible difference between non-equal :class:`timedelta` objects,
215 ``timedelta(microseconds=1)``.
216
217Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``.
218``-timedelta.max`` is not representable as a :class:`timedelta` object.
219
220Instance attributes (read-only):
221
222+------------------+--------------------------------------------+
223| Attribute | Value |
224+==================+============================================+
225| ``days`` | Between -999999999 and 999999999 inclusive |
226+------------------+--------------------------------------------+
227| ``seconds`` | Between 0 and 86399 inclusive |
228+------------------+--------------------------------------------+
229| ``microseconds`` | Between 0 and 999999 inclusive |
230+------------------+--------------------------------------------+
231
232Supported operations:
233
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000234.. XXX this table is too wide!
Georg Brandl116aa622007-08-15 14:28:22 +0000235
236+--------------------------------+-----------------------------------------------+
237| Operation | Result |
238+================================+===============================================+
239| ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == |
240| | *t3* and *t1*-*t3* == *t2* are true. (1) |
241+--------------------------------+-----------------------------------------------+
242| ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* |
243| | == *t2* - *t3* and *t2* == *t1* + *t3* are |
Farhaan Bukhsh5b6e49a2018-07-05 00:12:05 +0530244| | true. (1)(6) |
Georg Brandl116aa622007-08-15 14:28:22 +0000245+--------------------------------+-----------------------------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000246| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer. |
Georg Brandl116aa622007-08-15 14:28:22 +0000247| | Afterwards *t1* // i == *t2* is true, |
248| | provided ``i != 0``. |
249+--------------------------------+-----------------------------------------------+
250| | In general, *t1* \* i == *t1* \* (i-1) + *t1* |
251| | is true. (1) |
252+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000253| ``t1 = t2 * f or t1 = f * t2`` | Delta multiplied by a float. The result is |
254| | rounded to the nearest multiple of |
255| | timedelta.resolution using round-half-to-even.|
256+--------------------------------+-----------------------------------------------+
Yasser Af40b4a02019-03-15 23:56:58 -0400257| ``f = t2 / t3`` | Division (3) of overall duration *t2* by |
258| | interval unit *t3*. Returns a :class:`float` |
259| | object. |
Mark Dickinson7c186e22010-04-20 22:32:49 +0000260+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000261| ``t1 = t2 / f or t1 = t2 / i`` | Delta divided by a float or an int. The result|
262| | is rounded to the nearest multiple of |
263| | timedelta.resolution using round-half-to-even.|
264+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000265| ``t1 = t2 // i`` or | The floor is computed and the remainder (if |
266| ``t1 = t2 // t3`` | any) is thrown away. In the second case, an |
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000267| | integer is returned. (3) |
Mark Dickinson7c186e22010-04-20 22:32:49 +0000268+--------------------------------+-----------------------------------------------+
269| ``t1 = t2 % t3`` | The remainder is computed as a |
270| | :class:`timedelta` object. (3) |
271+--------------------------------+-----------------------------------------------+
272| ``q, r = divmod(t1, t2)`` | Computes the quotient and the remainder: |
273| | ``q = t1 // t2`` (3) and ``r = t1 % t2``. |
274| | q is an integer and r is a :class:`timedelta` |
275| | object. |
Georg Brandl116aa622007-08-15 14:28:22 +0000276+--------------------------------+-----------------------------------------------+
277| ``+t1`` | Returns a :class:`timedelta` object with the |
278| | same value. (2) |
279+--------------------------------+-----------------------------------------------+
Serhiy Storchaka3f819ca2018-10-31 02:26:06 +0200280| ``-t1`` | equivalent to |
281| | :class:`timedelta`\ (-*t1.days*, |
282| | -*t1.seconds*, -*t1.microseconds*), |
283| | and to *t1*\* -1. (1)(4) |
Georg Brandl116aa622007-08-15 14:28:22 +0000284+--------------------------------+-----------------------------------------------+
Georg Brandl495f7b52009-10-27 15:28:25 +0000285| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, and|
Georg Brandl116aa622007-08-15 14:28:22 +0000286| | to -*t* when ``t.days < 0``. (2) |
287+--------------------------------+-----------------------------------------------+
Georg Brandlf55c3152010-07-31 11:40:07 +0000288| ``str(t)`` | Returns a string in the form |
289| | ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D |
290| | is negative for negative ``t``. (5) |
291+--------------------------------+-----------------------------------------------+
Utkarsh Upadhyaycc5a65c2017-07-25 23:51:33 +0200292| ``repr(t)`` | Returns a string representation of the |
293| | :class:`timedelta` object as a constructor |
294| | call with canonical attribute values. |
Georg Brandlf55c3152010-07-31 11:40:07 +0000295+--------------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000296
Utkarsh Upadhyaycc5a65c2017-07-25 23:51:33 +0200297
Georg Brandl116aa622007-08-15 14:28:22 +0000298Notes:
299
300(1)
301 This is exact, but may overflow.
302
303(2)
304 This is exact, and cannot overflow.
305
306(3)
307 Division by 0 raises :exc:`ZeroDivisionError`.
308
309(4)
310 -*timedelta.max* is not representable as a :class:`timedelta` object.
311
Georg Brandlf55c3152010-07-31 11:40:07 +0000312(5)
313 String representations of :class:`timedelta` objects are normalized
314 similarly to their internal representation. This leads to somewhat
315 unusual results for negative timedeltas. For example:
316
317 >>> timedelta(hours=-5)
Utkarsh Upadhyay8e453182017-07-28 14:42:56 +0200318 datetime.timedelta(days=-1, seconds=68400)
Georg Brandlf55c3152010-07-31 11:40:07 +0000319 >>> print(_)
320 -1 day, 19:00:00
321
Farhaan Bukhsh5b6e49a2018-07-05 00:12:05 +0530322(6)
323 The expression ``t2 - t3`` will always be equal to the expression ``t2 + (-t3)`` except
324 when t3 is equal to ``timedelta.max``; in that case the former will produce a result
325 while the latter will overflow.
326
Georg Brandl116aa622007-08-15 14:28:22 +0000327In addition to the operations listed above :class:`timedelta` objects support
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300328certain additions and subtractions with :class:`date` and :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +0000329objects (see below).
330
Georg Brandl67b21b72010-08-17 15:07:14 +0000331.. versionchanged:: 3.2
332 Floor division and true division of a :class:`timedelta` object by another
333 :class:`timedelta` object are now supported, as are remainder operations and
334 the :func:`divmod` function. True division and multiplication of a
335 :class:`timedelta` object by a :class:`float` object are now supported.
Mark Dickinson7c186e22010-04-20 22:32:49 +0000336
337
Georg Brandl116aa622007-08-15 14:28:22 +0000338Comparisons of :class:`timedelta` objects are supported with the
339:class:`timedelta` object representing the smaller duration considered to be the
340smaller timedelta. In order to stop mixed-type comparisons from falling back to
341the default comparison by object address, when a :class:`timedelta` object is
342compared to an object of a different type, :exc:`TypeError` is raised unless the
343comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
344:const:`True`, respectively.
345
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000346:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl116aa622007-08-15 14:28:22 +0000347efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
348considered to be true if and only if it isn't equal to ``timedelta(0)``.
349
Antoine Pitroube6859d2009-11-25 23:02:32 +0000350Instance methods:
351
352.. method:: timedelta.total_seconds()
353
354 Return the total number of seconds contained in the duration. Equivalent to
Yasser Af40b4a02019-03-15 23:56:58 -0400355 ``td / timedelta(seconds=1)``. For interval units other than seconds, use the
356 division form directly (e.g. ``td / timedelta(microseconds=1)``).
Mark Dickinson0381e3f2010-05-08 14:35:02 +0000357
358 Note that for very large time intervals (greater than 270 years on
359 most platforms) this method will lose microsecond accuracy.
Antoine Pitroube6859d2009-11-25 23:02:32 +0000360
361 .. versionadded:: 3.2
362
363
Christian Heimesfe337bf2008-03-23 21:54:12 +0000364Example usage:
Georg Brandl48310cd2009-01-03 21:18:54 +0000365
Christian Heimes895627f2007-12-08 17:28:33 +0000366 >>> from datetime import timedelta
367 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000368 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Christian Heimes895627f2007-12-08 17:28:33 +0000369 ... minutes=50, seconds=600) # adds up to 365 days
Antoine Pitroube6859d2009-11-25 23:02:32 +0000370 >>> year.total_seconds()
371 31536000.0
Christian Heimes895627f2007-12-08 17:28:33 +0000372 >>> year == another_year
373 True
374 >>> ten_years = 10 * year
375 >>> ten_years, ten_years.days // 365
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +0200376 (datetime.timedelta(days=3650), 10)
Christian Heimes895627f2007-12-08 17:28:33 +0000377 >>> nine_years = ten_years - year
378 >>> nine_years, nine_years.days // 365
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +0200379 (datetime.timedelta(days=3285), 9)
delirious-lettucec7b3f0f2017-05-18 19:01:00 -0600380 >>> three_years = nine_years // 3
Christian Heimes895627f2007-12-08 17:28:33 +0000381 >>> three_years, three_years.days // 365
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +0200382 (datetime.timedelta(days=1095), 3)
Christian Heimes895627f2007-12-08 17:28:33 +0000383 >>> abs(three_years - ten_years) == 2 * three_years + year
384 True
385
Georg Brandl116aa622007-08-15 14:28:22 +0000386
387.. _datetime-date:
388
389:class:`date` Objects
390---------------------
391
392A :class:`date` object represents a date (year, month and day) in an idealized
393calendar, the current Gregorian calendar indefinitely extended in both
394directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
395called day number 2, and so on. This matches the definition of the "proleptic
396Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
397where it's the base calendar for all computations. See the book for algorithms
398for converting between proleptic Gregorian ordinals and many other calendar
399systems.
400
401
402.. class:: date(year, month, day)
403
Georg Brandl5c106642007-11-29 17:41:05 +0000404 All arguments are required. Arguments may be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000405 ranges:
406
407 * ``MINYEAR <= year <= MAXYEAR``
408 * ``1 <= month <= 12``
409 * ``1 <= day <= number of days in the given month and year``
410
411 If an argument outside those ranges is given, :exc:`ValueError` is raised.
412
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000413
Georg Brandl116aa622007-08-15 14:28:22 +0000414Other constructors, all class methods:
415
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000416.. classmethod:: date.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000417
418 Return the current local date. This is equivalent to
419 ``date.fromtimestamp(time.time())``.
420
421
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000422.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000423
424 Return the local date corresponding to the POSIX timestamp, such as is returned
Victor Stinner5d272cc2012-03-13 13:35:55 +0100425 by :func:`time.time`. This may raise :exc:`OverflowError`, if the timestamp is out
Victor Stinnerecc6e662012-03-14 00:39:29 +0100426 of the range of values supported by the platform C :c:func:`localtime` function,
427 and :exc:`OSError` on :c:func:`localtime` failure.
Georg Brandl116aa622007-08-15 14:28:22 +0000428 It's common for this to be restricted to years from 1970 through 2038. Note
429 that on non-POSIX systems that include leap seconds in their notion of a
430 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
431
Victor Stinner5d272cc2012-03-13 13:35:55 +0100432 .. versionchanged:: 3.3
433 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
434 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100435 :c:func:`localtime` function. Raise :exc:`OSError` instead of
436 :exc:`ValueError` on :c:func:`localtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100437
Georg Brandl116aa622007-08-15 14:28:22 +0000438
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000439.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000440
441 Return the date corresponding to the proleptic Gregorian ordinal, where January
442 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
443 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
444 d``.
445
Georg Brandl116aa622007-08-15 14:28:22 +0000446
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500447.. classmethod:: date.fromisoformat(date_string)
448
449 Return a :class:`date` corresponding to a *date_string* in the format emitted
450 by :meth:`date.isoformat`. Specifically, this function supports strings in
451 the format(s) ``YYYY-MM-DD``.
452
453 .. caution::
454
455 This does not support parsing arbitrary ISO 8601 strings - it is only intended
456 as the inverse operation of :meth:`date.isoformat`.
457
458 .. versionadded:: 3.7
459
460
461
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000462Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000463
464.. attribute:: date.min
465
466 The earliest representable date, ``date(MINYEAR, 1, 1)``.
467
468
469.. attribute:: date.max
470
471 The latest representable date, ``date(MAXYEAR, 12, 31)``.
472
473
474.. attribute:: date.resolution
475
476 The smallest possible difference between non-equal date objects,
477 ``timedelta(days=1)``.
478
Georg Brandl116aa622007-08-15 14:28:22 +0000479
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000480Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000481
482.. attribute:: date.year
483
484 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
485
486
487.. attribute:: date.month
488
489 Between 1 and 12 inclusive.
490
491
492.. attribute:: date.day
493
494 Between 1 and the number of days in the given month of the given year.
495
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000496
Georg Brandl116aa622007-08-15 14:28:22 +0000497Supported operations:
498
499+-------------------------------+----------------------------------------------+
500| Operation | Result |
501+===============================+==============================================+
502| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
503| | from *date1*. (1) |
504+-------------------------------+----------------------------------------------+
505| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
506| | timedelta == date1``. (2) |
507+-------------------------------+----------------------------------------------+
508| ``timedelta = date1 - date2`` | \(3) |
509+-------------------------------+----------------------------------------------+
510| ``date1 < date2`` | *date1* is considered less than *date2* when |
511| | *date1* precedes *date2* in time. (4) |
512+-------------------------------+----------------------------------------------+
513
514Notes:
515
516(1)
517 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
518 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
519 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
520 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
521 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
522
523(2)
Georg Brandl116aa622007-08-15 14:28:22 +0000524 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
525
526(3)
527 This is exact, and cannot overflow. timedelta.seconds and
528 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
529
530(4)
531 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
Danish Prakash9c223792018-09-12 02:29:23 +0530532 date2.toordinal()``. Date comparison raises :exc:`TypeError` if
533 the other comparand isn't also a :class:`date` object. However,
534 ``NotImplemented`` is returned instead if the other comparand has a
Georg Brandl116aa622007-08-15 14:28:22 +0000535 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
536 chance at implementing mixed-type comparison. If not, when a :class:`date`
537 object is compared to an object of a different type, :exc:`TypeError` is raised
538 unless the comparison is ``==`` or ``!=``. The latter cases return
539 :const:`False` or :const:`True`, respectively.
540
541Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
542objects are considered to be true.
543
544Instance methods:
545
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400546.. method:: date.replace(year=self.year, month=self.month, day=self.day)
Georg Brandl116aa622007-08-15 14:28:22 +0000547
Senthil Kumarana6bac952011-07-04 11:28:30 -0700548 Return a date with the same value, except for those parameters given new
549 values by whichever keyword arguments are specified. For example, if ``d ==
550 date(2002, 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000551
552
553.. method:: date.timetuple()
554
555 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
556 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
557 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000558 d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1,
559 1).toordinal() + 1`` is the day number within the current year starting with
560 ``1`` for January 1st.
Georg Brandl116aa622007-08-15 14:28:22 +0000561
562
563.. method:: date.toordinal()
564
565 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
566 has ordinal 1. For any :class:`date` object *d*,
567 ``date.fromordinal(d.toordinal()) == d``.
568
569
570.. method:: date.weekday()
571
572 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
573 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
574 :meth:`isoweekday`.
575
576
577.. method:: date.isoweekday()
578
579 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
580 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
581 :meth:`weekday`, :meth:`isocalendar`.
582
583
584.. method:: date.isocalendar()
585
586 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
587
588 The ISO calendar is a widely used variant of the Gregorian calendar. See
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300589 https://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm for a good
Mark Dickinsonf964ac22009-11-03 16:29:10 +0000590 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000591
592 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
593 Monday and ends on a Sunday. The first week of an ISO year is the first
594 (Gregorian) calendar week of a year containing a Thursday. This is called week
595 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
596
597 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
598 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
599 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
600 4).isocalendar() == (2004, 1, 7)``.
601
602
603.. method:: date.isoformat()
604
605 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
606 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
607
608
609.. method:: date.__str__()
610
611 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
612
613
614.. method:: date.ctime()
615
616 Return a string representing the date, for example ``date(2002, 12,
617 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
618 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
Georg Brandl60203b42010-10-06 10:11:56 +0000619 :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +0000620 :meth:`date.ctime` does not invoke) conforms to the C standard.
621
622
623.. method:: date.strftime(format)
624
625 Return a string representing the date, controlled by an explicit format string.
David Wolever569a5fa2013-08-12 16:56:02 -0400626 Format codes referring to hours, minutes or seconds will see 0 values. For a
627 complete list of formatting directives, see
628 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000629
Georg Brandl116aa622007-08-15 14:28:22 +0000630
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300631.. method:: date.__format__(format)
632
Martin Panterd5db1472016-02-08 01:34:09 +0000633 Same as :meth:`.date.strftime`. This makes it possible to specify a format
Martin Panterbc1ee462016-02-13 00:41:37 +0000634 string for a :class:`.date` object in :ref:`formatted string
635 literals <f-strings>` and when using :meth:`str.format`. For a
David Wolever569a5fa2013-08-12 16:56:02 -0400636 complete list of formatting directives, see
637 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300638
639
Christian Heimes895627f2007-12-08 17:28:33 +0000640Example of counting days to an event::
641
642 >>> import time
643 >>> from datetime import date
644 >>> today = date.today()
645 >>> today
646 datetime.date(2007, 12, 5)
647 >>> today == date.fromtimestamp(time.time())
648 True
649 >>> my_birthday = date(today.year, 6, 24)
650 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000651 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000652 >>> my_birthday
653 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000654 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000655 >>> time_to_birthday.days
656 202
657
Christian Heimesfe337bf2008-03-23 21:54:12 +0000658Example of working with :class:`date`:
659
660.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000661
662 >>> from datetime import date
663 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
664 >>> d
665 datetime.date(2002, 3, 11)
666 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000667 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000668 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000669 2002 # year
670 3 # month
671 11 # day
672 0
673 0
674 0
675 0 # weekday (0 = Monday)
676 70 # 70th day in the year
677 -1
678 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000679 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000680 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000681 2002 # ISO year
682 11 # ISO week number
683 1 # ISO day number ( 1 = Monday )
684 >>> d.isoformat()
685 '2002-03-11'
686 >>> d.strftime("%d/%m/%y")
687 '11/03/02'
688 >>> d.strftime("%A %d. %B %Y")
689 'Monday 11. March 2002'
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300690 >>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")
691 'The day is 11, the month is March.'
Christian Heimes895627f2007-12-08 17:28:33 +0000692
Georg Brandl116aa622007-08-15 14:28:22 +0000693
694.. _datetime-datetime:
695
Benjamin Petersond87dd432015-04-25 14:15:16 -0400696:class:`.datetime` Objects
697--------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000698
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300699A :class:`.datetime` object is a single object containing all the information
700from a :class:`date` object and a :class:`.time` object. Like a :class:`date`
701object, :class:`.datetime` assumes the current Gregorian calendar extended in
702both directions; like a time object, :class:`.datetime` assumes there are exactly
Georg Brandl116aa622007-08-15 14:28:22 +00007033600\*24 seconds in every day.
704
705Constructor:
706
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400707.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000708
709 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000710 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
711 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000712
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400713 * ``MINYEAR <= year <= MAXYEAR``,
714 * ``1 <= month <= 12``,
715 * ``1 <= day <= number of days in the given month and year``,
716 * ``0 <= hour < 24``,
717 * ``0 <= minute < 60``,
718 * ``0 <= second < 60``,
719 * ``0 <= microsecond < 1000000``,
720 * ``fold in [0, 1]``.
Georg Brandl116aa622007-08-15 14:28:22 +0000721
722 If an argument outside those ranges is given, :exc:`ValueError` is raised.
723
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400724 .. versionadded:: 3.6
725 Added the ``fold`` argument.
726
Georg Brandl116aa622007-08-15 14:28:22 +0000727Other constructors, all class methods:
728
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000729.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000730
Martin Panter16c7cfd2016-04-01 21:48:24 +0000731 Return the current local datetime, with :attr:`.tzinfo` ``None``. This is
Georg Brandl116aa622007-08-15 14:28:22 +0000732 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
733 :meth:`fromtimestamp`.
734
735
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000736.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000737
738 Return the current local date and time. If optional argument *tz* is ``None``
739 or not specified, this is like :meth:`today`, but, if possible, supplies more
740 precision than can be gotten from going through a :func:`time.time` timestamp
741 (for example, this may be possible on platforms supplying the C
Georg Brandl60203b42010-10-06 10:11:56 +0000742 :c:func:`gettimeofday` function).
Georg Brandl116aa622007-08-15 14:28:22 +0000743
Martin Panter16c7cfd2016-04-01 21:48:24 +0000744 If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` subclass, and the
745 current date and time are converted to *tz*’s time zone. In this case the
Georg Brandl116aa622007-08-15 14:28:22 +0000746 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
747 See also :meth:`today`, :meth:`utcnow`.
748
749
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000750.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000751
Martin Panter16c7cfd2016-04-01 21:48:24 +0000752 Return the current UTC date and time, with :attr:`.tzinfo` ``None``. This is like
Georg Brandl116aa622007-08-15 14:28:22 +0000753 :meth:`now`, but returns the current UTC date and time, as a naive
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300754 :class:`.datetime` object. An aware current UTC datetime can be obtained by
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000755 calling ``datetime.now(timezone.utc)``. See also :meth:`now`.
Georg Brandl116aa622007-08-15 14:28:22 +0000756
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000757.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000758
759 Return the local date and time corresponding to the POSIX timestamp, such as is
760 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
761 specified, the timestamp is converted to the platform's local date and time, and
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300762 the returned :class:`.datetime` object is naive.
Georg Brandl116aa622007-08-15 14:28:22 +0000763
Martin Panter16c7cfd2016-04-01 21:48:24 +0000764 If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` subclass, and the
765 timestamp is converted to *tz*’s time zone. In this case the result is
Georg Brandl116aa622007-08-15 14:28:22 +0000766 equivalent to
767 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
768
Victor Stinnerecc6e662012-03-14 00:39:29 +0100769 :meth:`fromtimestamp` may raise :exc:`OverflowError`, if the timestamp is out of
Georg Brandl60203b42010-10-06 10:11:56 +0000770 the range of values supported by the platform C :c:func:`localtime` or
Victor Stinnerecc6e662012-03-14 00:39:29 +0100771 :c:func:`gmtime` functions, and :exc:`OSError` on :c:func:`localtime` or
772 :c:func:`gmtime` failure.
773 It's common for this to be restricted to years in
Georg Brandl116aa622007-08-15 14:28:22 +0000774 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
775 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
776 and then it's possible to have two timestamps differing by a second that yield
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300777 identical :class:`.datetime` objects. See also :meth:`utcfromtimestamp`.
Georg Brandl116aa622007-08-15 14:28:22 +0000778
Victor Stinner5d272cc2012-03-13 13:35:55 +0100779 .. versionchanged:: 3.3
780 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
781 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100782 :c:func:`localtime` or :c:func:`gmtime` functions. Raise :exc:`OSError`
783 instead of :exc:`ValueError` on :c:func:`localtime` or :c:func:`gmtime`
784 failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100785
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400786 .. versionchanged:: 3.6
787 :meth:`fromtimestamp` may return instances with :attr:`.fold` set to 1.
Georg Brandl116aa622007-08-15 14:28:22 +0000788
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000789.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000790
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300791 Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with
Martin Panter16c7cfd2016-04-01 21:48:24 +0000792 :attr:`.tzinfo` ``None``. This may raise :exc:`OverflowError`, if the timestamp is
Victor Stinnerecc6e662012-03-14 00:39:29 +0100793 out of the range of values supported by the platform C :c:func:`gmtime` function,
794 and :exc:`OSError` on :c:func:`gmtime` failure.
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500795 It's common for this to be restricted to years in 1970 through 2038.
Georg Brandl116aa622007-08-15 14:28:22 +0000796
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500797 To get an aware :class:`.datetime` object, call :meth:`fromtimestamp`::
Alexander Belopolsky54afa552011-04-25 13:00:40 -0400798
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500799 datetime.fromtimestamp(timestamp, timezone.utc)
800
801 On the POSIX compliant platforms, it is equivalent to the following
802 expression::
803
804 datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)
805
806 except the latter formula always supports the full years range: between
807 :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
Alexander Belopolsky54afa552011-04-25 13:00:40 -0400808
Victor Stinner5d272cc2012-03-13 13:35:55 +0100809 .. versionchanged:: 3.3
810 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
811 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100812 :c:func:`gmtime` function. Raise :exc:`OSError` instead of
813 :exc:`ValueError` on :c:func:`gmtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100814
Georg Brandl116aa622007-08-15 14:28:22 +0000815
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000816.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000817
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300818 Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal,
Georg Brandl116aa622007-08-15 14:28:22 +0000819 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
820 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
Martin Panter16c7cfd2016-04-01 21:48:24 +0000821 microsecond of the result are all 0, and :attr:`.tzinfo` is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000822
823
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400824.. classmethod:: datetime.combine(date, time, tzinfo=self.tzinfo)
Georg Brandl116aa622007-08-15 14:28:22 +0000825
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300826 Return a new :class:`.datetime` object whose date components are equal to the
Alexander Belopolsky43746c32016-08-02 17:49:30 -0400827 given :class:`date` object's, and whose time components
828 are equal to the given :class:`.time` object's. If the *tzinfo*
829 argument is provided, its value is used to set the :attr:`.tzinfo` attribute
830 of the result, otherwise the :attr:`~.time.tzinfo` attribute of the *time* argument
831 is used.
832
833 For any :class:`.datetime` object *d*,
834 ``d == datetime.combine(d.date(), d.time(), d.tzinfo)``. If date is a
Martin Panter16c7cfd2016-04-01 21:48:24 +0000835 :class:`.datetime` object, its time components and :attr:`.tzinfo` attributes
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800836 are ignored.
Georg Brandl116aa622007-08-15 14:28:22 +0000837
Alexander Belopolsky43746c32016-08-02 17:49:30 -0400838 .. versionchanged:: 3.6
839 Added the *tzinfo* argument.
840
Georg Brandl116aa622007-08-15 14:28:22 +0000841
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500842.. classmethod:: datetime.fromisoformat(date_string)
843
844 Return a :class:`datetime` corresponding to a *date_string* in one of the
845 formats emitted by :meth:`date.isoformat` and :meth:`datetime.isoformat`.
846 Specifically, this function supports strings in the format(s)
Christophe Nanteuil92878822018-10-06 00:57:02 +0200847 ``YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]]``,
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500848 where ``*`` can match any single character.
849
850 .. caution::
851
852 This does not support parsing arbitrary ISO 8601 strings - it is only intended
853 as the inverse operation of :meth:`datetime.isoformat`.
854
855 .. versionadded:: 3.7
856
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000857.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000858
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300859 Return a :class:`.datetime` corresponding to *date_string*, parsed according to
Georg Brandl116aa622007-08-15 14:28:22 +0000860 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
861 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
862 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 -0400863 time tuple. For a complete list of formatting directives, see
864 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000865
Georg Brandl116aa622007-08-15 14:28:22 +0000866
Georg Brandl116aa622007-08-15 14:28:22 +0000867
868Class attributes:
869
Georg Brandl116aa622007-08-15 14:28:22 +0000870.. attribute:: datetime.min
871
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300872 The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1,
Georg Brandl116aa622007-08-15 14:28:22 +0000873 tzinfo=None)``.
874
875
876.. attribute:: datetime.max
877
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300878 The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
Georg Brandl116aa622007-08-15 14:28:22 +0000879 59, 999999, tzinfo=None)``.
880
881
882.. attribute:: datetime.resolution
883
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300884 The smallest possible difference between non-equal :class:`.datetime` objects,
Georg Brandl116aa622007-08-15 14:28:22 +0000885 ``timedelta(microseconds=1)``.
886
Georg Brandl116aa622007-08-15 14:28:22 +0000887
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000888Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000889
890.. attribute:: datetime.year
891
892 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
893
894
895.. attribute:: datetime.month
896
897 Between 1 and 12 inclusive.
898
899
900.. attribute:: datetime.day
901
902 Between 1 and the number of days in the given month of the given year.
903
904
905.. attribute:: datetime.hour
906
907 In ``range(24)``.
908
909
910.. attribute:: datetime.minute
911
912 In ``range(60)``.
913
914
915.. attribute:: datetime.second
916
917 In ``range(60)``.
918
919
920.. attribute:: datetime.microsecond
921
922 In ``range(1000000)``.
923
924
925.. attribute:: datetime.tzinfo
926
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300927 The object passed as the *tzinfo* argument to the :class:`.datetime` constructor,
Georg Brandl116aa622007-08-15 14:28:22 +0000928 or ``None`` if none was passed.
929
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000930
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400931.. attribute:: datetime.fold
932
933 In ``[0, 1]``. Used to disambiguate wall times during a repeated interval. (A
934 repeated interval occurs when clocks are rolled back at the end of daylight saving
935 time or when the UTC offset for the current zone is decreased for political reasons.)
936 The value 0 (1) represents the earlier (later) of the two moments with the same wall
937 time representation.
938
939 .. versionadded:: 3.6
940
Georg Brandl116aa622007-08-15 14:28:22 +0000941Supported operations:
942
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300943+---------------------------------------+--------------------------------+
944| Operation | Result |
945+=======================================+================================+
946| ``datetime2 = datetime1 + timedelta`` | \(1) |
947+---------------------------------------+--------------------------------+
948| ``datetime2 = datetime1 - timedelta`` | \(2) |
949+---------------------------------------+--------------------------------+
950| ``timedelta = datetime1 - datetime2`` | \(3) |
951+---------------------------------------+--------------------------------+
952| ``datetime1 < datetime2`` | Compares :class:`.datetime` to |
953| | :class:`.datetime`. (4) |
954+---------------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000955
956(1)
957 datetime2 is a duration of timedelta removed from datetime1, moving forward in
958 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
Martin Panter16c7cfd2016-04-01 21:48:24 +0000959 result has the same :attr:`~.datetime.tzinfo` attribute as the input datetime, and
Senthil Kumarana6bac952011-07-04 11:28:30 -0700960 datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
961 datetime2.year would be smaller than :const:`MINYEAR` or larger than
962 :const:`MAXYEAR`. Note that no time zone adjustments are done even if the
963 input is an aware object.
Georg Brandl116aa622007-08-15 14:28:22 +0000964
965(2)
966 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
Martin Panter16c7cfd2016-04-01 21:48:24 +0000967 addition, the result has the same :attr:`~.datetime.tzinfo` attribute as the input
Senthil Kumarana6bac952011-07-04 11:28:30 -0700968 datetime, and no time zone adjustments are done even if the input is aware.
Georg Brandl116aa622007-08-15 14:28:22 +0000969
970(3)
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300971 Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if
Georg Brandl116aa622007-08-15 14:28:22 +0000972 both operands are naive, or if both are aware. If one is aware and the other is
973 naive, :exc:`TypeError` is raised.
974
Martin Panter16c7cfd2016-04-01 21:48:24 +0000975 If both are naive, or both are aware and have the same :attr:`~.datetime.tzinfo` attribute,
976 the :attr:`~.datetime.tzinfo` attributes are ignored, and the result is a :class:`timedelta`
Georg Brandl116aa622007-08-15 14:28:22 +0000977 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
978 are done in this case.
979
Martin Panter16c7cfd2016-04-01 21:48:24 +0000980 If both are aware and have different :attr:`~.datetime.tzinfo` attributes, ``a-b`` acts
Senthil Kumarana6bac952011-07-04 11:28:30 -0700981 as if *a* and *b* were first converted to naive UTC datetimes first. The
982 result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
983 - b.utcoffset())`` except that the implementation never overflows.
Georg Brandl116aa622007-08-15 14:28:22 +0000984
985(4)
986 *datetime1* is considered less than *datetime2* when *datetime1* precedes
987 *datetime2* in time.
988
Alexander Belopolsky08313822012-06-15 20:19:47 -0400989 If one comparand is naive and the other is aware, :exc:`TypeError`
990 is raised if an order comparison is attempted. For equality
991 comparisons, naive instances are never equal to aware instances.
992
Martin Panter16c7cfd2016-04-01 21:48:24 +0000993 If both comparands are aware, and have the same :attr:`~.datetime.tzinfo` attribute, the
994 common :attr:`~.datetime.tzinfo` attribute is ignored and the base datetimes are
995 compared. If both comparands are aware and have different :attr:`~.datetime.tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -0700996 attributes, the comparands are first adjusted by subtracting their UTC
997 offsets (obtained from ``self.utcoffset()``).
Georg Brandl116aa622007-08-15 14:28:22 +0000998
Alexander Belopolsky08313822012-06-15 20:19:47 -0400999 .. versionchanged:: 3.3
Martin Panter16c7cfd2016-04-01 21:48:24 +00001000 Equality comparisons between naive and aware :class:`.datetime`
Éric Araujob0f08952012-06-24 16:22:09 -04001001 instances don't raise :exc:`TypeError`.
Alexander Belopolsky08313822012-06-15 20:19:47 -04001002
Georg Brandl116aa622007-08-15 14:28:22 +00001003 .. note::
1004
1005 In order to stop comparison from falling back to the default scheme of comparing
1006 object addresses, datetime comparison normally raises :exc:`TypeError` if the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001007 other comparand isn't also a :class:`.datetime` object. However,
Georg Brandl116aa622007-08-15 14:28:22 +00001008 ``NotImplemented`` is returned instead if the other comparand has a
1009 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001010 chance at implementing mixed-type comparison. If not, when a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +00001011 object is compared to an object of a different type, :exc:`TypeError` is raised
1012 unless the comparison is ``==`` or ``!=``. The latter cases return
1013 :const:`False` or :const:`True`, respectively.
1014
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001015:class:`.datetime` objects can be used as dictionary keys. In Boolean contexts,
1016all :class:`.datetime` objects are considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +00001017
1018Instance methods:
1019
Georg Brandl116aa622007-08-15 14:28:22 +00001020.. method:: datetime.date()
1021
1022 Return :class:`date` object with same year, month and day.
1023
1024
1025.. method:: datetime.time()
1026
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001027 Return :class:`.time` object with same hour, minute, second, microsecond and fold.
Martin Panter16c7cfd2016-04-01 21:48:24 +00001028 :attr:`.tzinfo` is ``None``. See also method :meth:`timetz`.
Georg Brandl116aa622007-08-15 14:28:22 +00001029
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001030 .. versionchanged:: 3.6
1031 The fold value is copied to the returned :class:`.time` object.
1032
Georg Brandl116aa622007-08-15 14:28:22 +00001033
1034.. method:: datetime.timetz()
1035
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001036 Return :class:`.time` object with same hour, minute, second, microsecond, fold, and
Senthil Kumarana6bac952011-07-04 11:28:30 -07001037 tzinfo attributes. See also method :meth:`time`.
Georg Brandl116aa622007-08-15 14:28:22 +00001038
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001039 .. versionchanged:: 3.6
1040 The fold value is copied to the returned :class:`.time` object.
Georg Brandl116aa622007-08-15 14:28:22 +00001041
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001042
1043.. method:: datetime.replace(year=self.year, month=self.month, day=self.day, \
1044 hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, \
1045 tzinfo=self.tzinfo, * fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001046
Senthil Kumarana6bac952011-07-04 11:28:30 -07001047 Return a datetime with the same attributes, except for those attributes given
1048 new values by whichever keyword arguments are specified. Note that
1049 ``tzinfo=None`` can be specified to create a naive datetime from an aware
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001050 datetime with no conversion of date and time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001051
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001052 .. versionadded:: 3.6
1053 Added the ``fold`` argument.
1054
Georg Brandl116aa622007-08-15 14:28:22 +00001055
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001056.. method:: datetime.astimezone(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001057
Martin Panter16c7cfd2016-04-01 21:48:24 +00001058 Return a :class:`.datetime` object with new :attr:`.tzinfo` attribute *tz*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001059 adjusting the date and time data so the result is the same UTC time as
Senthil Kumarana6bac952011-07-04 11:28:30 -07001060 *self*, but in *tz*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00001061
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001062 If provided, *tz* must be an instance of a :class:`tzinfo` subclass, and its
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001063 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. If *self*
Alexander Belopolsky877b2322018-06-10 17:02:58 -04001064 is naive, it is presumed to represent time in the system timezone.
Georg Brandl116aa622007-08-15 14:28:22 +00001065
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001066 If called without arguments (or with ``tz=None``) the system local
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001067 timezone is assumed for the target timezone. The ``.tzinfo`` attribute of the converted
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001068 datetime instance will be set to an instance of :class:`timezone`
1069 with the zone name and offset obtained from the OS.
1070
Georg Brandl116aa622007-08-15 14:28:22 +00001071 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001072 adjustment of date or time data is performed. Else the result is local
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001073 time in the timezone *tz*, representing the same UTC time as *self*: after
1074 ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will have
1075 the same date and time data as ``dt - dt.utcoffset()``.
Georg Brandl116aa622007-08-15 14:28:22 +00001076
1077 If you merely want to attach a time zone object *tz* to a datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001078 adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you
Georg Brandl116aa622007-08-15 14:28:22 +00001079 merely want to remove the time zone object from an aware datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001080 conversion of date and time data, use ``dt.replace(tzinfo=None)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001081
1082 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
1083 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
1084 Ignoring error cases, :meth:`astimezone` acts like::
1085
1086 def astimezone(self, tz):
1087 if self.tzinfo is tz:
1088 return self
1089 # Convert self to UTC, and attach the new time zone object.
1090 utc = (self - self.utcoffset()).replace(tzinfo=tz)
1091 # Convert from UTC to tz's local time.
1092 return tz.fromutc(utc)
1093
Georg Brandlee0be402012-06-26 09:14:40 +02001094 .. versionchanged:: 3.3
1095 *tz* now can be omitted.
1096
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001097 .. versionchanged:: 3.6
1098 The :meth:`astimezone` method can now be called on naive instances that
1099 are presumed to represent system local time.
1100
Georg Brandl116aa622007-08-15 14:28:22 +00001101
1102.. method:: datetime.utcoffset()
1103
Martin Panter16c7cfd2016-04-01 21:48:24 +00001104 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001105 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001106 return ``None`` or a :class:`timedelta` object with magnitude less than one day.
1107
1108 .. versionchanged:: 3.7
1109 The UTC offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001110
1111
1112.. method:: datetime.dst()
1113
Martin Panter16c7cfd2016-04-01 21:48:24 +00001114 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001115 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001116 ``None`` or a :class:`timedelta` object with magnitude less than one day.
1117
1118 .. versionchanged:: 3.7
1119 The DST offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001120
1121
1122.. method:: datetime.tzname()
1123
Martin Panter16c7cfd2016-04-01 21:48:24 +00001124 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001125 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
1126 ``None`` or a string object,
1127
1128
1129.. method:: datetime.timetuple()
1130
1131 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
1132 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
Alexander Belopolsky64912482010-06-08 18:59:20 +00001133 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
1134 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
1135 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
Martin Panter16c7cfd2016-04-01 21:48:24 +00001136 of the result is set according to the :meth:`dst` method: :attr:`.tzinfo` is
Georg Brandl682d7e02010-10-06 10:26:05 +00001137 ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
Alexander Belopolsky64912482010-06-08 18:59:20 +00001138 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
Alexander Belopolskyda62f2f2010-06-09 17:11:01 +00001139 else :attr:`tm_isdst` is set to ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +00001140
1141
1142.. method:: datetime.utctimetuple()
1143
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001144 If :class:`.datetime` instance *d* is naive, this is the same as
Georg Brandl116aa622007-08-15 14:28:22 +00001145 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
1146 ``d.dst()`` returns. DST is never in effect for a UTC time.
1147
1148 If *d* is aware, *d* is normalized to UTC time, by subtracting
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00001149 ``d.utcoffset()``, and a :class:`time.struct_time` for the
1150 normalized time is returned. :attr:`tm_isdst` is forced to 0. Note
1151 that an :exc:`OverflowError` may be raised if *d*.year was
1152 ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
Georg Brandl116aa622007-08-15 14:28:22 +00001153 boundary.
1154
1155
1156.. method:: datetime.toordinal()
1157
1158 Return the proleptic Gregorian ordinal of the date. The same as
1159 ``self.date().toordinal()``.
1160
Alexander Belopolskya4415142012-06-08 12:33:09 -04001161.. method:: datetime.timestamp()
1162
Martin Panter16c7cfd2016-04-01 21:48:24 +00001163 Return POSIX timestamp corresponding to the :class:`.datetime`
Alexander Belopolskya4415142012-06-08 12:33:09 -04001164 instance. The return value is a :class:`float` similar to that
1165 returned by :func:`time.time`.
1166
Martin Panter16c7cfd2016-04-01 21:48:24 +00001167 Naive :class:`.datetime` instances are assumed to represent local
Alexander Belopolskya4415142012-06-08 12:33:09 -04001168 time and this method relies on the platform C :c:func:`mktime`
Martin Panter16c7cfd2016-04-01 21:48:24 +00001169 function to perform the conversion. Since :class:`.datetime`
Alexander Belopolskya4415142012-06-08 12:33:09 -04001170 supports wider range of values than :c:func:`mktime` on many
1171 platforms, this method may raise :exc:`OverflowError` for times far
1172 in the past or far in the future.
1173
Martin Panter16c7cfd2016-04-01 21:48:24 +00001174 For aware :class:`.datetime` instances, the return value is computed
Alexander Belopolskya4415142012-06-08 12:33:09 -04001175 as::
1176
1177 (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
1178
1179 .. versionadded:: 3.3
1180
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001181 .. versionchanged:: 3.6
1182 The :meth:`timestamp` method uses the :attr:`.fold` attribute to
1183 disambiguate the times during a repeated interval.
1184
Alexander Belopolskya4415142012-06-08 12:33:09 -04001185 .. note::
1186
1187 There is no method to obtain the POSIX timestamp directly from a
Martin Panter16c7cfd2016-04-01 21:48:24 +00001188 naive :class:`.datetime` instance representing UTC time. If your
Alexander Belopolskya4415142012-06-08 12:33:09 -04001189 application uses this convention and your system timezone is not
1190 set to UTC, you can obtain the POSIX timestamp by supplying
1191 ``tzinfo=timezone.utc``::
1192
1193 timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
1194
1195 or by calculating the timestamp directly::
1196
1197 timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001198
1199.. method:: datetime.weekday()
1200
1201 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
1202 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
1203
1204
1205.. method:: datetime.isoweekday()
1206
1207 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
1208 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
1209 :meth:`isocalendar`.
1210
1211
1212.. method:: datetime.isocalendar()
1213
1214 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
1215 ``self.date().isocalendar()``.
1216
1217
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001218.. method:: datetime.isoformat(sep='T', timespec='auto')
Georg Brandl116aa622007-08-15 14:28:22 +00001219
1220 Return a string representing the date and time in ISO 8601 format,
Christophe Nanteuil92878822018-10-06 00:57:02 +02001221 YYYY-MM-DDTHH:MM:SS.ffffff or, if :attr:`microsecond` is 0,
Georg Brandl116aa622007-08-15 14:28:22 +00001222 YYYY-MM-DDTHH:MM:SS
1223
Christophe Nanteuil92878822018-10-06 00:57:02 +02001224 If :meth:`utcoffset` does not return ``None``, a string is
1225 appended, giving the UTC offset:
1226 YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]] or, if :attr:`microsecond`
1227 is 0 YYYY-MM-DDTHH:MM:SS+HH:MM[:SS[.ffffff]].
Georg Brandl116aa622007-08-15 14:28:22 +00001228
1229 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +00001230 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +00001231
1232 >>> from datetime import tzinfo, timedelta, datetime
1233 >>> class TZ(tzinfo):
1234 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1235 ...
1236 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1237 '2002-12-25 00:00:00-06:39'
1238
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001239 The optional argument *timespec* specifies the number of additional
1240 components of the time to include (the default is ``'auto'``).
1241 It can be one of the following:
1242
1243 - ``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0,
1244 same as ``'microseconds'`` otherwise.
1245 - ``'hours'``: Include the :attr:`hour` in the two-digit HH format.
1246 - ``'minutes'``: Include :attr:`hour` and :attr:`minute` in HH:MM format.
1247 - ``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second`
1248 in HH:MM:SS format.
1249 - ``'milliseconds'``: Include full time, but truncate fractional second
1250 part to milliseconds. HH:MM:SS.sss format.
Christophe Nanteuil92878822018-10-06 00:57:02 +02001251 - ``'microseconds'``: Include full time in HH:MM:SS.ffffff format.
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001252
1253 .. note::
1254
1255 Excluded time components are truncated, not rounded.
1256
1257 :exc:`ValueError` will be raised on an invalid *timespec* argument.
1258
1259
1260 >>> from datetime import datetime
Marco Buttu909a6f62017-03-18 17:59:33 +01001261 >>> datetime.now().isoformat(timespec='minutes') # doctest: +SKIP
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001262 '2002-12-25T00:00'
1263 >>> dt = datetime(2015, 1, 1, 12, 30, 59, 0)
1264 >>> dt.isoformat(timespec='microseconds')
1265 '2015-01-01T12:30:59.000000'
1266
1267 .. versionadded:: 3.6
1268 Added the *timespec* argument.
1269
Georg Brandl116aa622007-08-15 14:28:22 +00001270
1271.. method:: datetime.__str__()
1272
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001273 For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to
Georg Brandl116aa622007-08-15 14:28:22 +00001274 ``d.isoformat(' ')``.
1275
1276
1277.. method:: datetime.ctime()
1278
1279 Return a string representing the date and time, for example ``datetime(2002, 12,
1280 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1281 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
Georg Brandl60203b42010-10-06 10:11:56 +00001282 native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +00001283 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1284
1285
1286.. method:: datetime.strftime(format)
1287
1288 Return a string representing the date and time, controlled by an explicit format
David Wolever569a5fa2013-08-12 16:56:02 -04001289 string. For a complete list of formatting directives, see
1290 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001291
Georg Brandl116aa622007-08-15 14:28:22 +00001292
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001293.. method:: datetime.__format__(format)
1294
Martin Panterd5db1472016-02-08 01:34:09 +00001295 Same as :meth:`.datetime.strftime`. This makes it possible to specify a format
Martin Panterbc1ee462016-02-13 00:41:37 +00001296 string for a :class:`.datetime` object in :ref:`formatted string
1297 literals <f-strings>` and when using :meth:`str.format`. For a
David Wolever569a5fa2013-08-12 16:56:02 -04001298 complete list of formatting directives, see
1299 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001300
1301
Christian Heimesfe337bf2008-03-23 21:54:12 +00001302Examples of working with datetime objects:
1303
1304.. doctest::
1305
Christian Heimes895627f2007-12-08 17:28:33 +00001306 >>> from datetime import datetime, date, time
1307 >>> # Using datetime.combine()
1308 >>> d = date(2005, 7, 14)
1309 >>> t = time(12, 30)
1310 >>> datetime.combine(d, t)
1311 datetime.datetime(2005, 7, 14, 12, 30)
1312 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001313 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001314 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001315 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001316 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1317 >>> # Using datetime.strptime()
1318 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1319 >>> dt
1320 datetime.datetime(2006, 11, 21, 16, 30)
1321 >>> # Using datetime.timetuple() to get tuple of all attributes
1322 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001323 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001324 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001325 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001326 2006 # year
1327 11 # month
1328 21 # day
1329 16 # hour
1330 30 # minute
1331 0 # second
1332 1 # weekday (0 = Monday)
1333 325 # number of days since 1st January
1334 -1 # dst - method tzinfo.dst() returned None
1335 >>> # Date in ISO format
1336 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001337 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001338 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001339 ...
1340 2006 # ISO year
1341 47 # ISO week
1342 2 # ISO weekday
1343 >>> # Formatting datetime
1344 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1345 'Tuesday, 21. November 2006 04:30PM'
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001346 >>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
1347 'The day is 21, the month is November, the time is 04:30PM.'
Christian Heimes895627f2007-12-08 17:28:33 +00001348
Christian Heimesfe337bf2008-03-23 21:54:12 +00001349Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001350
1351 >>> from datetime import timedelta, datetime, tzinfo
1352 >>> class GMT1(tzinfo):
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001353 ... def utcoffset(self, dt):
1354 ... return timedelta(hours=1) + self.dst(dt)
1355 ... def dst(self, dt):
1356 ... # DST starts last Sunday in March
Christian Heimes895627f2007-12-08 17:28:33 +00001357 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1358 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001359 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001360 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001361 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1362 ... return timedelta(hours=1)
1363 ... else:
1364 ... return timedelta(0)
1365 ... def tzname(self,dt):
1366 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001367 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001368 >>> class GMT2(tzinfo):
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001369 ... def utcoffset(self, dt):
1370 ... return timedelta(hours=2) + self.dst(dt)
1371 ... def dst(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001372 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001373 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001374 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001375 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001376 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001377 ... return timedelta(hours=1)
Christian Heimes895627f2007-12-08 17:28:33 +00001378 ... else:
1379 ... return timedelta(0)
1380 ... def tzname(self,dt):
1381 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001382 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001383 >>> gmt1 = GMT1()
1384 >>> # Daylight Saving Time
1385 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1386 >>> dt1.dst()
1387 datetime.timedelta(0)
1388 >>> dt1.utcoffset()
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +02001389 datetime.timedelta(seconds=3600)
Christian Heimes895627f2007-12-08 17:28:33 +00001390 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1391 >>> dt2.dst()
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +02001392 datetime.timedelta(seconds=3600)
Christian Heimes895627f2007-12-08 17:28:33 +00001393 >>> dt2.utcoffset()
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +02001394 datetime.timedelta(seconds=7200)
Christian Heimes895627f2007-12-08 17:28:33 +00001395 >>> # Convert datetime to another time zone
1396 >>> dt3 = dt2.astimezone(GMT2())
1397 >>> dt3 # doctest: +ELLIPSIS
1398 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1399 >>> dt2 # doctest: +ELLIPSIS
1400 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1401 >>> dt2.utctimetuple() == dt3.utctimetuple()
1402 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001403
Christian Heimes895627f2007-12-08 17:28:33 +00001404
Georg Brandl116aa622007-08-15 14:28:22 +00001405
1406.. _datetime-time:
1407
Serhiy Storchakaee1b01a2016-12-02 23:13:53 +02001408:class:`.time` Objects
1409----------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001410
1411A time object represents a (local) time of day, independent of any particular
1412day, and subject to adjustment via a :class:`tzinfo` object.
1413
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001414.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001415
1416 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001417 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001418 following ranges:
1419
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001420 * ``0 <= hour < 24``,
1421 * ``0 <= minute < 60``,
1422 * ``0 <= second < 60``,
1423 * ``0 <= microsecond < 1000000``,
1424 * ``fold in [0, 1]``.
Georg Brandl116aa622007-08-15 14:28:22 +00001425
1426 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1427 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1428
1429Class attributes:
1430
1431
1432.. attribute:: time.min
1433
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001434 The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001435
1436
1437.. attribute:: time.max
1438
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001439 The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001440
1441
1442.. attribute:: time.resolution
1443
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001444 The smallest possible difference between non-equal :class:`.time` objects,
1445 ``timedelta(microseconds=1)``, although note that arithmetic on
1446 :class:`.time` objects is not supported.
Georg Brandl116aa622007-08-15 14:28:22 +00001447
Georg Brandl116aa622007-08-15 14:28:22 +00001448
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001449Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001450
1451.. attribute:: time.hour
1452
1453 In ``range(24)``.
1454
1455
1456.. attribute:: time.minute
1457
1458 In ``range(60)``.
1459
1460
1461.. attribute:: time.second
1462
1463 In ``range(60)``.
1464
1465
1466.. attribute:: time.microsecond
1467
1468 In ``range(1000000)``.
1469
1470
1471.. attribute:: time.tzinfo
1472
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001473 The object passed as the tzinfo argument to the :class:`.time` constructor, or
Georg Brandl116aa622007-08-15 14:28:22 +00001474 ``None`` if none was passed.
1475
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001476
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001477.. attribute:: time.fold
1478
1479 In ``[0, 1]``. Used to disambiguate wall times during a repeated interval. (A
1480 repeated interval occurs when clocks are rolled back at the end of daylight saving
1481 time or when the UTC offset for the current zone is decreased for political reasons.)
1482 The value 0 (1) represents the earlier (later) of the two moments with the same wall
1483 time representation.
1484
1485 .. versionadded:: 3.6
1486
1487
Georg Brandl116aa622007-08-15 14:28:22 +00001488Supported operations:
1489
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001490* comparison of :class:`.time` to :class:`.time`, where *a* is considered less
Georg Brandl116aa622007-08-15 14:28:22 +00001491 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
Alexander Belopolsky08313822012-06-15 20:19:47 -04001492 is aware, :exc:`TypeError` is raised if an order comparison is attempted. For equality
1493 comparisons, naive instances are never equal to aware instances.
1494
1495 If both comparands are aware, and have
Martin Panter16c7cfd2016-04-01 21:48:24 +00001496 the same :attr:`~time.tzinfo` attribute, the common :attr:`~time.tzinfo` attribute is
Senthil Kumarana6bac952011-07-04 11:28:30 -07001497 ignored and the base times are compared. If both comparands are aware and
Martin Panter16c7cfd2016-04-01 21:48:24 +00001498 have different :attr:`~time.tzinfo` attributes, the comparands are first adjusted by
Senthil Kumarana6bac952011-07-04 11:28:30 -07001499 subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
1500 to stop mixed-type comparisons from falling back to the default comparison by
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001501 object address, when a :class:`.time` object is compared to an object of a
Senthil Kumaran3aac1792011-07-04 11:43:51 -07001502 different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
Senthil Kumarana6bac952011-07-04 11:28:30 -07001503 ``!=``. The latter cases return :const:`False` or :const:`True`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +00001504
Alexander Belopolsky08313822012-06-15 20:19:47 -04001505 .. versionchanged:: 3.3
Serhiy Storchakaee1b01a2016-12-02 23:13:53 +02001506 Equality comparisons between naive and aware :class:`~datetime.time` instances
Éric Araujob0f08952012-06-24 16:22:09 -04001507 don't raise :exc:`TypeError`.
Alexander Belopolsky08313822012-06-15 20:19:47 -04001508
Georg Brandl116aa622007-08-15 14:28:22 +00001509* hash, use as dict key
1510
1511* efficient pickling
1512
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05001513In boolean contexts, a :class:`.time` object is always considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +00001514
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05001515.. versionchanged:: 3.5
1516 Before Python 3.5, a :class:`.time` object was considered to be false if it
1517 represented midnight in UTC. This behavior was considered obscure and
1518 error-prone and has been removed in Python 3.5. See :issue:`13936` for full
1519 details.
Georg Brandl116aa622007-08-15 14:28:22 +00001520
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001521
1522Other constructor:
1523
1524.. classmethod:: time.fromisoformat(time_string)
1525
1526 Return a :class:`time` corresponding to a *time_string* in one of the
1527 formats emitted by :meth:`time.isoformat`. Specifically, this function supports
Christophe Nanteuil92878822018-10-06 00:57:02 +02001528 strings in the format(s) ``HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]``.
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001529
1530 .. caution::
1531
1532 This does not support parsing arbitrary ISO 8601 strings - it is only intended
1533 as the inverse operation of :meth:`time.isoformat`.
1534
1535 .. versionadded:: 3.7
1536
1537
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001538Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001539
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001540.. method:: time.replace(hour=self.hour, minute=self.minute, second=self.second, \
1541 microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001542
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001543 Return a :class:`.time` with the same value, except for those attributes given
Senthil Kumarana6bac952011-07-04 11:28:30 -07001544 new values by whichever keyword arguments are specified. Note that
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001545 ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
1546 aware :class:`.time`, without conversion of the time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001547
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001548 .. versionadded:: 3.6
1549 Added the ``fold`` argument.
1550
Georg Brandl116aa622007-08-15 14:28:22 +00001551
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001552.. method:: time.isoformat(timespec='auto')
Georg Brandl116aa622007-08-15 14:28:22 +00001553
Christophe Nanteuil92878822018-10-06 00:57:02 +02001554 Return a string representing the time in ISO 8601 format, HH:MM:SS.ffffff or, if
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001555 :attr:`microsecond` is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
Christophe Nanteuil92878822018-10-06 00:57:02 +02001556 string is appended, giving the UTC offset: HH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]
1557 or, if self.microsecond is 0, HH:MM:SS+HH:MM[:SS[.ffffff]].
Georg Brandl116aa622007-08-15 14:28:22 +00001558
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001559 The optional argument *timespec* specifies the number of additional
1560 components of the time to include (the default is ``'auto'``).
1561 It can be one of the following:
1562
1563 - ``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0,
1564 same as ``'microseconds'`` otherwise.
1565 - ``'hours'``: Include the :attr:`hour` in the two-digit HH format.
1566 - ``'minutes'``: Include :attr:`hour` and :attr:`minute` in HH:MM format.
1567 - ``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second`
1568 in HH:MM:SS format.
1569 - ``'milliseconds'``: Include full time, but truncate fractional second
1570 part to milliseconds. HH:MM:SS.sss format.
Christophe Nanteuil92878822018-10-06 00:57:02 +02001571 - ``'microseconds'``: Include full time in HH:MM:SS.ffffff format.
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001572
1573 .. note::
1574
1575 Excluded time components are truncated, not rounded.
1576
1577 :exc:`ValueError` will be raised on an invalid *timespec* argument.
1578
1579
1580 >>> from datetime import time
Berker Peksag94f89a62016-06-04 21:36:53 -07001581 >>> time(hour=12, minute=34, second=56, microsecond=123456).isoformat(timespec='minutes')
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001582 '12:34'
Berker Peksag94f89a62016-06-04 21:36:53 -07001583 >>> dt = time(hour=12, minute=34, second=56, microsecond=0)
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001584 >>> dt.isoformat(timespec='microseconds')
1585 '12:34:56.000000'
1586 >>> dt.isoformat(timespec='auto')
1587 '12:34:56'
1588
1589 .. versionadded:: 3.6
1590 Added the *timespec* argument.
1591
Georg Brandl116aa622007-08-15 14:28:22 +00001592
1593.. method:: time.__str__()
1594
1595 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1596
1597
1598.. method:: time.strftime(format)
1599
David Wolever569a5fa2013-08-12 16:56:02 -04001600 Return a string representing the time, controlled by an explicit format
1601 string. For a complete list of formatting directives, see
David Woleverbbf4a462013-08-12 17:15:36 -04001602 :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001603
1604
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001605.. method:: time.__format__(format)
1606
Martin Panterd5db1472016-02-08 01:34:09 +00001607 Same as :meth:`.time.strftime`. This makes it possible to specify a format string
Martin Panterbc1ee462016-02-13 00:41:37 +00001608 for a :class:`.time` object in :ref:`formatted string
1609 literals <f-strings>` and when using :meth:`str.format`. For a
David Wolever569a5fa2013-08-12 16:56:02 -04001610 complete list of formatting directives, see
1611 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001612
1613
Georg Brandl116aa622007-08-15 14:28:22 +00001614.. method:: time.utcoffset()
1615
Martin Panter16c7cfd2016-04-01 21:48:24 +00001616 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001617 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001618 return ``None`` or a :class:`timedelta` object with magnitude less than one day.
1619
1620 .. versionchanged:: 3.7
1621 The UTC offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001622
1623
1624.. method:: time.dst()
1625
Martin Panter16c7cfd2016-04-01 21:48:24 +00001626 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001627 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001628 ``None``, or a :class:`timedelta` object with magnitude less than one day.
Georg Brandl116aa622007-08-15 14:28:22 +00001629
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001630 .. versionchanged:: 3.7
1631 The DST offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001632
1633.. method:: time.tzname()
1634
Martin Panter16c7cfd2016-04-01 21:48:24 +00001635 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001636 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1637 return ``None`` or a string object.
1638
Christian Heimesfe337bf2008-03-23 21:54:12 +00001639Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001640
Xiang Zhang6721c7c2016-12-27 12:23:59 +08001641 >>> from datetime import time, tzinfo, timedelta
Christian Heimes895627f2007-12-08 17:28:33 +00001642 >>> class GMT1(tzinfo):
1643 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001644 ... return timedelta(hours=1)
1645 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001646 ... return timedelta(0)
1647 ... def tzname(self,dt):
1648 ... return "Europe/Prague"
1649 ...
1650 >>> t = time(12, 10, 30, tzinfo=GMT1())
1651 >>> t # doctest: +ELLIPSIS
1652 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1653 >>> gmt = GMT1()
1654 >>> t.isoformat()
1655 '12:10:30+01:00'
1656 >>> t.dst()
1657 datetime.timedelta(0)
1658 >>> t.tzname()
1659 'Europe/Prague'
1660 >>> t.strftime("%H:%M:%S %Z")
1661 '12:10:30 Europe/Prague'
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001662 >>> 'The {} is {:%H:%M}.'.format("time", t)
1663 'The time is 12:10.'
Christian Heimes895627f2007-12-08 17:28:33 +00001664
Georg Brandl116aa622007-08-15 14:28:22 +00001665
1666.. _datetime-tzinfo:
1667
1668:class:`tzinfo` Objects
1669-----------------------
1670
Martin Panter16c7cfd2016-04-01 21:48:24 +00001671.. class:: tzinfo()
Georg Brandl116aa622007-08-15 14:28:22 +00001672
Martin Panter16c7cfd2016-04-01 21:48:24 +00001673 This is an abstract base class, meaning that this class should not be
1674 instantiated directly. You need to derive a concrete subclass, and (at least)
1675 supply implementations of the standard :class:`tzinfo` methods needed by the
1676 :class:`.datetime` methods you use. The :mod:`datetime` module supplies
1677 a simple concrete subclass of :class:`tzinfo`, :class:`timezone`, which can represent
1678 timezones with fixed offset from UTC such as UTC itself or North American EST and
1679 EDT.
Georg Brandl116aa622007-08-15 14:28:22 +00001680
Martin Panter16c7cfd2016-04-01 21:48:24 +00001681 An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1682 constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
1683 view their attributes as being in local time, and the :class:`tzinfo` object
1684 supports methods revealing offset of local time from UTC, the name of the time
1685 zone, and DST offset, all relative to a date or time object passed to them.
Georg Brandl116aa622007-08-15 14:28:22 +00001686
Martin Panter16c7cfd2016-04-01 21:48:24 +00001687 Special requirement for pickling: A :class:`tzinfo` subclass must have an
1688 :meth:`__init__` method that can be called with no arguments, else it can be
1689 pickled but possibly not unpickled again. This is a technical requirement that
1690 may be relaxed in the future.
1691
1692 A concrete subclass of :class:`tzinfo` may need to implement the following
1693 methods. Exactly which methods are needed depends on the uses made of aware
1694 :mod:`datetime` objects. If in doubt, simply implement all of them.
Georg Brandl116aa622007-08-15 14:28:22 +00001695
1696
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001697.. method:: tzinfo.utcoffset(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001698
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001699 Return offset of local time from UTC, as a :class:`timedelta` object that is
1700 positive east of UTC. If local time is
Georg Brandl116aa622007-08-15 14:28:22 +00001701 west of UTC, this should be negative. Note that this is intended to be the
1702 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1703 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1704 the UTC offset isn't known, return ``None``. Else the value returned must be a
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001705 :class:`timedelta` object strictly between ``-timedelta(hours=24)`` and
1706 ``timedelta(hours=24)`` (the magnitude of the offset must be less
Georg Brandl116aa622007-08-15 14:28:22 +00001707 than one day). Most implementations of :meth:`utcoffset` will probably look
1708 like one of these two::
1709
1710 return CONSTANT # fixed-offset class
1711 return CONSTANT + self.dst(dt) # daylight-aware class
1712
1713 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1714 ``None`` either.
1715
1716 The default implementation of :meth:`utcoffset` raises
1717 :exc:`NotImplementedError`.
1718
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001719 .. versionchanged:: 3.7
1720 The UTC offset is not restricted to a whole number of minutes.
1721
Georg Brandl116aa622007-08-15 14:28:22 +00001722
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001723.. method:: tzinfo.dst(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001724
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001725 Return the daylight saving time (DST) adjustment, as a :class:`timedelta`
1726 object or
Georg Brandl116aa622007-08-15 14:28:22 +00001727 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1728 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1729 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1730 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1731 no need to consult :meth:`dst` unless you're interested in obtaining DST info
Martin Panter16c7cfd2016-04-01 21:48:24 +00001732 separately. For example, :meth:`datetime.timetuple` calls its :attr:`~.datetime.tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -07001733 attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
1734 should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
1735 DST changes when crossing time zones.
Georg Brandl116aa622007-08-15 14:28:22 +00001736
1737 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1738 daylight times must be consistent in this sense:
1739
1740 ``tz.utcoffset(dt) - tz.dst(dt)``
1741
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001742 must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo ==
Georg Brandl116aa622007-08-15 14:28:22 +00001743 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1744 zone's "standard offset", which should not depend on the date or the time, but
1745 only on geographic location. The implementation of :meth:`datetime.astimezone`
1746 relies on this, but cannot detect violations; it's the programmer's
1747 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1748 this, it may be able to override the default implementation of
1749 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1750
1751 Most implementations of :meth:`dst` will probably look like one of these two::
1752
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001753 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001754 # a fixed-offset class: doesn't account for DST
1755 return timedelta(0)
1756
1757 or ::
1758
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001759 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001760 # Code to set dston and dstoff to the time zone's DST
1761 # transition times based on the input dt.year, and expressed
1762 # in standard local time. Then
1763
1764 if dston <= dt.replace(tzinfo=None) < dstoff:
1765 return timedelta(hours=1)
1766 else:
1767 return timedelta(0)
1768
1769 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1770
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001771 .. versionchanged:: 3.7
1772 The DST offset is not restricted to a whole number of minutes.
1773
Georg Brandl116aa622007-08-15 14:28:22 +00001774
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001775.. method:: tzinfo.tzname(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001776
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001777 Return the time zone name corresponding to the :class:`.datetime` object *dt*, as
Georg Brandl116aa622007-08-15 14:28:22 +00001778 a string. Nothing about string names is defined by the :mod:`datetime` module,
1779 and there's no requirement that it mean anything in particular. For example,
1780 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1781 valid replies. Return ``None`` if a string name isn't known. Note that this is
1782 a method rather than a fixed string primarily because some :class:`tzinfo`
1783 subclasses will wish to return different names depending on the specific value
1784 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1785 daylight time.
1786
1787 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1788
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001789
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001790These methods are called by a :class:`.datetime` or :class:`.time` object, in
1791response to their methods of the same names. A :class:`.datetime` object passes
1792itself as the argument, and a :class:`.time` object passes ``None`` as the
Georg Brandl116aa622007-08-15 14:28:22 +00001793argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001794accept a *dt* argument of ``None``, or of class :class:`.datetime`.
Georg Brandl116aa622007-08-15 14:28:22 +00001795
1796When ``None`` is passed, it's up to the class designer to decide the best
1797response. For example, returning ``None`` is appropriate if the class wishes to
1798say that time objects don't participate in the :class:`tzinfo` protocols. It
1799may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1800there is no other convention for discovering the standard offset.
1801
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001802When a :class:`.datetime` object is passed in response to a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +00001803method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1804rely on this, unless user code calls :class:`tzinfo` methods directly. The
1805intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1806time, and not need worry about objects in other timezones.
1807
1808There is one more :class:`tzinfo` method that a subclass may wish to override:
1809
1810
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001811.. method:: tzinfo.fromutc(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001812
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001813 This is called from the default :class:`datetime.astimezone()`
1814 implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s
1815 date and time data are to be viewed as expressing a UTC time. The purpose
1816 of :meth:`fromutc` is to adjust the date and time data, returning an
Senthil Kumarana6bac952011-07-04 11:28:30 -07001817 equivalent datetime in *self*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00001818
1819 Most :class:`tzinfo` subclasses should be able to inherit the default
1820 :meth:`fromutc` implementation without problems. It's strong enough to handle
1821 fixed-offset time zones, and time zones accounting for both standard and
1822 daylight time, and the latter even if the DST transition times differ in
1823 different years. An example of a time zone the default :meth:`fromutc`
1824 implementation may not handle correctly in all cases is one where the standard
1825 offset (from UTC) depends on the specific date and time passed, which can happen
1826 for political reasons. The default implementations of :meth:`astimezone` and
1827 :meth:`fromutc` may not produce the result you want if the result is one of the
1828 hours straddling the moment the standard offset changes.
1829
1830 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1831 like::
1832
1833 def fromutc(self, dt):
1834 # raise ValueError error if dt.tzinfo is not self
1835 dtoff = dt.utcoffset()
1836 dtdst = dt.dst()
1837 # raise ValueError if dtoff is None or dtdst is None
1838 delta = dtoff - dtdst # this is self's standard offset
1839 if delta:
1840 dt += delta # convert to standard local time
1841 dtdst = dt.dst()
1842 # raise ValueError if dtdst is None
1843 if dtdst:
1844 return dt + dtdst
1845 else:
1846 return dt
1847
Marco Buttu909a6f62017-03-18 17:59:33 +01001848In the following :download:`tzinfo_examples.py
1849<../includes/tzinfo_examples.py>` file there are some examples of
1850:class:`tzinfo` classes:
Georg Brandl116aa622007-08-15 14:28:22 +00001851
Marco Buttu909a6f62017-03-18 17:59:33 +01001852.. literalinclude:: ../includes/tzinfo_examples.py
Georg Brandl116aa622007-08-15 14:28:22 +00001853
Georg Brandl116aa622007-08-15 14:28:22 +00001854Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1855subclass accounting for both standard and daylight time, at the DST transition
1856points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00001857minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
18581:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001859
1860 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1861 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1862 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1863
1864 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1865
1866 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1867
1868When DST starts (the "start" line), the local wall clock leaps from 1:59 to
18693:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1870``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001871begins. For example, at the Spring forward transition of 2016, we get
1872
Marco Buttu909a6f62017-03-18 17:59:33 +01001873 >>> from datetime import datetime, timezone
1874 >>> from tzinfo_examples import HOUR, Eastern
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001875 >>> u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc)
1876 >>> for i in range(4):
1877 ... u = u0 + i*HOUR
1878 ... t = u.astimezone(Eastern)
1879 ... print(u.time(), 'UTC =', t.time(), t.tzname())
1880 ...
1881 05:00:00 UTC = 00:00:00 EST
1882 06:00:00 UTC = 01:00:00 EST
1883 07:00:00 UTC = 03:00:00 EDT
1884 08:00:00 UTC = 04:00:00 EDT
1885
Georg Brandl116aa622007-08-15 14:28:22 +00001886
1887When DST ends (the "end" line), there's a potentially worse problem: there's an
1888hour that can't be spelled unambiguously in local wall time: the last hour of
1889daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1890daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1891to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1892:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1893hours into the same local hour then. In the Eastern example, UTC times of the
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001894form 5:MM and 6:MM both map to 1:MM when converted to Eastern, but earlier times
1895have the :attr:`~datetime.fold` attribute set to 0 and the later times have it set to 1.
1896For example, at the Fall back transition of 2016, we get
Georg Brandl116aa622007-08-15 14:28:22 +00001897
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001898 >>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
1899 >>> for i in range(4):
1900 ... u = u0 + i*HOUR
1901 ... t = u.astimezone(Eastern)
1902 ... print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
1903 ...
1904 04:00:00 UTC = 00:00:00 EDT 0
1905 05:00:00 UTC = 01:00:00 EDT 0
1906 06:00:00 UTC = 01:00:00 EST 1
1907 07:00:00 UTC = 02:00:00 EST 0
1908
1909Note that the :class:`datetime` instances that differ only by the value of the
1910:attr:`~datetime.fold` attribute are considered equal in comparisons.
1911
1912Applications that can't bear wall-time ambiguities should explicitly check the
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001913value of the :attr:`~datetime.fold` attribute or avoid using hybrid
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001914:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`,
1915or any other fixed-offset :class:`tzinfo` subclass (such as a class representing
1916only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
1917
Sandro Tosid11d0d62012-04-24 19:46:06 +02001918.. seealso::
1919
wim glenn53f2af12017-06-06 12:54:41 -05001920 `dateutil.tz <https://dateutil.readthedocs.io/en/stable/tz.html>`_
Benjamin Peterson9b29acd2014-06-22 16:26:39 -07001921 The standard library has :class:`timezone` class for handling arbitrary
1922 fixed offsets from UTC and :attr:`timezone.utc` as UTC timezone instance.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001923
wim glenn53f2af12017-06-06 12:54:41 -05001924 *dateutil.tz* library brings the *IANA timezone database* (also known as the
Benjamin Peterson9b29acd2014-06-22 16:26:39 -07001925 Olson database) to Python and its usage is recommended.
Sandro Tosi100b8892012-04-28 11:19:37 +02001926
Serhiy Storchaka6dff0202016-05-07 10:49:07 +03001927 `IANA timezone database <https://www.iana.org/time-zones>`_
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001928 The Time Zone Database (often called tz, tzdata or zoneinfo) contains code and
Sandro Tosi100b8892012-04-28 11:19:37 +02001929 data that represent the history of local time for many representative
1930 locations around the globe. It is updated periodically to reflect changes
1931 made by political bodies to time zone boundaries, UTC offsets, and
1932 daylight-saving rules.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001933
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001934
1935.. _datetime-timezone:
1936
1937:class:`timezone` Objects
1938--------------------------
1939
Alexander Belopolsky6d3c9a62011-05-04 10:28:26 -04001940The :class:`timezone` class is a subclass of :class:`tzinfo`, each
1941instance of which represents a timezone defined by a fixed offset from
1942UTC. Note that objects of this class cannot be used to represent
1943timezone information in the locations where different offsets are used
1944in different days of the year or where historical changes have been
1945made to civil time.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001946
1947
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001948.. class:: timezone(offset, name=None)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001949
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001950 The *offset* argument must be specified as a :class:`timedelta`
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001951 object representing the difference between the local time and UTC. It must
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001952 be strictly between ``-timedelta(hours=24)`` and
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001953 ``timedelta(hours=24)``, otherwise :exc:`ValueError` is raised.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001954
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001955 The *name* argument is optional. If specified it must be a string that
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04001956 will be used as the value returned by the :meth:`datetime.tzname` method.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001957
Benjamin Peterson9b29acd2014-06-22 16:26:39 -07001958 .. versionadded:: 3.2
1959
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001960 .. versionchanged:: 3.7
1961 The UTC offset is not restricted to a whole number of minutes.
1962
1963
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001964.. method:: timezone.utcoffset(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001965
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001966 Return the fixed value specified when the :class:`timezone` instance is
1967 constructed. The *dt* argument is ignored. The return value is a
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001968 :class:`timedelta` instance equal to the difference between the
1969 local time and UTC.
1970
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001971 .. versionchanged:: 3.7
1972 The UTC offset is not restricted to a whole number of minutes.
1973
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001974.. method:: timezone.tzname(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001975
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04001976 Return the fixed value specified when the :class:`timezone` instance
1977 is constructed. If *name* is not provided in the constructor, the
1978 name returned by ``tzname(dt)`` is generated from the value of the
1979 ``offset`` as follows. If *offset* is ``timedelta(0)``, the name
1980 is "UTC", otherwise it is a string 'UTC±HH:MM', where ± is the sign
1981 of ``offset``, HH and MM are two digits of ``offset.hours`` and
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001982 ``offset.minutes`` respectively.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001983
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04001984 .. versionchanged:: 3.6
Berker Peksagdf326eb2015-09-09 18:32:50 +03001985 Name generated from ``offset=timedelta(0)`` is now plain 'UTC', not
1986 'UTC+00:00'.
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04001987
1988
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001989.. method:: timezone.dst(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001990
1991 Always returns ``None``.
1992
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001993.. method:: timezone.fromutc(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001994
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001995 Return ``dt + offset``. The *dt* argument must be an aware
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001996 :class:`.datetime` instance, with ``tzinfo`` set to ``self``.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001997
1998Class attributes:
1999
2000.. attribute:: timezone.utc
2001
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002002 The UTC timezone, ``timezone(timedelta(0))``.
Georg Brandl48310cd2009-01-03 21:18:54 +00002003
Georg Brandl116aa622007-08-15 14:28:22 +00002004
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03002005.. index::
Serhiy Storchaka913876d2018-10-28 13:41:26 +02002006 single: % (percent); datetime format
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03002007
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002008.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00002009
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002010:meth:`strftime` and :meth:`strptime` Behavior
2011----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00002012
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002013:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
Georg Brandl116aa622007-08-15 14:28:22 +00002014``strftime(format)`` method, to create a string representing the time under the
2015control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
2016acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
2017although not all objects support a :meth:`timetuple` method.
2018
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002019Conversely, the :meth:`datetime.strptime` class method creates a
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002020:class:`.datetime` object from a string representing a date and time and a
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002021corresponding format string. ``datetime.strptime(date_string, format)`` is
Gus Goulartc0799ec2018-10-29 08:49:52 -03002022equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``, except
2023when the format includes sub-second components or timezone offset information,
2024which are supported in ``datetime.strptime`` but are discarded by ``time.strptime``.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002025
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002026For :class:`.time` objects, the format codes for year, month, and day should not
Georg Brandl116aa622007-08-15 14:28:22 +00002027be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002028is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00002029
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002030For :class:`date` objects, the format codes for hours, minutes, seconds, and
2031microseconds should not be used, as :class:`date` objects have no such
2032values. If they're used anyway, ``0`` is substituted for them.
2033
Georg Brandl116aa622007-08-15 14:28:22 +00002034The full set of format codes supported varies across platforms, because Python
2035calls the platform C library's :func:`strftime` function, and platform
Georg Brandlb7117af2013-10-13 18:28:25 +02002036variations are common. To see the full set of format codes supported on your
2037platform, consult the :manpage:`strftime(3)` documentation.
Christian Heimes895627f2007-12-08 17:28:33 +00002038
Alexey Izbyshev1cffd0e2019-01-13 00:21:54 +07002039For the same reason, handling of format strings containing Unicode code points
2040that can't be represented in the charset of the current locale is also
2041platform-dependent. On some platforms such code points are preserved intact in
2042the output, while on others ``strftime`` may raise :exc:`UnicodeError` or return
2043an empty string instead.
2044
Christian Heimes895627f2007-12-08 17:28:33 +00002045The following is a list of all the format codes that the C standard (1989
2046version) requires, and these work on all platforms with a standard C
2047implementation. Note that the 1999 version of the C standard added additional
2048format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00002049
David Wolever569a5fa2013-08-12 16:56:02 -04002050+-----------+--------------------------------+------------------------+-------+
2051| Directive | Meaning | Example | Notes |
2052+===========+================================+========================+=======+
2053| ``%a`` | Weekday as locale's || Sun, Mon, ..., Sat | \(1) |
2054| | abbreviated name. | (en_US); | |
2055| | || So, Mo, ..., Sa | |
2056| | | (de_DE) | |
2057+-----------+--------------------------------+------------------------+-------+
2058| ``%A`` | Weekday as locale's full name. || Sunday, Monday, ..., | \(1) |
2059| | | Saturday (en_US); | |
2060| | || Sonntag, Montag, ..., | |
2061| | | Samstag (de_DE) | |
2062+-----------+--------------------------------+------------------------+-------+
2063| ``%w`` | Weekday as a decimal number, | 0, 1, ..., 6 | |
2064| | where 0 is Sunday and 6 is | | |
2065| | Saturday. | | |
2066+-----------+--------------------------------+------------------------+-------+
2067| ``%d`` | Day of the month as a | 01, 02, ..., 31 | |
2068| | zero-padded decimal number. | | |
2069+-----------+--------------------------------+------------------------+-------+
2070| ``%b`` | Month as locale's abbreviated || Jan, Feb, ..., Dec | \(1) |
2071| | name. | (en_US); | |
2072| | || Jan, Feb, ..., Dez | |
2073| | | (de_DE) | |
2074+-----------+--------------------------------+------------------------+-------+
2075| ``%B`` | Month as locale's full name. || January, February, | \(1) |
2076| | | ..., December (en_US);| |
2077| | || Januar, Februar, ..., | |
2078| | | Dezember (de_DE) | |
2079+-----------+--------------------------------+------------------------+-------+
2080| ``%m`` | Month as a zero-padded | 01, 02, ..., 12 | |
2081| | decimal number. | | |
2082+-----------+--------------------------------+------------------------+-------+
2083| ``%y`` | Year without century as a | 00, 01, ..., 99 | |
2084| | zero-padded decimal number. | | |
2085+-----------+--------------------------------+------------------------+-------+
2086| ``%Y`` | Year with century as a decimal | 0001, 0002, ..., 2013, | \(2) |
David Wolever5d07e702013-08-14 14:41:48 -04002087| | number. | 2014, ..., 9998, 9999 | |
David Wolever569a5fa2013-08-12 16:56:02 -04002088+-----------+--------------------------------+------------------------+-------+
2089| ``%H`` | Hour (24-hour clock) as a | 00, 01, ..., 23 | |
2090| | zero-padded decimal number. | | |
2091+-----------+--------------------------------+------------------------+-------+
2092| ``%I`` | Hour (12-hour clock) as a | 01, 02, ..., 12 | |
2093| | zero-padded decimal number. | | |
2094+-----------+--------------------------------+------------------------+-------+
2095| ``%p`` | Locale's equivalent of either || AM, PM (en_US); | \(1), |
2096| | AM or PM. || am, pm (de_DE) | \(3) |
2097+-----------+--------------------------------+------------------------+-------+
2098| ``%M`` | Minute as a zero-padded | 00, 01, ..., 59 | |
2099| | decimal number. | | |
2100+-----------+--------------------------------+------------------------+-------+
2101| ``%S`` | Second as a zero-padded | 00, 01, ..., 59 | \(4) |
2102| | decimal number. | | |
2103+-----------+--------------------------------+------------------------+-------+
2104| ``%f`` | Microsecond as a decimal | 000000, 000001, ..., | \(5) |
2105| | number, zero-padded on the | 999999 | |
2106| | left. | | |
2107+-----------+--------------------------------+------------------------+-------+
Christophe Nanteuil92878822018-10-06 00:57:02 +02002108| ``%z`` | UTC offset in the form | (empty), +0000, | \(6) |
2109| | ±HHMM[SS[.ffffff]] (empty | -0400, +1030, | |
2110| | string if the object is | +063415, | |
2111| | naive). | -030712.345216 | |
David Wolever569a5fa2013-08-12 16:56:02 -04002112+-----------+--------------------------------+------------------------+-------+
2113| ``%Z`` | Time zone name (empty string | (empty), UTC, EST, CST | |
2114| | if the object is naive). | | |
2115+-----------+--------------------------------+------------------------+-------+
2116| ``%j`` | Day of the year as a | 001, 002, ..., 366 | |
2117| | zero-padded decimal number. | | |
2118+-----------+--------------------------------+------------------------+-------+
2119| ``%U`` | Week number of the year | 00, 01, ..., 53 | \(7) |
2120| | (Sunday as the first day of | | |
2121| | the week) as a zero padded | | |
2122| | decimal number. All days in a | | |
2123| | new year preceding the first | | |
2124| | Sunday are considered to be in | | |
2125| | week 0. | | |
2126+-----------+--------------------------------+------------------------+-------+
2127| ``%W`` | Week number of the year | 00, 01, ..., 53 | \(7) |
2128| | (Monday as the first day of | | |
2129| | the week) as a decimal number. | | |
2130| | All days in a new year | | |
2131| | preceding the first Monday | | |
2132| | are considered to be in | | |
2133| | week 0. | | |
2134+-----------+--------------------------------+------------------------+-------+
2135| ``%c`` | Locale's appropriate date and || Tue Aug 16 21:30:00 | \(1) |
2136| | time representation. | 1988 (en_US); | |
2137| | || Di 16 Aug 21:30:00 | |
2138| | | 1988 (de_DE) | |
2139+-----------+--------------------------------+------------------------+-------+
2140| ``%x`` | Locale's appropriate date || 08/16/88 (None); | \(1) |
2141| | representation. || 08/16/1988 (en_US); | |
2142| | || 16.08.1988 (de_DE) | |
2143+-----------+--------------------------------+------------------------+-------+
2144| ``%X`` | Locale's appropriate time || 21:30:00 (en_US); | \(1) |
2145| | representation. || 21:30:00 (de_DE) | |
2146+-----------+--------------------------------+------------------------+-------+
2147| ``%%`` | A literal ``'%'`` character. | % | |
2148+-----------+--------------------------------+------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00002149
Alexander Belopolsky68713e42015-10-06 13:29:56 -04002150Several additional directives not required by the C89 standard are included for
2151convenience. These parameters all correspond to ISO 8601 date values. These
2152may not be available on all platforms when used with the :meth:`strftime`
2153method. The ISO 8601 year and ISO 8601 week directives are not interchangeable
2154with the year and week number directives above. Calling :meth:`strptime` with
2155incomplete or ambiguous ISO 8601 directives will raise a :exc:`ValueError`.
2156
2157+-----------+--------------------------------+------------------------+-------+
2158| Directive | Meaning | Example | Notes |
2159+===========+================================+========================+=======+
2160| ``%G`` | ISO 8601 year with century | 0001, 0002, ..., 2013, | \(8) |
2161| | representing the year that | 2014, ..., 9998, 9999 | |
2162| | contains the greater part of | | |
2163| | the ISO week (``%V``). | | |
2164+-----------+--------------------------------+------------------------+-------+
2165| ``%u`` | ISO 8601 weekday as a decimal | 1, 2, ..., 7 | |
2166| | number where 1 is Monday. | | |
2167+-----------+--------------------------------+------------------------+-------+
2168| ``%V`` | ISO 8601 week as a decimal | 01, 02, ..., 53 | \(8) |
2169| | number with Monday as | | |
2170| | the first day of the week. | | |
2171| | Week 01 is the week containing | | |
2172| | Jan 4. | | |
2173+-----------+--------------------------------+------------------------+-------+
2174
2175.. versionadded:: 3.6
2176 ``%G``, ``%u`` and ``%V`` were added.
2177
Christian Heimes895627f2007-12-08 17:28:33 +00002178Notes:
2179
2180(1)
David Wolever569a5fa2013-08-12 16:56:02 -04002181 Because the format depends on the current locale, care should be taken when
2182 making assumptions about the output value. Field orderings will vary (for
2183 example, "month/day/year" versus "day/month/year"), and the output may
2184 contain Unicode characters encoded using the locale's default encoding (for
Georg Brandlad321532013-10-29 08:05:10 +01002185 example, if the current locale is ``ja_JP``, the default encoding could be
David Wolever569a5fa2013-08-12 16:56:02 -04002186 any one of ``eucJP``, ``SJIS``, or ``utf-8``; use :meth:`locale.getlocale`
2187 to determine the current locale's encoding).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002188
2189(2)
David Wolever569a5fa2013-08-12 16:56:02 -04002190 The :meth:`strptime` method can parse years in the full [1, 9999] range, but
2191 years < 1000 must be zero-filled to 4-digit width.
Alexander Belopolsky085556a2011-01-10 23:28:33 +00002192
2193 .. versionchanged:: 3.2
2194 In previous versions, :meth:`strftime` method was restricted to
2195 years >= 1900.
2196
Alexander Belopolsky5611a1c2011-05-02 14:14:48 -04002197 .. versionchanged:: 3.3
2198 In version 3.2, :meth:`strftime` method was restricted to
2199 years >= 1000.
2200
David Wolever569a5fa2013-08-12 16:56:02 -04002201(3)
2202 When used with the :meth:`strptime` method, the ``%p`` directive only affects
2203 the output hour field if the ``%I`` directive is used to parse the hour.
Alexander Belopolskyca94f552010-06-17 18:30:34 +00002204
David Wolever569a5fa2013-08-12 16:56:02 -04002205(4)
2206 Unlike the :mod:`time` module, the :mod:`datetime` module does not support
2207 leap seconds.
2208
2209(5)
2210 When used with the :meth:`strptime` method, the ``%f`` directive
2211 accepts from one to six digits and zero pads on the right. ``%f`` is
2212 an extension to the set of format characters in the C standard (but
2213 implemented separately in datetime objects, and therefore always
2214 available).
2215
2216(6)
2217 For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
2218 strings.
2219
2220 For an aware object:
2221
2222 ``%z``
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002223 :meth:`utcoffset` is transformed into a string of the form
Christophe Nanteuil92878822018-10-06 00:57:02 +02002224 ±HHMM[SS[.ffffff]], where HH is a 2-digit string giving the number of UTC
2225 offset hours, MM is a 2-digit string giving the number of UTC offset
Serhiy Storchakabac2d5b2018-03-28 22:14:26 +03002226 minutes, SS is a 2-digit string giving the number of UTC offset
Christophe Nanteuil92878822018-10-06 00:57:02 +02002227 seconds and ffffff is a 6-digit string giving the number of UTC
2228 offset microseconds. The ffffff part is omitted when the offset is a
2229 whole number of seconds and both the ffffff and the SS part is omitted
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002230 when the offset is a whole number of minutes. For example, if
2231 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
2232 replaced with the string ``'-0330'``.
2233
2234 .. versionchanged:: 3.7
2235 The UTC offset is not restricted to a whole number of minutes.
David Wolever569a5fa2013-08-12 16:56:02 -04002236
Mario Corchero32318932017-10-26 01:35:41 +01002237 .. versionchanged:: 3.7
2238 When the ``%z`` directive is provided to the :meth:`strptime` method,
2239 the UTC offsets can have a colon as a separator between hours, minutes
2240 and seconds.
2241 For example, ``'+01:00:00'`` will be parsed as an offset of one hour.
2242 In addition, providing ``'Z'`` is identical to ``'+00:00'``.
2243
David Wolever569a5fa2013-08-12 16:56:02 -04002244 ``%Z``
2245 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty
2246 string. Otherwise ``%Z`` is replaced by the returned value, which must
2247 be a string.
2248
2249 .. versionchanged:: 3.2
2250 When the ``%z`` directive is provided to the :meth:`strptime` method, an
2251 aware :class:`.datetime` object will be produced. The ``tzinfo`` of the
2252 result will be set to a :class:`timezone` instance.
2253
2254(7)
2255 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used
Alexander Belopolsky68713e42015-10-06 13:29:56 -04002256 in calculations when the day of the week and the calendar year (``%Y``)
2257 are specified.
2258
2259(8)
2260 Similar to ``%U`` and ``%W``, ``%V`` is only used in calculations when the
2261 day of the week and the ISO year (``%G``) are specified in a
2262 :meth:`strptime` format string. Also note that ``%G`` and ``%Y`` are not
Martin Panterf1579822016-05-26 06:03:33 +00002263 interchangeable.
R David Murray9075d8b2012-05-14 22:14:46 -04002264
2265.. rubric:: Footnotes
2266
2267.. [#] If, that is, we ignore the effects of Relativity