blob: dce51a16e868a46a17e829de659269e2c389ab6c [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 |
244| | true. (1) |
245+--------------------------------+-----------------------------------------------+
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+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000257| ``f = t2 / t3`` | Division (3) of *t2* by *t3*. Returns a |
258| | :class:`float` object. |
259+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000260| ``t1 = t2 / f or t1 = t2 / i`` | Delta divided by a float or an int. The result|
261| | is rounded to the nearest multiple of |
262| | timedelta.resolution using round-half-to-even.|
263+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000264| ``t1 = t2 // i`` or | The floor is computed and the remainder (if |
265| ``t1 = t2 // t3`` | any) is thrown away. In the second case, an |
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000266| | integer is returned. (3) |
Mark Dickinson7c186e22010-04-20 22:32:49 +0000267+--------------------------------+-----------------------------------------------+
268| ``t1 = t2 % t3`` | The remainder is computed as a |
269| | :class:`timedelta` object. (3) |
270+--------------------------------+-----------------------------------------------+
271| ``q, r = divmod(t1, t2)`` | Computes the quotient and the remainder: |
272| | ``q = t1 // t2`` (3) and ``r = t1 % t2``. |
273| | q is an integer and r is a :class:`timedelta` |
274| | object. |
Georg Brandl116aa622007-08-15 14:28:22 +0000275+--------------------------------+-----------------------------------------------+
276| ``+t1`` | Returns a :class:`timedelta` object with the |
277| | same value. (2) |
278+--------------------------------+-----------------------------------------------+
279| ``-t1`` | equivalent to :class:`timedelta`\ |
280| | (-*t1.days*, -*t1.seconds*, |
281| | -*t1.microseconds*), and to *t1*\* -1. (1)(4) |
282+--------------------------------+-----------------------------------------------+
Georg Brandl495f7b52009-10-27 15:28:25 +0000283| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, and|
Georg Brandl116aa622007-08-15 14:28:22 +0000284| | to -*t* when ``t.days < 0``. (2) |
285+--------------------------------+-----------------------------------------------+
Georg Brandlf55c3152010-07-31 11:40:07 +0000286| ``str(t)`` | Returns a string in the form |
287| | ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D |
288| | is negative for negative ``t``. (5) |
289+--------------------------------+-----------------------------------------------+
Utkarsh Upadhyaycc5a65c2017-07-25 23:51:33 +0200290| ``repr(t)`` | Returns a string representation of the |
291| | :class:`timedelta` object as a constructor |
292| | call with canonical attribute values. |
Georg Brandlf55c3152010-07-31 11:40:07 +0000293+--------------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000294
Utkarsh Upadhyaycc5a65c2017-07-25 23:51:33 +0200295
Georg Brandl116aa622007-08-15 14:28:22 +0000296Notes:
297
298(1)
299 This is exact, but may overflow.
300
301(2)
302 This is exact, and cannot overflow.
303
304(3)
305 Division by 0 raises :exc:`ZeroDivisionError`.
306
307(4)
308 -*timedelta.max* is not representable as a :class:`timedelta` object.
309
Georg Brandlf55c3152010-07-31 11:40:07 +0000310(5)
311 String representations of :class:`timedelta` objects are normalized
312 similarly to their internal representation. This leads to somewhat
313 unusual results for negative timedeltas. For example:
314
315 >>> timedelta(hours=-5)
Utkarsh Upadhyay8e453182017-07-28 14:42:56 +0200316 datetime.timedelta(days=-1, seconds=68400)
Georg Brandlf55c3152010-07-31 11:40:07 +0000317 >>> print(_)
318 -1 day, 19:00:00
319
Georg Brandl116aa622007-08-15 14:28:22 +0000320In addition to the operations listed above :class:`timedelta` objects support
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300321certain additions and subtractions with :class:`date` and :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +0000322objects (see below).
323
Georg Brandl67b21b72010-08-17 15:07:14 +0000324.. versionchanged:: 3.2
325 Floor division and true division of a :class:`timedelta` object by another
326 :class:`timedelta` object are now supported, as are remainder operations and
327 the :func:`divmod` function. True division and multiplication of a
328 :class:`timedelta` object by a :class:`float` object are now supported.
Mark Dickinson7c186e22010-04-20 22:32:49 +0000329
330
Georg Brandl116aa622007-08-15 14:28:22 +0000331Comparisons of :class:`timedelta` objects are supported with the
332:class:`timedelta` object representing the smaller duration considered to be the
333smaller timedelta. In order to stop mixed-type comparisons from falling back to
334the default comparison by object address, when a :class:`timedelta` object is
335compared to an object of a different type, :exc:`TypeError` is raised unless the
336comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
337:const:`True`, respectively.
338
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000339:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl116aa622007-08-15 14:28:22 +0000340efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
341considered to be true if and only if it isn't equal to ``timedelta(0)``.
342
Antoine Pitroube6859d2009-11-25 23:02:32 +0000343Instance methods:
344
345.. method:: timedelta.total_seconds()
346
347 Return the total number of seconds contained in the duration. Equivalent to
Mark Dickinson0381e3f2010-05-08 14:35:02 +0000348 ``td / timedelta(seconds=1)``.
349
350 Note that for very large time intervals (greater than 270 years on
351 most platforms) this method will lose microsecond accuracy.
Antoine Pitroube6859d2009-11-25 23:02:32 +0000352
353 .. versionadded:: 3.2
354
355
Christian Heimesfe337bf2008-03-23 21:54:12 +0000356Example usage:
Georg Brandl48310cd2009-01-03 21:18:54 +0000357
Christian Heimes895627f2007-12-08 17:28:33 +0000358 >>> from datetime import timedelta
359 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000360 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Christian Heimes895627f2007-12-08 17:28:33 +0000361 ... minutes=50, seconds=600) # adds up to 365 days
Antoine Pitroube6859d2009-11-25 23:02:32 +0000362 >>> year.total_seconds()
363 31536000.0
Christian Heimes895627f2007-12-08 17:28:33 +0000364 >>> year == another_year
365 True
366 >>> ten_years = 10 * year
367 >>> ten_years, ten_years.days // 365
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +0200368 (datetime.timedelta(days=3650), 10)
Christian Heimes895627f2007-12-08 17:28:33 +0000369 >>> nine_years = ten_years - year
370 >>> nine_years, nine_years.days // 365
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +0200371 (datetime.timedelta(days=3285), 9)
delirious-lettucec7b3f0f2017-05-18 19:01:00 -0600372 >>> three_years = nine_years // 3
Christian Heimes895627f2007-12-08 17:28:33 +0000373 >>> three_years, three_years.days // 365
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +0200374 (datetime.timedelta(days=1095), 3)
Christian Heimes895627f2007-12-08 17:28:33 +0000375 >>> abs(three_years - ten_years) == 2 * three_years + year
376 True
377
Georg Brandl116aa622007-08-15 14:28:22 +0000378
379.. _datetime-date:
380
381:class:`date` Objects
382---------------------
383
384A :class:`date` object represents a date (year, month and day) in an idealized
385calendar, the current Gregorian calendar indefinitely extended in both
386directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
387called day number 2, and so on. This matches the definition of the "proleptic
388Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
389where it's the base calendar for all computations. See the book for algorithms
390for converting between proleptic Gregorian ordinals and many other calendar
391systems.
392
393
394.. class:: date(year, month, day)
395
Georg Brandl5c106642007-11-29 17:41:05 +0000396 All arguments are required. Arguments may be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000397 ranges:
398
399 * ``MINYEAR <= year <= MAXYEAR``
400 * ``1 <= month <= 12``
401 * ``1 <= day <= number of days in the given month and year``
402
403 If an argument outside those ranges is given, :exc:`ValueError` is raised.
404
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000405
Georg Brandl116aa622007-08-15 14:28:22 +0000406Other constructors, all class methods:
407
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000408.. classmethod:: date.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000409
410 Return the current local date. This is equivalent to
411 ``date.fromtimestamp(time.time())``.
412
413
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000414.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000415
416 Return the local date corresponding to the POSIX timestamp, such as is returned
Victor Stinner5d272cc2012-03-13 13:35:55 +0100417 by :func:`time.time`. This may raise :exc:`OverflowError`, if the timestamp is out
Victor Stinnerecc6e662012-03-14 00:39:29 +0100418 of the range of values supported by the platform C :c:func:`localtime` function,
419 and :exc:`OSError` on :c:func:`localtime` failure.
Georg Brandl116aa622007-08-15 14:28:22 +0000420 It's common for this to be restricted to years from 1970 through 2038. Note
421 that on non-POSIX systems that include leap seconds in their notion of a
422 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
423
Victor Stinner5d272cc2012-03-13 13:35:55 +0100424 .. versionchanged:: 3.3
425 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
426 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100427 :c:func:`localtime` function. Raise :exc:`OSError` instead of
428 :exc:`ValueError` on :c:func:`localtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100429
Georg Brandl116aa622007-08-15 14:28:22 +0000430
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000431.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000432
433 Return the date corresponding to the proleptic Gregorian ordinal, where January
434 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
435 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
436 d``.
437
Georg Brandl116aa622007-08-15 14:28:22 +0000438
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000439Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000440
441.. attribute:: date.min
442
443 The earliest representable date, ``date(MINYEAR, 1, 1)``.
444
445
446.. attribute:: date.max
447
448 The latest representable date, ``date(MAXYEAR, 12, 31)``.
449
450
451.. attribute:: date.resolution
452
453 The smallest possible difference between non-equal date objects,
454 ``timedelta(days=1)``.
455
Georg Brandl116aa622007-08-15 14:28:22 +0000456
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000457Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000458
459.. attribute:: date.year
460
461 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
462
463
464.. attribute:: date.month
465
466 Between 1 and 12 inclusive.
467
468
469.. attribute:: date.day
470
471 Between 1 and the number of days in the given month of the given year.
472
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000473
Georg Brandl116aa622007-08-15 14:28:22 +0000474Supported operations:
475
476+-------------------------------+----------------------------------------------+
477| Operation | Result |
478+===============================+==============================================+
479| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
480| | from *date1*. (1) |
481+-------------------------------+----------------------------------------------+
482| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
483| | timedelta == date1``. (2) |
484+-------------------------------+----------------------------------------------+
485| ``timedelta = date1 - date2`` | \(3) |
486+-------------------------------+----------------------------------------------+
487| ``date1 < date2`` | *date1* is considered less than *date2* when |
488| | *date1* precedes *date2* in time. (4) |
489+-------------------------------+----------------------------------------------+
490
491Notes:
492
493(1)
494 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
495 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
496 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
497 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
498 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
499
500(2)
501 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
502 isolation can overflow in cases where date1 - timedelta does not.
503 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
504
505(3)
506 This is exact, and cannot overflow. timedelta.seconds and
507 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
508
509(4)
510 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
511 date2.toordinal()``. In order to stop comparison from falling back to the
512 default scheme of comparing object addresses, date comparison normally raises
513 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
514 However, ``NotImplemented`` is returned instead if the other comparand has a
515 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
516 chance at implementing mixed-type comparison. If not, when a :class:`date`
517 object is compared to an object of a different type, :exc:`TypeError` is raised
518 unless the comparison is ``==`` or ``!=``. The latter cases return
519 :const:`False` or :const:`True`, respectively.
520
521Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
522objects are considered to be true.
523
524Instance methods:
525
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400526.. method:: date.replace(year=self.year, month=self.month, day=self.day)
Georg Brandl116aa622007-08-15 14:28:22 +0000527
Senthil Kumarana6bac952011-07-04 11:28:30 -0700528 Return a date with the same value, except for those parameters given new
529 values by whichever keyword arguments are specified. For example, if ``d ==
530 date(2002, 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000531
532
533.. method:: date.timetuple()
534
535 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
536 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
537 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000538 d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1,
539 1).toordinal() + 1`` is the day number within the current year starting with
540 ``1`` for January 1st.
Georg Brandl116aa622007-08-15 14:28:22 +0000541
542
543.. method:: date.toordinal()
544
545 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
546 has ordinal 1. For any :class:`date` object *d*,
547 ``date.fromordinal(d.toordinal()) == d``.
548
549
550.. method:: date.weekday()
551
552 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
553 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
554 :meth:`isoweekday`.
555
556
557.. method:: date.isoweekday()
558
559 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
560 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
561 :meth:`weekday`, :meth:`isocalendar`.
562
563
564.. method:: date.isocalendar()
565
566 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
567
568 The ISO calendar is a widely used variant of the Gregorian calendar. See
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300569 https://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm for a good
Mark Dickinsonf964ac22009-11-03 16:29:10 +0000570 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000571
572 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
573 Monday and ends on a Sunday. The first week of an ISO year is the first
574 (Gregorian) calendar week of a year containing a Thursday. This is called week
575 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
576
577 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
578 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
579 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
580 4).isocalendar() == (2004, 1, 7)``.
581
582
583.. method:: date.isoformat()
584
585 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
586 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
587
588
589.. method:: date.__str__()
590
591 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
592
593
594.. method:: date.ctime()
595
596 Return a string representing the date, for example ``date(2002, 12,
597 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
598 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
Georg Brandl60203b42010-10-06 10:11:56 +0000599 :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +0000600 :meth:`date.ctime` does not invoke) conforms to the C standard.
601
602
603.. method:: date.strftime(format)
604
605 Return a string representing the date, controlled by an explicit format string.
David Wolever569a5fa2013-08-12 16:56:02 -0400606 Format codes referring to hours, minutes or seconds will see 0 values. For a
607 complete list of formatting directives, see
608 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000609
Georg Brandl116aa622007-08-15 14:28:22 +0000610
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300611.. method:: date.__format__(format)
612
Martin Panterd5db1472016-02-08 01:34:09 +0000613 Same as :meth:`.date.strftime`. This makes it possible to specify a format
Martin Panterbc1ee462016-02-13 00:41:37 +0000614 string for a :class:`.date` object in :ref:`formatted string
615 literals <f-strings>` and when using :meth:`str.format`. For a
David Wolever569a5fa2013-08-12 16:56:02 -0400616 complete list of formatting directives, see
617 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300618
619
Christian Heimes895627f2007-12-08 17:28:33 +0000620Example of counting days to an event::
621
622 >>> import time
623 >>> from datetime import date
624 >>> today = date.today()
625 >>> today
626 datetime.date(2007, 12, 5)
627 >>> today == date.fromtimestamp(time.time())
628 True
629 >>> my_birthday = date(today.year, 6, 24)
630 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000631 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000632 >>> my_birthday
633 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000634 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000635 >>> time_to_birthday.days
636 202
637
Christian Heimesfe337bf2008-03-23 21:54:12 +0000638Example of working with :class:`date`:
639
640.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000641
642 >>> from datetime import date
643 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
644 >>> d
645 datetime.date(2002, 3, 11)
646 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000647 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000648 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000649 2002 # year
650 3 # month
651 11 # day
652 0
653 0
654 0
655 0 # weekday (0 = Monday)
656 70 # 70th day in the year
657 -1
658 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000659 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000660 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000661 2002 # ISO year
662 11 # ISO week number
663 1 # ISO day number ( 1 = Monday )
664 >>> d.isoformat()
665 '2002-03-11'
666 >>> d.strftime("%d/%m/%y")
667 '11/03/02'
668 >>> d.strftime("%A %d. %B %Y")
669 'Monday 11. March 2002'
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300670 >>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")
671 'The day is 11, the month is March.'
Christian Heimes895627f2007-12-08 17:28:33 +0000672
Georg Brandl116aa622007-08-15 14:28:22 +0000673
674.. _datetime-datetime:
675
Benjamin Petersond87dd432015-04-25 14:15:16 -0400676:class:`.datetime` Objects
677--------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000678
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300679A :class:`.datetime` object is a single object containing all the information
680from a :class:`date` object and a :class:`.time` object. Like a :class:`date`
681object, :class:`.datetime` assumes the current Gregorian calendar extended in
682both directions; like a time object, :class:`.datetime` assumes there are exactly
Georg Brandl116aa622007-08-15 14:28:22 +00006833600\*24 seconds in every day.
684
685Constructor:
686
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400687.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000688
689 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000690 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
691 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000692
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400693 * ``MINYEAR <= year <= MAXYEAR``,
694 * ``1 <= month <= 12``,
695 * ``1 <= day <= number of days in the given month and year``,
696 * ``0 <= hour < 24``,
697 * ``0 <= minute < 60``,
698 * ``0 <= second < 60``,
699 * ``0 <= microsecond < 1000000``,
700 * ``fold in [0, 1]``.
Georg Brandl116aa622007-08-15 14:28:22 +0000701
702 If an argument outside those ranges is given, :exc:`ValueError` is raised.
703
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400704 .. versionadded:: 3.6
705 Added the ``fold`` argument.
706
Georg Brandl116aa622007-08-15 14:28:22 +0000707Other constructors, all class methods:
708
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000709.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000710
Martin Panter16c7cfd2016-04-01 21:48:24 +0000711 Return the current local datetime, with :attr:`.tzinfo` ``None``. This is
Georg Brandl116aa622007-08-15 14:28:22 +0000712 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
713 :meth:`fromtimestamp`.
714
715
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000716.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000717
718 Return the current local date and time. If optional argument *tz* is ``None``
719 or not specified, this is like :meth:`today`, but, if possible, supplies more
720 precision than can be gotten from going through a :func:`time.time` timestamp
721 (for example, this may be possible on platforms supplying the C
Georg Brandl60203b42010-10-06 10:11:56 +0000722 :c:func:`gettimeofday` function).
Georg Brandl116aa622007-08-15 14:28:22 +0000723
Martin Panter16c7cfd2016-04-01 21:48:24 +0000724 If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` subclass, and the
725 current date and time are converted to *tz*’s time zone. In this case the
Georg Brandl116aa622007-08-15 14:28:22 +0000726 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
727 See also :meth:`today`, :meth:`utcnow`.
728
729
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000730.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000731
Martin Panter16c7cfd2016-04-01 21:48:24 +0000732 Return the current UTC date and time, with :attr:`.tzinfo` ``None``. This is like
Georg Brandl116aa622007-08-15 14:28:22 +0000733 :meth:`now`, but returns the current UTC date and time, as a naive
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300734 :class:`.datetime` object. An aware current UTC datetime can be obtained by
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000735 calling ``datetime.now(timezone.utc)``. See also :meth:`now`.
Georg Brandl116aa622007-08-15 14:28:22 +0000736
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000737.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000738
739 Return the local date and time corresponding to the POSIX timestamp, such as is
740 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
741 specified, the timestamp is converted to the platform's local date and time, and
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300742 the returned :class:`.datetime` object is naive.
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 timestamp is converted to *tz*’s time zone. In this case the result is
Georg Brandl116aa622007-08-15 14:28:22 +0000746 equivalent to
747 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
748
Victor Stinnerecc6e662012-03-14 00:39:29 +0100749 :meth:`fromtimestamp` may raise :exc:`OverflowError`, if the timestamp is out of
Georg Brandl60203b42010-10-06 10:11:56 +0000750 the range of values supported by the platform C :c:func:`localtime` or
Victor Stinnerecc6e662012-03-14 00:39:29 +0100751 :c:func:`gmtime` functions, and :exc:`OSError` on :c:func:`localtime` or
752 :c:func:`gmtime` failure.
753 It's common for this to be restricted to years in
Georg Brandl116aa622007-08-15 14:28:22 +0000754 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
755 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
756 and then it's possible to have two timestamps differing by a second that yield
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300757 identical :class:`.datetime` objects. See also :meth:`utcfromtimestamp`.
Georg Brandl116aa622007-08-15 14:28:22 +0000758
Victor Stinner5d272cc2012-03-13 13:35:55 +0100759 .. versionchanged:: 3.3
760 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
761 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100762 :c:func:`localtime` or :c:func:`gmtime` functions. Raise :exc:`OSError`
763 instead of :exc:`ValueError` on :c:func:`localtime` or :c:func:`gmtime`
764 failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100765
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400766 .. versionchanged:: 3.6
767 :meth:`fromtimestamp` may return instances with :attr:`.fold` set to 1.
Georg Brandl116aa622007-08-15 14:28:22 +0000768
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000769.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000770
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300771 Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with
Martin Panter16c7cfd2016-04-01 21:48:24 +0000772 :attr:`.tzinfo` ``None``. This may raise :exc:`OverflowError`, if the timestamp is
Victor Stinnerecc6e662012-03-14 00:39:29 +0100773 out of the range of values supported by the platform C :c:func:`gmtime` function,
774 and :exc:`OSError` on :c:func:`gmtime` failure.
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500775 It's common for this to be restricted to years in 1970 through 2038.
Georg Brandl116aa622007-08-15 14:28:22 +0000776
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500777 To get an aware :class:`.datetime` object, call :meth:`fromtimestamp`::
Alexander Belopolsky54afa552011-04-25 13:00:40 -0400778
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500779 datetime.fromtimestamp(timestamp, timezone.utc)
780
781 On the POSIX compliant platforms, it is equivalent to the following
782 expression::
783
784 datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)
785
786 except the latter formula always supports the full years range: between
787 :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
Alexander Belopolsky54afa552011-04-25 13:00:40 -0400788
Victor Stinner5d272cc2012-03-13 13:35:55 +0100789 .. versionchanged:: 3.3
790 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
791 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100792 :c:func:`gmtime` function. Raise :exc:`OSError` instead of
793 :exc:`ValueError` on :c:func:`gmtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100794
Georg Brandl116aa622007-08-15 14:28:22 +0000795
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000796.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000797
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300798 Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal,
Georg Brandl116aa622007-08-15 14:28:22 +0000799 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
800 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
Martin Panter16c7cfd2016-04-01 21:48:24 +0000801 microsecond of the result are all 0, and :attr:`.tzinfo` is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000802
803
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400804.. classmethod:: datetime.combine(date, time, tzinfo=self.tzinfo)
Georg Brandl116aa622007-08-15 14:28:22 +0000805
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300806 Return a new :class:`.datetime` object whose date components are equal to the
Alexander Belopolsky43746c32016-08-02 17:49:30 -0400807 given :class:`date` object's, and whose time components
808 are equal to the given :class:`.time` object's. If the *tzinfo*
809 argument is provided, its value is used to set the :attr:`.tzinfo` attribute
810 of the result, otherwise the :attr:`~.time.tzinfo` attribute of the *time* argument
811 is used.
812
813 For any :class:`.datetime` object *d*,
814 ``d == datetime.combine(d.date(), d.time(), d.tzinfo)``. If date is a
Martin Panter16c7cfd2016-04-01 21:48:24 +0000815 :class:`.datetime` object, its time components and :attr:`.tzinfo` attributes
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800816 are ignored.
Georg Brandl116aa622007-08-15 14:28:22 +0000817
Alexander Belopolsky43746c32016-08-02 17:49:30 -0400818 .. versionchanged:: 3.6
819 Added the *tzinfo* argument.
820
Georg Brandl116aa622007-08-15 14:28:22 +0000821
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000822.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000823
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300824 Return a :class:`.datetime` corresponding to *date_string*, parsed according to
Georg Brandl116aa622007-08-15 14:28:22 +0000825 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
826 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
827 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 -0400828 time tuple. For a complete list of formatting directives, see
829 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000830
Georg Brandl116aa622007-08-15 14:28:22 +0000831
Georg Brandl116aa622007-08-15 14:28:22 +0000832
833Class attributes:
834
Georg Brandl116aa622007-08-15 14:28:22 +0000835.. attribute:: datetime.min
836
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300837 The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1,
Georg Brandl116aa622007-08-15 14:28:22 +0000838 tzinfo=None)``.
839
840
841.. attribute:: datetime.max
842
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300843 The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
Georg Brandl116aa622007-08-15 14:28:22 +0000844 59, 999999, tzinfo=None)``.
845
846
847.. attribute:: datetime.resolution
848
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300849 The smallest possible difference between non-equal :class:`.datetime` objects,
Georg Brandl116aa622007-08-15 14:28:22 +0000850 ``timedelta(microseconds=1)``.
851
Georg Brandl116aa622007-08-15 14:28:22 +0000852
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000853Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000854
855.. attribute:: datetime.year
856
857 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
858
859
860.. attribute:: datetime.month
861
862 Between 1 and 12 inclusive.
863
864
865.. attribute:: datetime.day
866
867 Between 1 and the number of days in the given month of the given year.
868
869
870.. attribute:: datetime.hour
871
872 In ``range(24)``.
873
874
875.. attribute:: datetime.minute
876
877 In ``range(60)``.
878
879
880.. attribute:: datetime.second
881
882 In ``range(60)``.
883
884
885.. attribute:: datetime.microsecond
886
887 In ``range(1000000)``.
888
889
890.. attribute:: datetime.tzinfo
891
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300892 The object passed as the *tzinfo* argument to the :class:`.datetime` constructor,
Georg Brandl116aa622007-08-15 14:28:22 +0000893 or ``None`` if none was passed.
894
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000895
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400896.. attribute:: datetime.fold
897
898 In ``[0, 1]``. Used to disambiguate wall times during a repeated interval. (A
899 repeated interval occurs when clocks are rolled back at the end of daylight saving
900 time or when the UTC offset for the current zone is decreased for political reasons.)
901 The value 0 (1) represents the earlier (later) of the two moments with the same wall
902 time representation.
903
904 .. versionadded:: 3.6
905
Georg Brandl116aa622007-08-15 14:28:22 +0000906Supported operations:
907
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300908+---------------------------------------+--------------------------------+
909| Operation | Result |
910+=======================================+================================+
911| ``datetime2 = datetime1 + timedelta`` | \(1) |
912+---------------------------------------+--------------------------------+
913| ``datetime2 = datetime1 - timedelta`` | \(2) |
914+---------------------------------------+--------------------------------+
915| ``timedelta = datetime1 - datetime2`` | \(3) |
916+---------------------------------------+--------------------------------+
917| ``datetime1 < datetime2`` | Compares :class:`.datetime` to |
918| | :class:`.datetime`. (4) |
919+---------------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000920
921(1)
922 datetime2 is a duration of timedelta removed from datetime1, moving forward in
923 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
Martin Panter16c7cfd2016-04-01 21:48:24 +0000924 result has the same :attr:`~.datetime.tzinfo` attribute as the input datetime, and
Senthil Kumarana6bac952011-07-04 11:28:30 -0700925 datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
926 datetime2.year would be smaller than :const:`MINYEAR` or larger than
927 :const:`MAXYEAR`. Note that no time zone adjustments are done even if the
928 input is an aware object.
Georg Brandl116aa622007-08-15 14:28:22 +0000929
930(2)
931 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
Martin Panter16c7cfd2016-04-01 21:48:24 +0000932 addition, the result has the same :attr:`~.datetime.tzinfo` attribute as the input
Senthil Kumarana6bac952011-07-04 11:28:30 -0700933 datetime, and no time zone adjustments are done even if the input is aware.
934 This isn't quite equivalent to datetime1 + (-timedelta), because -timedelta
935 in isolation can overflow in cases where datetime1 - timedelta does not.
Georg Brandl116aa622007-08-15 14:28:22 +0000936
937(3)
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300938 Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if
Georg Brandl116aa622007-08-15 14:28:22 +0000939 both operands are naive, or if both are aware. If one is aware and the other is
940 naive, :exc:`TypeError` is raised.
941
Martin Panter16c7cfd2016-04-01 21:48:24 +0000942 If both are naive, or both are aware and have the same :attr:`~.datetime.tzinfo` attribute,
943 the :attr:`~.datetime.tzinfo` attributes are ignored, and the result is a :class:`timedelta`
Georg Brandl116aa622007-08-15 14:28:22 +0000944 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
945 are done in this case.
946
Martin Panter16c7cfd2016-04-01 21:48:24 +0000947 If both are aware and have different :attr:`~.datetime.tzinfo` attributes, ``a-b`` acts
Senthil Kumarana6bac952011-07-04 11:28:30 -0700948 as if *a* and *b* were first converted to naive UTC datetimes first. The
949 result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
950 - b.utcoffset())`` except that the implementation never overflows.
Georg Brandl116aa622007-08-15 14:28:22 +0000951
952(4)
953 *datetime1* is considered less than *datetime2* when *datetime1* precedes
954 *datetime2* in time.
955
Alexander Belopolsky08313822012-06-15 20:19:47 -0400956 If one comparand is naive and the other is aware, :exc:`TypeError`
957 is raised if an order comparison is attempted. For equality
958 comparisons, naive instances are never equal to aware instances.
959
Martin Panter16c7cfd2016-04-01 21:48:24 +0000960 If both comparands are aware, and have the same :attr:`~.datetime.tzinfo` attribute, the
961 common :attr:`~.datetime.tzinfo` attribute is ignored and the base datetimes are
962 compared. If both comparands are aware and have different :attr:`~.datetime.tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -0700963 attributes, the comparands are first adjusted by subtracting their UTC
964 offsets (obtained from ``self.utcoffset()``).
Georg Brandl116aa622007-08-15 14:28:22 +0000965
Alexander Belopolsky08313822012-06-15 20:19:47 -0400966 .. versionchanged:: 3.3
Martin Panter16c7cfd2016-04-01 21:48:24 +0000967 Equality comparisons between naive and aware :class:`.datetime`
Éric Araujob0f08952012-06-24 16:22:09 -0400968 instances don't raise :exc:`TypeError`.
Alexander Belopolsky08313822012-06-15 20:19:47 -0400969
Georg Brandl116aa622007-08-15 14:28:22 +0000970 .. note::
971
972 In order to stop comparison from falling back to the default scheme of comparing
973 object addresses, datetime comparison normally raises :exc:`TypeError` if the
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300974 other comparand isn't also a :class:`.datetime` object. However,
Georg Brandl116aa622007-08-15 14:28:22 +0000975 ``NotImplemented`` is returned instead if the other comparand has a
976 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300977 chance at implementing mixed-type comparison. If not, when a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +0000978 object is compared to an object of a different type, :exc:`TypeError` is raised
979 unless the comparison is ``==`` or ``!=``. The latter cases return
980 :const:`False` or :const:`True`, respectively.
981
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300982:class:`.datetime` objects can be used as dictionary keys. In Boolean contexts,
983all :class:`.datetime` objects are considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +0000984
985Instance methods:
986
Georg Brandl116aa622007-08-15 14:28:22 +0000987.. method:: datetime.date()
988
989 Return :class:`date` object with same year, month and day.
990
991
992.. method:: datetime.time()
993
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400994 Return :class:`.time` object with same hour, minute, second, microsecond and fold.
Martin Panter16c7cfd2016-04-01 21:48:24 +0000995 :attr:`.tzinfo` is ``None``. See also method :meth:`timetz`.
Georg Brandl116aa622007-08-15 14:28:22 +0000996
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400997 .. versionchanged:: 3.6
998 The fold value is copied to the returned :class:`.time` object.
999
Georg Brandl116aa622007-08-15 14:28:22 +00001000
1001.. method:: datetime.timetz()
1002
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001003 Return :class:`.time` object with same hour, minute, second, microsecond, fold, and
Senthil Kumarana6bac952011-07-04 11:28:30 -07001004 tzinfo attributes. See also method :meth:`time`.
Georg Brandl116aa622007-08-15 14:28:22 +00001005
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001006 .. versionchanged:: 3.6
1007 The fold value is copied to the returned :class:`.time` object.
Georg Brandl116aa622007-08-15 14:28:22 +00001008
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001009
1010.. method:: datetime.replace(year=self.year, month=self.month, day=self.day, \
1011 hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, \
1012 tzinfo=self.tzinfo, * fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001013
Senthil Kumarana6bac952011-07-04 11:28:30 -07001014 Return a datetime with the same attributes, except for those attributes given
1015 new values by whichever keyword arguments are specified. Note that
1016 ``tzinfo=None`` can be specified to create a naive datetime from an aware
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001017 datetime with no conversion of date and time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001018
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001019 .. versionadded:: 3.6
1020 Added the ``fold`` argument.
1021
Georg Brandl116aa622007-08-15 14:28:22 +00001022
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001023.. method:: datetime.astimezone(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001024
Martin Panter16c7cfd2016-04-01 21:48:24 +00001025 Return a :class:`.datetime` object with new :attr:`.tzinfo` attribute *tz*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001026 adjusting the date and time data so the result is the same UTC time as
Senthil Kumarana6bac952011-07-04 11:28:30 -07001027 *self*, but in *tz*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00001028
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001029 If provided, *tz* must be an instance of a :class:`tzinfo` subclass, and its
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001030 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. If *self*
1031 is naive (``self.tzinfo is None``), it is presumed to represent time in the
1032 system timezone.
Georg Brandl116aa622007-08-15 14:28:22 +00001033
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001034 If called without arguments (or with ``tz=None``) the system local
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001035 timezone is assumed for the target timezone. The ``.tzinfo`` attribute of the converted
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001036 datetime instance will be set to an instance of :class:`timezone`
1037 with the zone name and offset obtained from the OS.
1038
Georg Brandl116aa622007-08-15 14:28:22 +00001039 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001040 adjustment of date or time data is performed. Else the result is local
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001041 time in the timezone *tz*, representing the same UTC time as *self*: after
1042 ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will have
1043 the same date and time data as ``dt - dt.utcoffset()``.
Georg Brandl116aa622007-08-15 14:28:22 +00001044
1045 If you merely want to attach a time zone object *tz* to a datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001046 adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you
Georg Brandl116aa622007-08-15 14:28:22 +00001047 merely want to remove the time zone object from an aware datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001048 conversion of date and time data, use ``dt.replace(tzinfo=None)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001049
1050 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
1051 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
1052 Ignoring error cases, :meth:`astimezone` acts like::
1053
1054 def astimezone(self, tz):
1055 if self.tzinfo is tz:
1056 return self
1057 # Convert self to UTC, and attach the new time zone object.
1058 utc = (self - self.utcoffset()).replace(tzinfo=tz)
1059 # Convert from UTC to tz's local time.
1060 return tz.fromutc(utc)
1061
Georg Brandlee0be402012-06-26 09:14:40 +02001062 .. versionchanged:: 3.3
1063 *tz* now can be omitted.
1064
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001065 .. versionchanged:: 3.6
1066 The :meth:`astimezone` method can now be called on naive instances that
1067 are presumed to represent system local time.
1068
Georg Brandl116aa622007-08-15 14:28:22 +00001069
1070.. method:: datetime.utcoffset()
1071
Martin Panter16c7cfd2016-04-01 21:48:24 +00001072 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001073 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001074 return ``None`` or a :class:`timedelta` object with magnitude less than one day.
1075
1076 .. versionchanged:: 3.7
1077 The UTC offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001078
1079
1080.. method:: datetime.dst()
1081
Martin Panter16c7cfd2016-04-01 21:48:24 +00001082 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001083 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001084 ``None`` or a :class:`timedelta` object with magnitude less than one day.
1085
1086 .. versionchanged:: 3.7
1087 The DST offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001088
1089
1090.. method:: datetime.tzname()
1091
Martin Panter16c7cfd2016-04-01 21:48:24 +00001092 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001093 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
1094 ``None`` or a string object,
1095
1096
1097.. method:: datetime.timetuple()
1098
1099 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
1100 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
Alexander Belopolsky64912482010-06-08 18:59:20 +00001101 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
1102 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
1103 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
Martin Panter16c7cfd2016-04-01 21:48:24 +00001104 of the result is set according to the :meth:`dst` method: :attr:`.tzinfo` is
Georg Brandl682d7e02010-10-06 10:26:05 +00001105 ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
Alexander Belopolsky64912482010-06-08 18:59:20 +00001106 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
Alexander Belopolskyda62f2f2010-06-09 17:11:01 +00001107 else :attr:`tm_isdst` is set to ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +00001108
1109
1110.. method:: datetime.utctimetuple()
1111
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001112 If :class:`.datetime` instance *d* is naive, this is the same as
Georg Brandl116aa622007-08-15 14:28:22 +00001113 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
1114 ``d.dst()`` returns. DST is never in effect for a UTC time.
1115
1116 If *d* is aware, *d* is normalized to UTC time, by subtracting
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00001117 ``d.utcoffset()``, and a :class:`time.struct_time` for the
1118 normalized time is returned. :attr:`tm_isdst` is forced to 0. Note
1119 that an :exc:`OverflowError` may be raised if *d*.year was
1120 ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
Georg Brandl116aa622007-08-15 14:28:22 +00001121 boundary.
1122
1123
1124.. method:: datetime.toordinal()
1125
1126 Return the proleptic Gregorian ordinal of the date. The same as
1127 ``self.date().toordinal()``.
1128
Alexander Belopolskya4415142012-06-08 12:33:09 -04001129.. method:: datetime.timestamp()
1130
Martin Panter16c7cfd2016-04-01 21:48:24 +00001131 Return POSIX timestamp corresponding to the :class:`.datetime`
Alexander Belopolskya4415142012-06-08 12:33:09 -04001132 instance. The return value is a :class:`float` similar to that
1133 returned by :func:`time.time`.
1134
Martin Panter16c7cfd2016-04-01 21:48:24 +00001135 Naive :class:`.datetime` instances are assumed to represent local
Alexander Belopolskya4415142012-06-08 12:33:09 -04001136 time and this method relies on the platform C :c:func:`mktime`
Martin Panter16c7cfd2016-04-01 21:48:24 +00001137 function to perform the conversion. Since :class:`.datetime`
Alexander Belopolskya4415142012-06-08 12:33:09 -04001138 supports wider range of values than :c:func:`mktime` on many
1139 platforms, this method may raise :exc:`OverflowError` for times far
1140 in the past or far in the future.
1141
Martin Panter16c7cfd2016-04-01 21:48:24 +00001142 For aware :class:`.datetime` instances, the return value is computed
Alexander Belopolskya4415142012-06-08 12:33:09 -04001143 as::
1144
1145 (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
1146
1147 .. versionadded:: 3.3
1148
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001149 .. versionchanged:: 3.6
1150 The :meth:`timestamp` method uses the :attr:`.fold` attribute to
1151 disambiguate the times during a repeated interval.
1152
Alexander Belopolskya4415142012-06-08 12:33:09 -04001153 .. note::
1154
1155 There is no method to obtain the POSIX timestamp directly from a
Martin Panter16c7cfd2016-04-01 21:48:24 +00001156 naive :class:`.datetime` instance representing UTC time. If your
Alexander Belopolskya4415142012-06-08 12:33:09 -04001157 application uses this convention and your system timezone is not
1158 set to UTC, you can obtain the POSIX timestamp by supplying
1159 ``tzinfo=timezone.utc``::
1160
1161 timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
1162
1163 or by calculating the timestamp directly::
1164
1165 timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001166
1167.. method:: datetime.weekday()
1168
1169 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
1170 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
1171
1172
1173.. method:: datetime.isoweekday()
1174
1175 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
1176 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
1177 :meth:`isocalendar`.
1178
1179
1180.. method:: datetime.isocalendar()
1181
1182 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
1183 ``self.date().isocalendar()``.
1184
1185
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001186.. method:: datetime.isoformat(sep='T', timespec='auto')
Georg Brandl116aa622007-08-15 14:28:22 +00001187
1188 Return a string representing the date and time in ISO 8601 format,
1189 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
1190 YYYY-MM-DDTHH:MM:SS
1191
1192 If :meth:`utcoffset` does not return ``None``, a 6-character string is
1193 appended, giving the UTC offset in (signed) hours and minutes:
1194 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
1195 YYYY-MM-DDTHH:MM:SS+HH:MM
1196
1197 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +00001198 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +00001199
1200 >>> from datetime import tzinfo, timedelta, datetime
1201 >>> class TZ(tzinfo):
1202 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1203 ...
1204 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1205 '2002-12-25 00:00:00-06:39'
1206
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001207 The optional argument *timespec* specifies the number of additional
1208 components of the time to include (the default is ``'auto'``).
1209 It can be one of the following:
1210
1211 - ``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0,
1212 same as ``'microseconds'`` otherwise.
1213 - ``'hours'``: Include the :attr:`hour` in the two-digit HH format.
1214 - ``'minutes'``: Include :attr:`hour` and :attr:`minute` in HH:MM format.
1215 - ``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second`
1216 in HH:MM:SS format.
1217 - ``'milliseconds'``: Include full time, but truncate fractional second
1218 part to milliseconds. HH:MM:SS.sss format.
1219 - ``'microseconds'``: Include full time in HH:MM:SS.mmmmmm format.
1220
1221 .. note::
1222
1223 Excluded time components are truncated, not rounded.
1224
1225 :exc:`ValueError` will be raised on an invalid *timespec* argument.
1226
1227
1228 >>> from datetime import datetime
Marco Buttu909a6f62017-03-18 17:59:33 +01001229 >>> datetime.now().isoformat(timespec='minutes') # doctest: +SKIP
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001230 '2002-12-25T00:00'
1231 >>> dt = datetime(2015, 1, 1, 12, 30, 59, 0)
1232 >>> dt.isoformat(timespec='microseconds')
1233 '2015-01-01T12:30:59.000000'
1234
1235 .. versionadded:: 3.6
1236 Added the *timespec* argument.
1237
Georg Brandl116aa622007-08-15 14:28:22 +00001238
1239.. method:: datetime.__str__()
1240
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001241 For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to
Georg Brandl116aa622007-08-15 14:28:22 +00001242 ``d.isoformat(' ')``.
1243
1244
1245.. method:: datetime.ctime()
1246
1247 Return a string representing the date and time, for example ``datetime(2002, 12,
1248 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1249 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
Georg Brandl60203b42010-10-06 10:11:56 +00001250 native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +00001251 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1252
1253
1254.. method:: datetime.strftime(format)
1255
1256 Return a string representing the date and time, controlled by an explicit format
David Wolever569a5fa2013-08-12 16:56:02 -04001257 string. For a complete list of formatting directives, see
1258 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001259
Georg Brandl116aa622007-08-15 14:28:22 +00001260
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001261.. method:: datetime.__format__(format)
1262
Martin Panterd5db1472016-02-08 01:34:09 +00001263 Same as :meth:`.datetime.strftime`. This makes it possible to specify a format
Martin Panterbc1ee462016-02-13 00:41:37 +00001264 string for a :class:`.datetime` object in :ref:`formatted string
1265 literals <f-strings>` and when using :meth:`str.format`. For a
David Wolever569a5fa2013-08-12 16:56:02 -04001266 complete list of formatting directives, see
1267 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001268
1269
Christian Heimesfe337bf2008-03-23 21:54:12 +00001270Examples of working with datetime objects:
1271
1272.. doctest::
1273
Christian Heimes895627f2007-12-08 17:28:33 +00001274 >>> from datetime import datetime, date, time
1275 >>> # Using datetime.combine()
1276 >>> d = date(2005, 7, 14)
1277 >>> t = time(12, 30)
1278 >>> datetime.combine(d, t)
1279 datetime.datetime(2005, 7, 14, 12, 30)
1280 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001281 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001282 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001283 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001284 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1285 >>> # Using datetime.strptime()
1286 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1287 >>> dt
1288 datetime.datetime(2006, 11, 21, 16, 30)
1289 >>> # Using datetime.timetuple() to get tuple of all attributes
1290 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001291 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001292 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001293 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001294 2006 # year
1295 11 # month
1296 21 # day
1297 16 # hour
1298 30 # minute
1299 0 # second
1300 1 # weekday (0 = Monday)
1301 325 # number of days since 1st January
1302 -1 # dst - method tzinfo.dst() returned None
1303 >>> # Date in ISO format
1304 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001305 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001306 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001307 ...
1308 2006 # ISO year
1309 47 # ISO week
1310 2 # ISO weekday
1311 >>> # Formatting datetime
1312 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1313 'Tuesday, 21. November 2006 04:30PM'
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001314 >>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
1315 'The day is 21, the month is November, the time is 04:30PM.'
Christian Heimes895627f2007-12-08 17:28:33 +00001316
Christian Heimesfe337bf2008-03-23 21:54:12 +00001317Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001318
1319 >>> from datetime import timedelta, datetime, tzinfo
1320 >>> class GMT1(tzinfo):
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001321 ... def utcoffset(self, dt):
1322 ... return timedelta(hours=1) + self.dst(dt)
1323 ... def dst(self, dt):
1324 ... # DST starts last Sunday in March
Christian Heimes895627f2007-12-08 17:28:33 +00001325 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1326 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001327 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001328 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001329 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1330 ... return timedelta(hours=1)
1331 ... else:
1332 ... return timedelta(0)
1333 ... def tzname(self,dt):
1334 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001335 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001336 >>> class GMT2(tzinfo):
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001337 ... def utcoffset(self, dt):
1338 ... return timedelta(hours=2) + self.dst(dt)
1339 ... def dst(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001340 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001341 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001342 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001343 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001344 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001345 ... return timedelta(hours=1)
Christian Heimes895627f2007-12-08 17:28:33 +00001346 ... else:
1347 ... return timedelta(0)
1348 ... def tzname(self,dt):
1349 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001350 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001351 >>> gmt1 = GMT1()
1352 >>> # Daylight Saving Time
1353 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1354 >>> dt1.dst()
1355 datetime.timedelta(0)
1356 >>> dt1.utcoffset()
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +02001357 datetime.timedelta(seconds=3600)
Christian Heimes895627f2007-12-08 17:28:33 +00001358 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1359 >>> dt2.dst()
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +02001360 datetime.timedelta(seconds=3600)
Christian Heimes895627f2007-12-08 17:28:33 +00001361 >>> dt2.utcoffset()
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +02001362 datetime.timedelta(seconds=7200)
Christian Heimes895627f2007-12-08 17:28:33 +00001363 >>> # Convert datetime to another time zone
1364 >>> dt3 = dt2.astimezone(GMT2())
1365 >>> dt3 # doctest: +ELLIPSIS
1366 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1367 >>> dt2 # doctest: +ELLIPSIS
1368 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1369 >>> dt2.utctimetuple() == dt3.utctimetuple()
1370 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001371
Christian Heimes895627f2007-12-08 17:28:33 +00001372
Georg Brandl116aa622007-08-15 14:28:22 +00001373
1374.. _datetime-time:
1375
Serhiy Storchakaee1b01a2016-12-02 23:13:53 +02001376:class:`.time` Objects
1377----------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001378
1379A time object represents a (local) time of day, independent of any particular
1380day, and subject to adjustment via a :class:`tzinfo` object.
1381
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001382.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001383
1384 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001385 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001386 following ranges:
1387
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001388 * ``0 <= hour < 24``,
1389 * ``0 <= minute < 60``,
1390 * ``0 <= second < 60``,
1391 * ``0 <= microsecond < 1000000``,
1392 * ``fold in [0, 1]``.
Georg Brandl116aa622007-08-15 14:28:22 +00001393
1394 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1395 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1396
1397Class attributes:
1398
1399
1400.. attribute:: time.min
1401
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001402 The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001403
1404
1405.. attribute:: time.max
1406
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001407 The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001408
1409
1410.. attribute:: time.resolution
1411
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001412 The smallest possible difference between non-equal :class:`.time` objects,
1413 ``timedelta(microseconds=1)``, although note that arithmetic on
1414 :class:`.time` objects is not supported.
Georg Brandl116aa622007-08-15 14:28:22 +00001415
Georg Brandl116aa622007-08-15 14:28:22 +00001416
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001417Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001418
1419.. attribute:: time.hour
1420
1421 In ``range(24)``.
1422
1423
1424.. attribute:: time.minute
1425
1426 In ``range(60)``.
1427
1428
1429.. attribute:: time.second
1430
1431 In ``range(60)``.
1432
1433
1434.. attribute:: time.microsecond
1435
1436 In ``range(1000000)``.
1437
1438
1439.. attribute:: time.tzinfo
1440
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001441 The object passed as the tzinfo argument to the :class:`.time` constructor, or
Georg Brandl116aa622007-08-15 14:28:22 +00001442 ``None`` if none was passed.
1443
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001444
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001445.. attribute:: time.fold
1446
1447 In ``[0, 1]``. Used to disambiguate wall times during a repeated interval. (A
1448 repeated interval occurs when clocks are rolled back at the end of daylight saving
1449 time or when the UTC offset for the current zone is decreased for political reasons.)
1450 The value 0 (1) represents the earlier (later) of the two moments with the same wall
1451 time representation.
1452
1453 .. versionadded:: 3.6
1454
1455
Georg Brandl116aa622007-08-15 14:28:22 +00001456Supported operations:
1457
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001458* comparison of :class:`.time` to :class:`.time`, where *a* is considered less
Georg Brandl116aa622007-08-15 14:28:22 +00001459 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
Alexander Belopolsky08313822012-06-15 20:19:47 -04001460 is aware, :exc:`TypeError` is raised if an order comparison is attempted. For equality
1461 comparisons, naive instances are never equal to aware instances.
1462
1463 If both comparands are aware, and have
Martin Panter16c7cfd2016-04-01 21:48:24 +00001464 the same :attr:`~time.tzinfo` attribute, the common :attr:`~time.tzinfo` attribute is
Senthil Kumarana6bac952011-07-04 11:28:30 -07001465 ignored and the base times are compared. If both comparands are aware and
Martin Panter16c7cfd2016-04-01 21:48:24 +00001466 have different :attr:`~time.tzinfo` attributes, the comparands are first adjusted by
Senthil Kumarana6bac952011-07-04 11:28:30 -07001467 subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
1468 to stop mixed-type comparisons from falling back to the default comparison by
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001469 object address, when a :class:`.time` object is compared to an object of a
Senthil Kumaran3aac1792011-07-04 11:43:51 -07001470 different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
Senthil Kumarana6bac952011-07-04 11:28:30 -07001471 ``!=``. The latter cases return :const:`False` or :const:`True`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +00001472
Alexander Belopolsky08313822012-06-15 20:19:47 -04001473 .. versionchanged:: 3.3
Serhiy Storchakaee1b01a2016-12-02 23:13:53 +02001474 Equality comparisons between naive and aware :class:`~datetime.time` instances
Éric Araujob0f08952012-06-24 16:22:09 -04001475 don't raise :exc:`TypeError`.
Alexander Belopolsky08313822012-06-15 20:19:47 -04001476
Georg Brandl116aa622007-08-15 14:28:22 +00001477* hash, use as dict key
1478
1479* efficient pickling
1480
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05001481In boolean contexts, a :class:`.time` object is always considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +00001482
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05001483.. versionchanged:: 3.5
1484 Before Python 3.5, a :class:`.time` object was considered to be false if it
1485 represented midnight in UTC. This behavior was considered obscure and
1486 error-prone and has been removed in Python 3.5. See :issue:`13936` for full
1487 details.
Georg Brandl116aa622007-08-15 14:28:22 +00001488
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001489Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001490
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001491.. method:: time.replace(hour=self.hour, minute=self.minute, second=self.second, \
1492 microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001493
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001494 Return a :class:`.time` with the same value, except for those attributes given
Senthil Kumarana6bac952011-07-04 11:28:30 -07001495 new values by whichever keyword arguments are specified. Note that
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001496 ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
1497 aware :class:`.time`, without conversion of the time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001498
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001499 .. versionadded:: 3.6
1500 Added the ``fold`` argument.
1501
Georg Brandl116aa622007-08-15 14:28:22 +00001502
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001503.. method:: time.isoformat(timespec='auto')
Georg Brandl116aa622007-08-15 14:28:22 +00001504
1505 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001506 :attr:`microsecond` is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
Georg Brandl116aa622007-08-15 14:28:22 +00001507 6-character string is appended, giving the UTC offset in (signed) hours and
1508 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1509
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001510 The optional argument *timespec* specifies the number of additional
1511 components of the time to include (the default is ``'auto'``).
1512 It can be one of the following:
1513
1514 - ``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0,
1515 same as ``'microseconds'`` otherwise.
1516 - ``'hours'``: Include the :attr:`hour` in the two-digit HH format.
1517 - ``'minutes'``: Include :attr:`hour` and :attr:`minute` in HH:MM format.
1518 - ``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second`
1519 in HH:MM:SS format.
1520 - ``'milliseconds'``: Include full time, but truncate fractional second
1521 part to milliseconds. HH:MM:SS.sss format.
1522 - ``'microseconds'``: Include full time in HH:MM:SS.mmmmmm format.
1523
1524 .. note::
1525
1526 Excluded time components are truncated, not rounded.
1527
1528 :exc:`ValueError` will be raised on an invalid *timespec* argument.
1529
1530
1531 >>> from datetime import time
Berker Peksag94f89a62016-06-04 21:36:53 -07001532 >>> time(hour=12, minute=34, second=56, microsecond=123456).isoformat(timespec='minutes')
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001533 '12:34'
Berker Peksag94f89a62016-06-04 21:36:53 -07001534 >>> dt = time(hour=12, minute=34, second=56, microsecond=0)
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001535 >>> dt.isoformat(timespec='microseconds')
1536 '12:34:56.000000'
1537 >>> dt.isoformat(timespec='auto')
1538 '12:34:56'
1539
1540 .. versionadded:: 3.6
1541 Added the *timespec* argument.
1542
Georg Brandl116aa622007-08-15 14:28:22 +00001543
1544.. method:: time.__str__()
1545
1546 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1547
1548
1549.. method:: time.strftime(format)
1550
David Wolever569a5fa2013-08-12 16:56:02 -04001551 Return a string representing the time, controlled by an explicit format
1552 string. For a complete list of formatting directives, see
David Woleverbbf4a462013-08-12 17:15:36 -04001553 :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001554
1555
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001556.. method:: time.__format__(format)
1557
Martin Panterd5db1472016-02-08 01:34:09 +00001558 Same as :meth:`.time.strftime`. This makes it possible to specify a format string
Martin Panterbc1ee462016-02-13 00:41:37 +00001559 for a :class:`.time` object in :ref:`formatted string
1560 literals <f-strings>` and when using :meth:`str.format`. For a
David Wolever569a5fa2013-08-12 16:56:02 -04001561 complete list of formatting directives, see
1562 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001563
1564
Georg Brandl116aa622007-08-15 14:28:22 +00001565.. method:: time.utcoffset()
1566
Martin Panter16c7cfd2016-04-01 21:48:24 +00001567 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001568 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001569 return ``None`` or a :class:`timedelta` object with magnitude less than one day.
1570
1571 .. versionchanged:: 3.7
1572 The UTC offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001573
1574
1575.. method:: time.dst()
1576
Martin Panter16c7cfd2016-04-01 21:48:24 +00001577 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001578 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001579 ``None``, or a :class:`timedelta` object with magnitude less than one day.
Georg Brandl116aa622007-08-15 14:28:22 +00001580
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001581 .. versionchanged:: 3.7
1582 The DST offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001583
1584.. method:: time.tzname()
1585
Martin Panter16c7cfd2016-04-01 21:48:24 +00001586 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001587 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1588 return ``None`` or a string object.
1589
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001590
Christian Heimesfe337bf2008-03-23 21:54:12 +00001591Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001592
Xiang Zhang6721c7c2016-12-27 12:23:59 +08001593 >>> from datetime import time, tzinfo, timedelta
Christian Heimes895627f2007-12-08 17:28:33 +00001594 >>> class GMT1(tzinfo):
1595 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001596 ... return timedelta(hours=1)
1597 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001598 ... return timedelta(0)
1599 ... def tzname(self,dt):
1600 ... return "Europe/Prague"
1601 ...
1602 >>> t = time(12, 10, 30, tzinfo=GMT1())
1603 >>> t # doctest: +ELLIPSIS
1604 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1605 >>> gmt = GMT1()
1606 >>> t.isoformat()
1607 '12:10:30+01:00'
1608 >>> t.dst()
1609 datetime.timedelta(0)
1610 >>> t.tzname()
1611 'Europe/Prague'
1612 >>> t.strftime("%H:%M:%S %Z")
1613 '12:10:30 Europe/Prague'
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001614 >>> 'The {} is {:%H:%M}.'.format("time", t)
1615 'The time is 12:10.'
Christian Heimes895627f2007-12-08 17:28:33 +00001616
Georg Brandl116aa622007-08-15 14:28:22 +00001617
1618.. _datetime-tzinfo:
1619
1620:class:`tzinfo` Objects
1621-----------------------
1622
Martin Panter16c7cfd2016-04-01 21:48:24 +00001623.. class:: tzinfo()
Georg Brandl116aa622007-08-15 14:28:22 +00001624
Martin Panter16c7cfd2016-04-01 21:48:24 +00001625 This is an abstract base class, meaning that this class should not be
1626 instantiated directly. You need to derive a concrete subclass, and (at least)
1627 supply implementations of the standard :class:`tzinfo` methods needed by the
1628 :class:`.datetime` methods you use. The :mod:`datetime` module supplies
1629 a simple concrete subclass of :class:`tzinfo`, :class:`timezone`, which can represent
1630 timezones with fixed offset from UTC such as UTC itself or North American EST and
1631 EDT.
Georg Brandl116aa622007-08-15 14:28:22 +00001632
Martin Panter16c7cfd2016-04-01 21:48:24 +00001633 An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1634 constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
1635 view their attributes as being in local time, and the :class:`tzinfo` object
1636 supports methods revealing offset of local time from UTC, the name of the time
1637 zone, and DST offset, all relative to a date or time object passed to them.
Georg Brandl116aa622007-08-15 14:28:22 +00001638
Martin Panter16c7cfd2016-04-01 21:48:24 +00001639 Special requirement for pickling: A :class:`tzinfo` subclass must have an
1640 :meth:`__init__` method that can be called with no arguments, else it can be
1641 pickled but possibly not unpickled again. This is a technical requirement that
1642 may be relaxed in the future.
1643
1644 A concrete subclass of :class:`tzinfo` may need to implement the following
1645 methods. Exactly which methods are needed depends on the uses made of aware
1646 :mod:`datetime` objects. If in doubt, simply implement all of them.
Georg Brandl116aa622007-08-15 14:28:22 +00001647
1648
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001649.. method:: tzinfo.utcoffset(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001650
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001651 Return offset of local time from UTC, as a :class:`timedelta` object that is
1652 positive east of UTC. If local time is
Georg Brandl116aa622007-08-15 14:28:22 +00001653 west of UTC, this should be negative. Note that this is intended to be the
1654 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1655 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1656 the UTC offset isn't known, return ``None``. Else the value returned must be a
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001657 :class:`timedelta` object strictly between ``-timedelta(hours=24)`` and
1658 ``timedelta(hours=24)`` (the magnitude of the offset must be less
Georg Brandl116aa622007-08-15 14:28:22 +00001659 than one day). Most implementations of :meth:`utcoffset` will probably look
1660 like one of these two::
1661
1662 return CONSTANT # fixed-offset class
1663 return CONSTANT + self.dst(dt) # daylight-aware class
1664
1665 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1666 ``None`` either.
1667
1668 The default implementation of :meth:`utcoffset` raises
1669 :exc:`NotImplementedError`.
1670
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001671 .. versionchanged:: 3.7
1672 The UTC offset is not restricted to a whole number of minutes.
1673
Georg Brandl116aa622007-08-15 14:28:22 +00001674
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001675.. method:: tzinfo.dst(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001676
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001677 Return the daylight saving time (DST) adjustment, as a :class:`timedelta`
1678 object or
Georg Brandl116aa622007-08-15 14:28:22 +00001679 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1680 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1681 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1682 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1683 no need to consult :meth:`dst` unless you're interested in obtaining DST info
Martin Panter16c7cfd2016-04-01 21:48:24 +00001684 separately. For example, :meth:`datetime.timetuple` calls its :attr:`~.datetime.tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -07001685 attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
1686 should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
1687 DST changes when crossing time zones.
Georg Brandl116aa622007-08-15 14:28:22 +00001688
1689 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1690 daylight times must be consistent in this sense:
1691
1692 ``tz.utcoffset(dt) - tz.dst(dt)``
1693
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001694 must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo ==
Georg Brandl116aa622007-08-15 14:28:22 +00001695 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1696 zone's "standard offset", which should not depend on the date or the time, but
1697 only on geographic location. The implementation of :meth:`datetime.astimezone`
1698 relies on this, but cannot detect violations; it's the programmer's
1699 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1700 this, it may be able to override the default implementation of
1701 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1702
1703 Most implementations of :meth:`dst` will probably look like one of these two::
1704
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001705 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001706 # a fixed-offset class: doesn't account for DST
1707 return timedelta(0)
1708
1709 or ::
1710
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001711 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001712 # Code to set dston and dstoff to the time zone's DST
1713 # transition times based on the input dt.year, and expressed
1714 # in standard local time. Then
1715
1716 if dston <= dt.replace(tzinfo=None) < dstoff:
1717 return timedelta(hours=1)
1718 else:
1719 return timedelta(0)
1720
1721 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1722
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001723 .. versionchanged:: 3.7
1724 The DST offset is not restricted to a whole number of minutes.
1725
Georg Brandl116aa622007-08-15 14:28:22 +00001726
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001727.. method:: tzinfo.tzname(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001728
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001729 Return the time zone name corresponding to the :class:`.datetime` object *dt*, as
Georg Brandl116aa622007-08-15 14:28:22 +00001730 a string. Nothing about string names is defined by the :mod:`datetime` module,
1731 and there's no requirement that it mean anything in particular. For example,
1732 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1733 valid replies. Return ``None`` if a string name isn't known. Note that this is
1734 a method rather than a fixed string primarily because some :class:`tzinfo`
1735 subclasses will wish to return different names depending on the specific value
1736 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1737 daylight time.
1738
1739 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1740
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001741
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001742These methods are called by a :class:`.datetime` or :class:`.time` object, in
1743response to their methods of the same names. A :class:`.datetime` object passes
1744itself as the argument, and a :class:`.time` object passes ``None`` as the
Georg Brandl116aa622007-08-15 14:28:22 +00001745argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001746accept a *dt* argument of ``None``, or of class :class:`.datetime`.
Georg Brandl116aa622007-08-15 14:28:22 +00001747
1748When ``None`` is passed, it's up to the class designer to decide the best
1749response. For example, returning ``None`` is appropriate if the class wishes to
1750say that time objects don't participate in the :class:`tzinfo` protocols. It
1751may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1752there is no other convention for discovering the standard offset.
1753
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001754When a :class:`.datetime` object is passed in response to a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +00001755method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1756rely on this, unless user code calls :class:`tzinfo` methods directly. The
1757intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1758time, and not need worry about objects in other timezones.
1759
1760There is one more :class:`tzinfo` method that a subclass may wish to override:
1761
1762
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001763.. method:: tzinfo.fromutc(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001764
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001765 This is called from the default :class:`datetime.astimezone()`
1766 implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s
1767 date and time data are to be viewed as expressing a UTC time. The purpose
1768 of :meth:`fromutc` is to adjust the date and time data, returning an
Senthil Kumarana6bac952011-07-04 11:28:30 -07001769 equivalent datetime in *self*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00001770
1771 Most :class:`tzinfo` subclasses should be able to inherit the default
1772 :meth:`fromutc` implementation without problems. It's strong enough to handle
1773 fixed-offset time zones, and time zones accounting for both standard and
1774 daylight time, and the latter even if the DST transition times differ in
1775 different years. An example of a time zone the default :meth:`fromutc`
1776 implementation may not handle correctly in all cases is one where the standard
1777 offset (from UTC) depends on the specific date and time passed, which can happen
1778 for political reasons. The default implementations of :meth:`astimezone` and
1779 :meth:`fromutc` may not produce the result you want if the result is one of the
1780 hours straddling the moment the standard offset changes.
1781
1782 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1783 like::
1784
1785 def fromutc(self, dt):
1786 # raise ValueError error if dt.tzinfo is not self
1787 dtoff = dt.utcoffset()
1788 dtdst = dt.dst()
1789 # raise ValueError if dtoff is None or dtdst is None
1790 delta = dtoff - dtdst # this is self's standard offset
1791 if delta:
1792 dt += delta # convert to standard local time
1793 dtdst = dt.dst()
1794 # raise ValueError if dtdst is None
1795 if dtdst:
1796 return dt + dtdst
1797 else:
1798 return dt
1799
Marco Buttu909a6f62017-03-18 17:59:33 +01001800In the following :download:`tzinfo_examples.py
1801<../includes/tzinfo_examples.py>` file there are some examples of
1802:class:`tzinfo` classes:
Georg Brandl116aa622007-08-15 14:28:22 +00001803
Marco Buttu909a6f62017-03-18 17:59:33 +01001804.. literalinclude:: ../includes/tzinfo_examples.py
Georg Brandl116aa622007-08-15 14:28:22 +00001805
Georg Brandl116aa622007-08-15 14:28:22 +00001806Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1807subclass accounting for both standard and daylight time, at the DST transition
1808points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00001809minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
18101:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001811
1812 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1813 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1814 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1815
1816 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1817
1818 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1819
1820When DST starts (the "start" line), the local wall clock leaps from 1:59 to
18213:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1822``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001823begins. For example, at the Spring forward transition of 2016, we get
1824
Marco Buttu909a6f62017-03-18 17:59:33 +01001825 >>> from datetime import datetime, timezone
1826 >>> from tzinfo_examples import HOUR, Eastern
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001827 >>> u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc)
1828 >>> for i in range(4):
1829 ... u = u0 + i*HOUR
1830 ... t = u.astimezone(Eastern)
1831 ... print(u.time(), 'UTC =', t.time(), t.tzname())
1832 ...
1833 05:00:00 UTC = 00:00:00 EST
1834 06:00:00 UTC = 01:00:00 EST
1835 07:00:00 UTC = 03:00:00 EDT
1836 08:00:00 UTC = 04:00:00 EDT
1837
Georg Brandl116aa622007-08-15 14:28:22 +00001838
1839When DST ends (the "end" line), there's a potentially worse problem: there's an
1840hour that can't be spelled unambiguously in local wall time: the last hour of
1841daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1842daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1843to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1844:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1845hours into the same local hour then. In the Eastern example, UTC times of the
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001846form 5:MM and 6:MM both map to 1:MM when converted to Eastern, but earlier times
1847have the :attr:`~datetime.fold` attribute set to 0 and the later times have it set to 1.
1848For example, at the Fall back transition of 2016, we get
Georg Brandl116aa622007-08-15 14:28:22 +00001849
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001850 >>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
1851 >>> for i in range(4):
1852 ... u = u0 + i*HOUR
1853 ... t = u.astimezone(Eastern)
1854 ... print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
1855 ...
1856 04:00:00 UTC = 00:00:00 EDT 0
1857 05:00:00 UTC = 01:00:00 EDT 0
1858 06:00:00 UTC = 01:00:00 EST 1
1859 07:00:00 UTC = 02:00:00 EST 0
1860
1861Note that the :class:`datetime` instances that differ only by the value of the
1862:attr:`~datetime.fold` attribute are considered equal in comparisons.
1863
1864Applications that can't bear wall-time ambiguities should explicitly check the
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001865value of the :attr:`~datetime.fold` attribute or avoid using hybrid
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001866:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`,
1867or any other fixed-offset :class:`tzinfo` subclass (such as a class representing
1868only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
1869
Sandro Tosid11d0d62012-04-24 19:46:06 +02001870.. seealso::
1871
wim glenn53f2af12017-06-06 12:54:41 -05001872 `dateutil.tz <https://dateutil.readthedocs.io/en/stable/tz.html>`_
Benjamin Peterson9b29acd2014-06-22 16:26:39 -07001873 The standard library has :class:`timezone` class for handling arbitrary
1874 fixed offsets from UTC and :attr:`timezone.utc` as UTC timezone instance.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001875
wim glenn53f2af12017-06-06 12:54:41 -05001876 *dateutil.tz* library brings the *IANA timezone database* (also known as the
Benjamin Peterson9b29acd2014-06-22 16:26:39 -07001877 Olson database) to Python and its usage is recommended.
Sandro Tosi100b8892012-04-28 11:19:37 +02001878
Serhiy Storchaka6dff0202016-05-07 10:49:07 +03001879 `IANA timezone database <https://www.iana.org/time-zones>`_
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001880 The Time Zone Database (often called tz, tzdata or zoneinfo) contains code and
Sandro Tosi100b8892012-04-28 11:19:37 +02001881 data that represent the history of local time for many representative
1882 locations around the globe. It is updated periodically to reflect changes
1883 made by political bodies to time zone boundaries, UTC offsets, and
1884 daylight-saving rules.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001885
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001886
1887.. _datetime-timezone:
1888
1889:class:`timezone` Objects
1890--------------------------
1891
Alexander Belopolsky6d3c9a62011-05-04 10:28:26 -04001892The :class:`timezone` class is a subclass of :class:`tzinfo`, each
1893instance of which represents a timezone defined by a fixed offset from
1894UTC. Note that objects of this class cannot be used to represent
1895timezone information in the locations where different offsets are used
1896in different days of the year or where historical changes have been
1897made to civil time.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001898
1899
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001900.. class:: timezone(offset, name=None)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001901
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001902 The *offset* argument must be specified as a :class:`timedelta`
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001903 object representing the difference between the local time and UTC. It must
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001904 be strictly between ``-timedelta(hours=24)`` and
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001905 ``timedelta(hours=24)``, otherwise :exc:`ValueError` is raised.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001906
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001907 The *name* argument is optional. If specified it must be a string that
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04001908 will be used as the value returned by the :meth:`datetime.tzname` method.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001909
Benjamin Peterson9b29acd2014-06-22 16:26:39 -07001910 .. versionadded:: 3.2
1911
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001912 .. versionchanged:: 3.7
1913 The UTC offset is not restricted to a whole number of minutes.
1914
1915
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001916.. method:: timezone.utcoffset(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001917
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001918 Return the fixed value specified when the :class:`timezone` instance is
1919 constructed. The *dt* argument is ignored. The return value is a
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001920 :class:`timedelta` instance equal to the difference between the
1921 local time and UTC.
1922
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001923 .. versionchanged:: 3.7
1924 The UTC offset is not restricted to a whole number of minutes.
1925
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001926.. method:: timezone.tzname(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001927
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04001928 Return the fixed value specified when the :class:`timezone` instance
1929 is constructed. If *name* is not provided in the constructor, the
1930 name returned by ``tzname(dt)`` is generated from the value of the
1931 ``offset`` as follows. If *offset* is ``timedelta(0)``, the name
1932 is "UTC", otherwise it is a string 'UTC±HH:MM', where ± is the sign
1933 of ``offset``, HH and MM are two digits of ``offset.hours`` and
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001934 ``offset.minutes`` respectively.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001935
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04001936 .. versionchanged:: 3.6
Berker Peksagdf326eb2015-09-09 18:32:50 +03001937 Name generated from ``offset=timedelta(0)`` is now plain 'UTC', not
1938 'UTC+00:00'.
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04001939
1940
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001941.. method:: timezone.dst(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001942
1943 Always returns ``None``.
1944
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001945.. method:: timezone.fromutc(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001946
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001947 Return ``dt + offset``. The *dt* argument must be an aware
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001948 :class:`.datetime` instance, with ``tzinfo`` set to ``self``.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001949
1950Class attributes:
1951
1952.. attribute:: timezone.utc
1953
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001954 The UTC timezone, ``timezone(timedelta(0))``.
Georg Brandl48310cd2009-01-03 21:18:54 +00001955
Georg Brandl116aa622007-08-15 14:28:22 +00001956
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001957.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00001958
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001959:meth:`strftime` and :meth:`strptime` Behavior
1960----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001961
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001962:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
Georg Brandl116aa622007-08-15 14:28:22 +00001963``strftime(format)`` method, to create a string representing the time under the
1964control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1965acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1966although not all objects support a :meth:`timetuple` method.
1967
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001968Conversely, the :meth:`datetime.strptime` class method creates a
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001969:class:`.datetime` object from a string representing a date and time and a
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001970corresponding format string. ``datetime.strptime(date_string, format)`` is
1971equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1972
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001973For :class:`.time` objects, the format codes for year, month, and day should not
Georg Brandl116aa622007-08-15 14:28:22 +00001974be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001975is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00001976
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001977For :class:`date` objects, the format codes for hours, minutes, seconds, and
1978microseconds should not be used, as :class:`date` objects have no such
1979values. If they're used anyway, ``0`` is substituted for them.
1980
Georg Brandl116aa622007-08-15 14:28:22 +00001981The full set of format codes supported varies across platforms, because Python
1982calls the platform C library's :func:`strftime` function, and platform
Georg Brandlb7117af2013-10-13 18:28:25 +02001983variations are common. To see the full set of format codes supported on your
1984platform, consult the :manpage:`strftime(3)` documentation.
Christian Heimes895627f2007-12-08 17:28:33 +00001985
1986The following is a list of all the format codes that the C standard (1989
1987version) requires, and these work on all platforms with a standard C
1988implementation. Note that the 1999 version of the C standard added additional
1989format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001990
David Wolever569a5fa2013-08-12 16:56:02 -04001991+-----------+--------------------------------+------------------------+-------+
1992| Directive | Meaning | Example | Notes |
1993+===========+================================+========================+=======+
1994| ``%a`` | Weekday as locale's || Sun, Mon, ..., Sat | \(1) |
1995| | abbreviated name. | (en_US); | |
1996| | || So, Mo, ..., Sa | |
1997| | | (de_DE) | |
1998+-----------+--------------------------------+------------------------+-------+
1999| ``%A`` | Weekday as locale's full name. || Sunday, Monday, ..., | \(1) |
2000| | | Saturday (en_US); | |
2001| | || Sonntag, Montag, ..., | |
2002| | | Samstag (de_DE) | |
2003+-----------+--------------------------------+------------------------+-------+
2004| ``%w`` | Weekday as a decimal number, | 0, 1, ..., 6 | |
2005| | where 0 is Sunday and 6 is | | |
2006| | Saturday. | | |
2007+-----------+--------------------------------+------------------------+-------+
2008| ``%d`` | Day of the month as a | 01, 02, ..., 31 | |
2009| | zero-padded decimal number. | | |
2010+-----------+--------------------------------+------------------------+-------+
2011| ``%b`` | Month as locale's abbreviated || Jan, Feb, ..., Dec | \(1) |
2012| | name. | (en_US); | |
2013| | || Jan, Feb, ..., Dez | |
2014| | | (de_DE) | |
2015+-----------+--------------------------------+------------------------+-------+
2016| ``%B`` | Month as locale's full name. || January, February, | \(1) |
2017| | | ..., December (en_US);| |
2018| | || Januar, Februar, ..., | |
2019| | | Dezember (de_DE) | |
2020+-----------+--------------------------------+------------------------+-------+
2021| ``%m`` | Month as a zero-padded | 01, 02, ..., 12 | |
2022| | decimal number. | | |
2023+-----------+--------------------------------+------------------------+-------+
2024| ``%y`` | Year without century as a | 00, 01, ..., 99 | |
2025| | zero-padded decimal number. | | |
2026+-----------+--------------------------------+------------------------+-------+
2027| ``%Y`` | Year with century as a decimal | 0001, 0002, ..., 2013, | \(2) |
David Wolever5d07e702013-08-14 14:41:48 -04002028| | number. | 2014, ..., 9998, 9999 | |
David Wolever569a5fa2013-08-12 16:56:02 -04002029+-----------+--------------------------------+------------------------+-------+
2030| ``%H`` | Hour (24-hour clock) as a | 00, 01, ..., 23 | |
2031| | zero-padded decimal number. | | |
2032+-----------+--------------------------------+------------------------+-------+
2033| ``%I`` | Hour (12-hour clock) as a | 01, 02, ..., 12 | |
2034| | zero-padded decimal number. | | |
2035+-----------+--------------------------------+------------------------+-------+
2036| ``%p`` | Locale's equivalent of either || AM, PM (en_US); | \(1), |
2037| | AM or PM. || am, pm (de_DE) | \(3) |
2038+-----------+--------------------------------+------------------------+-------+
2039| ``%M`` | Minute as a zero-padded | 00, 01, ..., 59 | |
2040| | decimal number. | | |
2041+-----------+--------------------------------+------------------------+-------+
2042| ``%S`` | Second as a zero-padded | 00, 01, ..., 59 | \(4) |
2043| | decimal number. | | |
2044+-----------+--------------------------------+------------------------+-------+
2045| ``%f`` | Microsecond as a decimal | 000000, 000001, ..., | \(5) |
2046| | number, zero-padded on the | 999999 | |
2047| | left. | | |
2048+-----------+--------------------------------+------------------------+-------+
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002049| ``%z`` | UTC offset in the form | (empty), +0000, -0400, | \(6) |
2050| | ±HHMM[SS] (empty string if the | +1030 | |
Berker Peksagbace9762016-05-04 23:25:44 +03002051| | object is naive). | | |
David Wolever569a5fa2013-08-12 16:56:02 -04002052+-----------+--------------------------------+------------------------+-------+
2053| ``%Z`` | Time zone name (empty string | (empty), UTC, EST, CST | |
2054| | if the object is naive). | | |
2055+-----------+--------------------------------+------------------------+-------+
2056| ``%j`` | Day of the year as a | 001, 002, ..., 366 | |
2057| | zero-padded decimal number. | | |
2058+-----------+--------------------------------+------------------------+-------+
2059| ``%U`` | Week number of the year | 00, 01, ..., 53 | \(7) |
2060| | (Sunday as the first day of | | |
2061| | the week) as a zero padded | | |
2062| | decimal number. All days in a | | |
2063| | new year preceding the first | | |
2064| | Sunday are considered to be in | | |
2065| | week 0. | | |
2066+-----------+--------------------------------+------------------------+-------+
2067| ``%W`` | Week number of the year | 00, 01, ..., 53 | \(7) |
2068| | (Monday as the first day of | | |
2069| | the week) as a decimal number. | | |
2070| | All days in a new year | | |
2071| | preceding the first Monday | | |
2072| | are considered to be in | | |
2073| | week 0. | | |
2074+-----------+--------------------------------+------------------------+-------+
2075| ``%c`` | Locale's appropriate date and || Tue Aug 16 21:30:00 | \(1) |
2076| | time representation. | 1988 (en_US); | |
2077| | || Di 16 Aug 21:30:00 | |
2078| | | 1988 (de_DE) | |
2079+-----------+--------------------------------+------------------------+-------+
2080| ``%x`` | Locale's appropriate date || 08/16/88 (None); | \(1) |
2081| | representation. || 08/16/1988 (en_US); | |
2082| | || 16.08.1988 (de_DE) | |
2083+-----------+--------------------------------+------------------------+-------+
2084| ``%X`` | Locale's appropriate time || 21:30:00 (en_US); | \(1) |
2085| | representation. || 21:30:00 (de_DE) | |
2086+-----------+--------------------------------+------------------------+-------+
2087| ``%%`` | A literal ``'%'`` character. | % | |
2088+-----------+--------------------------------+------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00002089
Alexander Belopolsky68713e42015-10-06 13:29:56 -04002090Several additional directives not required by the C89 standard are included for
2091convenience. These parameters all correspond to ISO 8601 date values. These
2092may not be available on all platforms when used with the :meth:`strftime`
2093method. The ISO 8601 year and ISO 8601 week directives are not interchangeable
2094with the year and week number directives above. Calling :meth:`strptime` with
2095incomplete or ambiguous ISO 8601 directives will raise a :exc:`ValueError`.
2096
2097+-----------+--------------------------------+------------------------+-------+
2098| Directive | Meaning | Example | Notes |
2099+===========+================================+========================+=======+
2100| ``%G`` | ISO 8601 year with century | 0001, 0002, ..., 2013, | \(8) |
2101| | representing the year that | 2014, ..., 9998, 9999 | |
2102| | contains the greater part of | | |
2103| | the ISO week (``%V``). | | |
2104+-----------+--------------------------------+------------------------+-------+
2105| ``%u`` | ISO 8601 weekday as a decimal | 1, 2, ..., 7 | |
2106| | number where 1 is Monday. | | |
2107+-----------+--------------------------------+------------------------+-------+
2108| ``%V`` | ISO 8601 week as a decimal | 01, 02, ..., 53 | \(8) |
2109| | number with Monday as | | |
2110| | the first day of the week. | | |
2111| | Week 01 is the week containing | | |
2112| | Jan 4. | | |
2113+-----------+--------------------------------+------------------------+-------+
2114
2115.. versionadded:: 3.6
2116 ``%G``, ``%u`` and ``%V`` were added.
2117
Christian Heimes895627f2007-12-08 17:28:33 +00002118Notes:
2119
2120(1)
David Wolever569a5fa2013-08-12 16:56:02 -04002121 Because the format depends on the current locale, care should be taken when
2122 making assumptions about the output value. Field orderings will vary (for
2123 example, "month/day/year" versus "day/month/year"), and the output may
2124 contain Unicode characters encoded using the locale's default encoding (for
Georg Brandlad321532013-10-29 08:05:10 +01002125 example, if the current locale is ``ja_JP``, the default encoding could be
David Wolever569a5fa2013-08-12 16:56:02 -04002126 any one of ``eucJP``, ``SJIS``, or ``utf-8``; use :meth:`locale.getlocale`
2127 to determine the current locale's encoding).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002128
2129(2)
David Wolever569a5fa2013-08-12 16:56:02 -04002130 The :meth:`strptime` method can parse years in the full [1, 9999] range, but
2131 years < 1000 must be zero-filled to 4-digit width.
Alexander Belopolsky085556a2011-01-10 23:28:33 +00002132
2133 .. versionchanged:: 3.2
2134 In previous versions, :meth:`strftime` method was restricted to
2135 years >= 1900.
2136
Alexander Belopolsky5611a1c2011-05-02 14:14:48 -04002137 .. versionchanged:: 3.3
2138 In version 3.2, :meth:`strftime` method was restricted to
2139 years >= 1000.
2140
David Wolever569a5fa2013-08-12 16:56:02 -04002141(3)
2142 When used with the :meth:`strptime` method, the ``%p`` directive only affects
2143 the output hour field if the ``%I`` directive is used to parse the hour.
Alexander Belopolskyca94f552010-06-17 18:30:34 +00002144
David Wolever569a5fa2013-08-12 16:56:02 -04002145(4)
2146 Unlike the :mod:`time` module, the :mod:`datetime` module does not support
2147 leap seconds.
2148
2149(5)
2150 When used with the :meth:`strptime` method, the ``%f`` directive
2151 accepts from one to six digits and zero pads on the right. ``%f`` is
2152 an extension to the set of format characters in the C standard (but
2153 implemented separately in datetime objects, and therefore always
2154 available).
2155
2156(6)
2157 For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
2158 strings.
2159
2160 For an aware object:
2161
2162 ``%z``
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002163 :meth:`utcoffset` is transformed into a string of the form
2164 ±HHMM[SS[.uuuuuu]], where HH is a 2-digit string giving the number of UTC
David Wolever569a5fa2013-08-12 16:56:02 -04002165 offset hours, and MM is a 2-digit string giving the number of UTC offset
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002166 minutes, SS is a 2-digit string string giving the number of UTC offset
2167 seconds and uuuuuu is a 2-digit string string giving the number of UTC
2168 offset microseconds. The uuuuuu part is omitted when the offset is a
2169 whole number of minutes and both the uuuuuu and the SS parts are omitted
2170 when the offset is a whole number of minutes. For example, if
2171 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
2172 replaced with the string ``'-0330'``.
2173
2174 .. versionchanged:: 3.7
2175 The UTC offset is not restricted to a whole number of minutes.
David Wolever569a5fa2013-08-12 16:56:02 -04002176
Mario Corchero32318932017-10-26 01:35:41 +01002177 .. versionchanged:: 3.7
2178 When the ``%z`` directive is provided to the :meth:`strptime` method,
2179 the UTC offsets can have a colon as a separator between hours, minutes
2180 and seconds.
2181 For example, ``'+01:00:00'`` will be parsed as an offset of one hour.
2182 In addition, providing ``'Z'`` is identical to ``'+00:00'``.
2183
David Wolever569a5fa2013-08-12 16:56:02 -04002184 ``%Z``
2185 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty
2186 string. Otherwise ``%Z`` is replaced by the returned value, which must
2187 be a string.
2188
2189 .. versionchanged:: 3.2
2190 When the ``%z`` directive is provided to the :meth:`strptime` method, an
2191 aware :class:`.datetime` object will be produced. The ``tzinfo`` of the
2192 result will be set to a :class:`timezone` instance.
2193
2194(7)
2195 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used
Alexander Belopolsky68713e42015-10-06 13:29:56 -04002196 in calculations when the day of the week and the calendar year (``%Y``)
2197 are specified.
2198
2199(8)
2200 Similar to ``%U`` and ``%W``, ``%V`` is only used in calculations when the
2201 day of the week and the ISO year (``%G``) are specified in a
2202 :meth:`strptime` format string. Also note that ``%G`` and ``%Y`` are not
Martin Panterf1579822016-05-26 06:03:33 +00002203 interchangeable.
R David Murray9075d8b2012-05-14 22:14:46 -04002204
2205.. rubric:: Footnotes
2206
2207.. [#] If, that is, we ignore the effects of Relativity