blob: 7a276b139f5eca5261489f04c707f43825d678cc [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`datetime` --- Basic date and time types
2=============================================
3
4.. module:: datetime
5 :synopsis: Basic date and time types.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Tim Peters <tim@zope.com>
8.. sectionauthor:: Tim Peters <tim@zope.com>
9.. sectionauthor:: A.M. Kuchling <amk@amk.ca>
10
Andrew Kuchling2e3743c2014-03-19 16:23:01 -040011**Source code:** :source:`Lib/datetime.py`
12
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040013--------------
14
Christian Heimes5b5e81c2007-12-31 16:14:33 +000015.. XXX what order should the types be discussed in?
Georg Brandl116aa622007-08-15 14:28:22 +000016
Georg Brandl116aa622007-08-15 14:28:22 +000017The :mod:`datetime` module supplies classes for manipulating dates and times in
18both simple and complex ways. While date and time arithmetic is supported, the
Senthil Kumarana6bac952011-07-04 11:28:30 -070019focus of the implementation is on efficient attribute extraction for output
R David Murray539f2392012-05-14 22:17:23 -040020formatting and manipulation. For related functionality, see also the
21:mod:`time` and :mod:`calendar` modules.
Georg Brandl116aa622007-08-15 14:28:22 +000022
R David Murray9075d8b2012-05-14 22:14:46 -040023There are two kinds of date and time objects: "naive" and "aware".
Georg Brandl116aa622007-08-15 14:28:22 +000024
R David Murray9075d8b2012-05-14 22:14:46 -040025An aware object has sufficient knowledge of applicable algorithmic and
26political time adjustments, such as time zone and daylight saving time
27information, to locate itself relative to other aware objects. An aware object
28is used to represent a specific moment in time that is not open to
29interpretation [#]_.
30
31A naive object does not contain enough information to unambiguously locate
32itself relative to other date/time objects. Whether a naive object represents
R David Murray539f2392012-05-14 22:17:23 -040033Coordinated Universal Time (UTC), local time, or time in some other timezone is
34purely up to the program, just like it is up to the program whether a
35particular number represents metres, miles, or mass. Naive objects are easy to
36understand and to work with, at the cost of ignoring some aspects of reality.
Georg Brandl116aa622007-08-15 14:28:22 +000037
R David Murray539f2392012-05-14 22:17:23 -040038For applications requiring aware objects, :class:`.datetime` and :class:`.time`
Martin Panter16c7cfd2016-04-01 21:48:24 +000039objects have an optional time zone information attribute, :attr:`!tzinfo`, that
R David Murray539f2392012-05-14 22:17:23 -040040can be set to an instance of a subclass of the abstract :class:`tzinfo` class.
41These :class:`tzinfo` objects capture information about the offset from UTC
42time, the time zone name, and whether Daylight Saving Time is in effect. Note
43that only one concrete :class:`tzinfo` class, the :class:`timezone` class, is
44supplied by the :mod:`datetime` module. The :class:`timezone` class can
45represent simple timezones with fixed offset from UTC, such as UTC itself or
46North American EST and EDT timezones. Supporting timezones at deeper levels of
47detail is up to the application. The rules for time adjustment across the
Alexander Belopolsky4e749a12010-06-14 14:15:50 +000048world are more political than rational, change frequently, and there is no
49standard suitable for every application aside from UTC.
Georg Brandl116aa622007-08-15 14:28:22 +000050
51The :mod:`datetime` module exports the following constants:
52
Georg Brandl116aa622007-08-15 14:28:22 +000053.. data:: MINYEAR
54
Ezio Melotti35ec7f72011-10-02 12:44:50 +030055 The smallest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl116aa622007-08-15 14:28:22 +000056 :const:`MINYEAR` is ``1``.
57
58
59.. data:: MAXYEAR
60
Ezio Melotti35ec7f72011-10-02 12:44:50 +030061 The largest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl116aa622007-08-15 14:28:22 +000062 :const:`MAXYEAR` is ``9999``.
63
64
65.. seealso::
66
67 Module :mod:`calendar`
68 General calendar related functions.
69
70 Module :mod:`time`
71 Time access and conversions.
72
73
74Available Types
75---------------
76
Georg Brandl116aa622007-08-15 14:28:22 +000077.. class:: date
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000078 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000079
80 An idealized naive date, assuming the current Gregorian calendar always was, and
81 always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and
82 :attr:`day`.
83
84
85.. class:: time
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000086 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000087
88 An idealized time, independent of any particular day, assuming that every day
89 has exactly 24\*60\*60 seconds (there is no notion of "leap seconds" here).
90 Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
Martin Panter16c7cfd2016-04-01 21:48:24 +000091 and :attr:`.tzinfo`.
Georg Brandl116aa622007-08-15 14:28:22 +000092
93
94.. class:: datetime
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000095 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000096
97 A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`,
98 :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
Martin Panter16c7cfd2016-04-01 21:48:24 +000099 and :attr:`.tzinfo`.
Georg Brandl116aa622007-08-15 14:28:22 +0000100
101
102.. class:: timedelta
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000103 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000104
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300105 A duration expressing the difference between two :class:`date`, :class:`.time`,
106 or :class:`.datetime` instances to microsecond resolution.
Georg Brandl116aa622007-08-15 14:28:22 +0000107
108
109.. class:: tzinfo
Martin Panter16c7cfd2016-04-01 21:48:24 +0000110 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000111
112 An abstract base class for time zone information objects. These are used by the
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300113 :class:`.datetime` and :class:`.time` classes to provide a customizable notion of
Georg Brandl116aa622007-08-15 14:28:22 +0000114 time adjustment (for example, to account for time zone and/or daylight saving
115 time).
116
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000117.. class:: timezone
Martin Panter16c7cfd2016-04-01 21:48:24 +0000118 :noindex:
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000119
120 A class that implements the :class:`tzinfo` abstract base class as a
121 fixed offset from the UTC.
122
123 .. versionadded:: 3.2
124
125
Georg Brandl116aa622007-08-15 14:28:22 +0000126Objects of these types are immutable.
127
128Objects of the :class:`date` type are always naive.
129
R David Murray9075d8b2012-05-14 22:14:46 -0400130An object of type :class:`.time` or :class:`.datetime` may be naive or aware.
131A :class:`.datetime` object *d* is aware if ``d.tzinfo`` is not ``None`` and
132``d.tzinfo.utcoffset(d)`` does not return ``None``. If ``d.tzinfo`` is
133``None``, or if ``d.tzinfo`` is not ``None`` but ``d.tzinfo.utcoffset(d)``
134returns ``None``, *d* is naive. A :class:`.time` object *t* is aware
135if ``t.tzinfo`` is not ``None`` and ``t.tzinfo.utcoffset(None)`` does not return
136``None``. Otherwise, *t* is naive.
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138The distinction between naive and aware doesn't apply to :class:`timedelta`
139objects.
140
141Subclass relationships::
142
143 object
144 timedelta
145 tzinfo
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000146 timezone
Georg Brandl116aa622007-08-15 14:28:22 +0000147 time
148 date
149 datetime
150
151
152.. _datetime-timedelta:
153
154:class:`timedelta` Objects
155--------------------------
156
157A :class:`timedelta` object represents a duration, the difference between two
158dates or times.
159
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000160.. class:: timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000161
Georg Brandl5c106642007-11-29 17:41:05 +0000162 All arguments are optional and default to ``0``. Arguments may be integers
Georg Brandl116aa622007-08-15 14:28:22 +0000163 or floats, and may be positive or negative.
164
165 Only *days*, *seconds* and *microseconds* are stored internally. Arguments are
166 converted to those units:
167
168 * A millisecond is converted to 1000 microseconds.
169 * A minute is converted to 60 seconds.
170 * An hour is converted to 3600 seconds.
171 * A week is converted to 7 days.
172
173 and days, seconds and microseconds are then normalized so that the
174 representation is unique, with
175
176 * ``0 <= microseconds < 1000000``
177 * ``0 <= seconds < 3600*24`` (the number of seconds in one day)
178 * ``-999999999 <= days <= 999999999``
179
Alexander Belopolsky790d2692013-08-04 14:51:35 -0400180 If any argument is a float and there are fractional microseconds,
181 the fractional microseconds left over from all arguments are
182 combined and their sum is rounded to the nearest microsecond using
183 round-half-to-even tiebreaker. If no argument is a float, the
184 conversion and normalization processes are exact (no information is
185 lost).
Georg Brandl116aa622007-08-15 14:28:22 +0000186
187 If the normalized value of days lies outside the indicated range,
188 :exc:`OverflowError` is raised.
189
190 Note that normalization of negative values may be surprising at first. For
Christian Heimesfe337bf2008-03-23 21:54:12 +0000191 example,
Georg Brandl116aa622007-08-15 14:28:22 +0000192
Christian Heimes895627f2007-12-08 17:28:33 +0000193 >>> from datetime import timedelta
Georg Brandl116aa622007-08-15 14:28:22 +0000194 >>> d = timedelta(microseconds=-1)
195 >>> (d.days, d.seconds, d.microseconds)
196 (-1, 86399, 999999)
197
Georg Brandl116aa622007-08-15 14:28:22 +0000198
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000199Class attributes are:
Georg Brandl116aa622007-08-15 14:28:22 +0000200
201.. attribute:: timedelta.min
202
203 The most negative :class:`timedelta` object, ``timedelta(-999999999)``.
204
205
206.. attribute:: timedelta.max
207
208 The most positive :class:`timedelta` object, ``timedelta(days=999999999,
209 hours=23, minutes=59, seconds=59, microseconds=999999)``.
210
211
212.. attribute:: timedelta.resolution
213
214 The smallest possible difference between non-equal :class:`timedelta` objects,
215 ``timedelta(microseconds=1)``.
216
217Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``.
218``-timedelta.max`` is not representable as a :class:`timedelta` object.
219
220Instance attributes (read-only):
221
222+------------------+--------------------------------------------+
223| Attribute | Value |
224+==================+============================================+
225| ``days`` | Between -999999999 and 999999999 inclusive |
226+------------------+--------------------------------------------+
227| ``seconds`` | Between 0 and 86399 inclusive |
228+------------------+--------------------------------------------+
229| ``microseconds`` | Between 0 and 999999 inclusive |
230+------------------+--------------------------------------------+
231
232Supported operations:
233
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000234.. XXX this table is too wide!
Georg Brandl116aa622007-08-15 14:28:22 +0000235
236+--------------------------------+-----------------------------------------------+
237| Operation | Result |
238+================================+===============================================+
239| ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == |
240| | *t3* and *t1*-*t3* == *t2* are true. (1) |
241+--------------------------------+-----------------------------------------------+
242| ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* |
243| | == *t2* - *t3* and *t2* == *t1* + *t3* are |
Farhaan Bukhsh5b6e49a2018-07-05 00:12:05 +0530244| | true. (1)(6) |
Georg Brandl116aa622007-08-15 14:28:22 +0000245+--------------------------------+-----------------------------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000246| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer. |
Georg Brandl116aa622007-08-15 14:28:22 +0000247| | Afterwards *t1* // i == *t2* is true, |
248| | provided ``i != 0``. |
249+--------------------------------+-----------------------------------------------+
250| | In general, *t1* \* i == *t1* \* (i-1) + *t1* |
251| | is true. (1) |
252+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000253| ``t1 = t2 * f or t1 = f * t2`` | Delta multiplied by a float. The result is |
254| | rounded to the nearest multiple of |
255| | timedelta.resolution using round-half-to-even.|
256+--------------------------------+-----------------------------------------------+
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
Farhaan Bukhsh5b6e49a2018-07-05 00:12:05 +0530320(6)
321 The expression ``t2 - t3`` will always be equal to the expression ``t2 + (-t3)`` except
322 when t3 is equal to ``timedelta.max``; in that case the former will produce a result
323 while the latter will overflow.
324
Georg Brandl116aa622007-08-15 14:28:22 +0000325In addition to the operations listed above :class:`timedelta` objects support
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300326certain additions and subtractions with :class:`date` and :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +0000327objects (see below).
328
Georg Brandl67b21b72010-08-17 15:07:14 +0000329.. versionchanged:: 3.2
330 Floor division and true division of a :class:`timedelta` object by another
331 :class:`timedelta` object are now supported, as are remainder operations and
332 the :func:`divmod` function. True division and multiplication of a
333 :class:`timedelta` object by a :class:`float` object are now supported.
Mark Dickinson7c186e22010-04-20 22:32:49 +0000334
335
Georg Brandl116aa622007-08-15 14:28:22 +0000336Comparisons of :class:`timedelta` objects are supported with the
337:class:`timedelta` object representing the smaller duration considered to be the
338smaller timedelta. In order to stop mixed-type comparisons from falling back to
339the default comparison by object address, when a :class:`timedelta` object is
340compared to an object of a different type, :exc:`TypeError` is raised unless the
341comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
342:const:`True`, respectively.
343
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000344:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl116aa622007-08-15 14:28:22 +0000345efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
346considered to be true if and only if it isn't equal to ``timedelta(0)``.
347
Antoine Pitroube6859d2009-11-25 23:02:32 +0000348Instance methods:
349
350.. method:: timedelta.total_seconds()
351
352 Return the total number of seconds contained in the duration. Equivalent to
Mark Dickinson0381e3f2010-05-08 14:35:02 +0000353 ``td / timedelta(seconds=1)``.
354
355 Note that for very large time intervals (greater than 270 years on
356 most platforms) this method will lose microsecond accuracy.
Antoine Pitroube6859d2009-11-25 23:02:32 +0000357
358 .. versionadded:: 3.2
359
360
Christian Heimesfe337bf2008-03-23 21:54:12 +0000361Example usage:
Georg Brandl48310cd2009-01-03 21:18:54 +0000362
Christian Heimes895627f2007-12-08 17:28:33 +0000363 >>> from datetime import timedelta
364 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000365 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Christian Heimes895627f2007-12-08 17:28:33 +0000366 ... minutes=50, seconds=600) # adds up to 365 days
Antoine Pitroube6859d2009-11-25 23:02:32 +0000367 >>> year.total_seconds()
368 31536000.0
Christian Heimes895627f2007-12-08 17:28:33 +0000369 >>> year == another_year
370 True
371 >>> ten_years = 10 * year
372 >>> ten_years, ten_years.days // 365
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +0200373 (datetime.timedelta(days=3650), 10)
Christian Heimes895627f2007-12-08 17:28:33 +0000374 >>> nine_years = ten_years - year
375 >>> nine_years, nine_years.days // 365
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +0200376 (datetime.timedelta(days=3285), 9)
delirious-lettucec7b3f0f2017-05-18 19:01:00 -0600377 >>> three_years = nine_years // 3
Christian Heimes895627f2007-12-08 17:28:33 +0000378 >>> three_years, three_years.days // 365
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +0200379 (datetime.timedelta(days=1095), 3)
Christian Heimes895627f2007-12-08 17:28:33 +0000380 >>> abs(three_years - ten_years) == 2 * three_years + year
381 True
382
Georg Brandl116aa622007-08-15 14:28:22 +0000383
384.. _datetime-date:
385
386:class:`date` Objects
387---------------------
388
389A :class:`date` object represents a date (year, month and day) in an idealized
390calendar, the current Gregorian calendar indefinitely extended in both
391directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
392called day number 2, and so on. This matches the definition of the "proleptic
393Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
394where it's the base calendar for all computations. See the book for algorithms
395for converting between proleptic Gregorian ordinals and many other calendar
396systems.
397
398
399.. class:: date(year, month, day)
400
Georg Brandl5c106642007-11-29 17:41:05 +0000401 All arguments are required. Arguments may be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000402 ranges:
403
404 * ``MINYEAR <= year <= MAXYEAR``
405 * ``1 <= month <= 12``
406 * ``1 <= day <= number of days in the given month and year``
407
408 If an argument outside those ranges is given, :exc:`ValueError` is raised.
409
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000410
Georg Brandl116aa622007-08-15 14:28:22 +0000411Other constructors, all class methods:
412
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000413.. classmethod:: date.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000414
415 Return the current local date. This is equivalent to
416 ``date.fromtimestamp(time.time())``.
417
418
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000419.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000420
421 Return the local date corresponding to the POSIX timestamp, such as is returned
Victor Stinner5d272cc2012-03-13 13:35:55 +0100422 by :func:`time.time`. This may raise :exc:`OverflowError`, if the timestamp is out
Victor Stinnerecc6e662012-03-14 00:39:29 +0100423 of the range of values supported by the platform C :c:func:`localtime` function,
424 and :exc:`OSError` on :c:func:`localtime` failure.
Georg Brandl116aa622007-08-15 14:28:22 +0000425 It's common for this to be restricted to years from 1970 through 2038. Note
426 that on non-POSIX systems that include leap seconds in their notion of a
427 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
428
Victor Stinner5d272cc2012-03-13 13:35:55 +0100429 .. versionchanged:: 3.3
430 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
431 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100432 :c:func:`localtime` function. Raise :exc:`OSError` instead of
433 :exc:`ValueError` on :c:func:`localtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100434
Georg Brandl116aa622007-08-15 14:28:22 +0000435
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000436.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000437
438 Return the date corresponding to the proleptic Gregorian ordinal, where January
439 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
440 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
441 d``.
442
Georg Brandl116aa622007-08-15 14:28:22 +0000443
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500444.. classmethod:: date.fromisoformat(date_string)
445
446 Return a :class:`date` corresponding to a *date_string* in the format emitted
447 by :meth:`date.isoformat`. Specifically, this function supports strings in
448 the format(s) ``YYYY-MM-DD``.
449
450 .. caution::
451
452 This does not support parsing arbitrary ISO 8601 strings - it is only intended
453 as the inverse operation of :meth:`date.isoformat`.
454
455 .. versionadded:: 3.7
456
457
458
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000459Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000460
461.. attribute:: date.min
462
463 The earliest representable date, ``date(MINYEAR, 1, 1)``.
464
465
466.. attribute:: date.max
467
468 The latest representable date, ``date(MAXYEAR, 12, 31)``.
469
470
471.. attribute:: date.resolution
472
473 The smallest possible difference between non-equal date objects,
474 ``timedelta(days=1)``.
475
Georg Brandl116aa622007-08-15 14:28:22 +0000476
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000477Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000478
479.. attribute:: date.year
480
481 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
482
483
484.. attribute:: date.month
485
486 Between 1 and 12 inclusive.
487
488
489.. attribute:: date.day
490
491 Between 1 and the number of days in the given month of the given year.
492
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000493
Georg Brandl116aa622007-08-15 14:28:22 +0000494Supported operations:
495
496+-------------------------------+----------------------------------------------+
497| Operation | Result |
498+===============================+==============================================+
499| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
500| | from *date1*. (1) |
501+-------------------------------+----------------------------------------------+
502| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
503| | timedelta == date1``. (2) |
504+-------------------------------+----------------------------------------------+
505| ``timedelta = date1 - date2`` | \(3) |
506+-------------------------------+----------------------------------------------+
507| ``date1 < date2`` | *date1* is considered less than *date2* when |
508| | *date1* precedes *date2* in time. (4) |
509+-------------------------------+----------------------------------------------+
510
511Notes:
512
513(1)
514 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
515 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
516 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
517 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
518 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
519
520(2)
Georg Brandl116aa622007-08-15 14:28:22 +0000521 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
522
523(3)
524 This is exact, and cannot overflow. timedelta.seconds and
525 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
526
527(4)
528 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
Danish Prakash9c223792018-09-12 02:29:23 +0530529 date2.toordinal()``. Date comparison raises :exc:`TypeError` if
530 the other comparand isn't also a :class:`date` object. However,
531 ``NotImplemented`` is returned instead if the other comparand has a
Georg Brandl116aa622007-08-15 14:28:22 +0000532 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
533 chance at implementing mixed-type comparison. If not, when a :class:`date`
534 object is compared to an object of a different type, :exc:`TypeError` is raised
535 unless the comparison is ``==`` or ``!=``. The latter cases return
536 :const:`False` or :const:`True`, respectively.
537
538Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
539objects are considered to be true.
540
541Instance methods:
542
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400543.. method:: date.replace(year=self.year, month=self.month, day=self.day)
Georg Brandl116aa622007-08-15 14:28:22 +0000544
Senthil Kumarana6bac952011-07-04 11:28:30 -0700545 Return a date with the same value, except for those parameters given new
546 values by whichever keyword arguments are specified. For example, if ``d ==
547 date(2002, 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000548
549
550.. method:: date.timetuple()
551
552 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
553 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
554 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000555 d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1,
556 1).toordinal() + 1`` is the day number within the current year starting with
557 ``1`` for January 1st.
Georg Brandl116aa622007-08-15 14:28:22 +0000558
559
560.. method:: date.toordinal()
561
562 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
563 has ordinal 1. For any :class:`date` object *d*,
564 ``date.fromordinal(d.toordinal()) == d``.
565
566
567.. method:: date.weekday()
568
569 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
570 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
571 :meth:`isoweekday`.
572
573
574.. method:: date.isoweekday()
575
576 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
577 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
578 :meth:`weekday`, :meth:`isocalendar`.
579
580
581.. method:: date.isocalendar()
582
583 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
584
585 The ISO calendar is a widely used variant of the Gregorian calendar. See
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300586 https://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm for a good
Mark Dickinsonf964ac22009-11-03 16:29:10 +0000587 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000588
589 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
590 Monday and ends on a Sunday. The first week of an ISO year is the first
591 (Gregorian) calendar week of a year containing a Thursday. This is called week
592 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
593
594 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
595 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
596 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
597 4).isocalendar() == (2004, 1, 7)``.
598
599
600.. method:: date.isoformat()
601
602 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
603 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
604
605
606.. method:: date.__str__()
607
608 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
609
610
611.. method:: date.ctime()
612
613 Return a string representing the date, for example ``date(2002, 12,
614 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
615 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
Georg Brandl60203b42010-10-06 10:11:56 +0000616 :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +0000617 :meth:`date.ctime` does not invoke) conforms to the C standard.
618
619
620.. method:: date.strftime(format)
621
622 Return a string representing the date, controlled by an explicit format string.
David Wolever569a5fa2013-08-12 16:56:02 -0400623 Format codes referring to hours, minutes or seconds will see 0 values. For a
624 complete list of formatting directives, see
625 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000626
Georg Brandl116aa622007-08-15 14:28:22 +0000627
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300628.. method:: date.__format__(format)
629
Martin Panterd5db1472016-02-08 01:34:09 +0000630 Same as :meth:`.date.strftime`. This makes it possible to specify a format
Martin Panterbc1ee462016-02-13 00:41:37 +0000631 string for a :class:`.date` object in :ref:`formatted string
632 literals <f-strings>` and when using :meth:`str.format`. For a
David Wolever569a5fa2013-08-12 16:56:02 -0400633 complete list of formatting directives, see
634 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300635
636
Christian Heimes895627f2007-12-08 17:28:33 +0000637Example of counting days to an event::
638
639 >>> import time
640 >>> from datetime import date
641 >>> today = date.today()
642 >>> today
643 datetime.date(2007, 12, 5)
644 >>> today == date.fromtimestamp(time.time())
645 True
646 >>> my_birthday = date(today.year, 6, 24)
647 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000648 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000649 >>> my_birthday
650 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000651 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000652 >>> time_to_birthday.days
653 202
654
Christian Heimesfe337bf2008-03-23 21:54:12 +0000655Example of working with :class:`date`:
656
657.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000658
659 >>> from datetime import date
660 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
661 >>> d
662 datetime.date(2002, 3, 11)
663 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000664 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000665 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000666 2002 # year
667 3 # month
668 11 # day
669 0
670 0
671 0
672 0 # weekday (0 = Monday)
673 70 # 70th day in the year
674 -1
675 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000676 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000677 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000678 2002 # ISO year
679 11 # ISO week number
680 1 # ISO day number ( 1 = Monday )
681 >>> d.isoformat()
682 '2002-03-11'
683 >>> d.strftime("%d/%m/%y")
684 '11/03/02'
685 >>> d.strftime("%A %d. %B %Y")
686 'Monday 11. March 2002'
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300687 >>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")
688 'The day is 11, the month is March.'
Christian Heimes895627f2007-12-08 17:28:33 +0000689
Georg Brandl116aa622007-08-15 14:28:22 +0000690
691.. _datetime-datetime:
692
Benjamin Petersond87dd432015-04-25 14:15:16 -0400693:class:`.datetime` Objects
694--------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000695
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300696A :class:`.datetime` object is a single object containing all the information
697from a :class:`date` object and a :class:`.time` object. Like a :class:`date`
698object, :class:`.datetime` assumes the current Gregorian calendar extended in
699both directions; like a time object, :class:`.datetime` assumes there are exactly
Georg Brandl116aa622007-08-15 14:28:22 +00007003600\*24 seconds in every day.
701
702Constructor:
703
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400704.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000705
706 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000707 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
708 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000709
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400710 * ``MINYEAR <= year <= MAXYEAR``,
711 * ``1 <= month <= 12``,
712 * ``1 <= day <= number of days in the given month and year``,
713 * ``0 <= hour < 24``,
714 * ``0 <= minute < 60``,
715 * ``0 <= second < 60``,
716 * ``0 <= microsecond < 1000000``,
717 * ``fold in [0, 1]``.
Georg Brandl116aa622007-08-15 14:28:22 +0000718
719 If an argument outside those ranges is given, :exc:`ValueError` is raised.
720
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400721 .. versionadded:: 3.6
722 Added the ``fold`` argument.
723
Georg Brandl116aa622007-08-15 14:28:22 +0000724Other constructors, all class methods:
725
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000726.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000727
Martin Panter16c7cfd2016-04-01 21:48:24 +0000728 Return the current local datetime, with :attr:`.tzinfo` ``None``. This is
Georg Brandl116aa622007-08-15 14:28:22 +0000729 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
730 :meth:`fromtimestamp`.
731
732
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000733.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000734
735 Return the current local date and time. If optional argument *tz* is ``None``
736 or not specified, this is like :meth:`today`, but, if possible, supplies more
737 precision than can be gotten from going through a :func:`time.time` timestamp
738 (for example, this may be possible on platforms supplying the C
Georg Brandl60203b42010-10-06 10:11:56 +0000739 :c:func:`gettimeofday` function).
Georg Brandl116aa622007-08-15 14:28:22 +0000740
Martin Panter16c7cfd2016-04-01 21:48:24 +0000741 If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` subclass, and the
742 current date and time are converted to *tz*’s time zone. In this case the
Georg Brandl116aa622007-08-15 14:28:22 +0000743 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
744 See also :meth:`today`, :meth:`utcnow`.
745
746
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000747.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000748
Martin Panter16c7cfd2016-04-01 21:48:24 +0000749 Return the current UTC date and time, with :attr:`.tzinfo` ``None``. This is like
Georg Brandl116aa622007-08-15 14:28:22 +0000750 :meth:`now`, but returns the current UTC date and time, as a naive
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300751 :class:`.datetime` object. An aware current UTC datetime can be obtained by
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000752 calling ``datetime.now(timezone.utc)``. See also :meth:`now`.
Georg Brandl116aa622007-08-15 14:28:22 +0000753
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000754.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000755
756 Return the local date and time corresponding to the POSIX timestamp, such as is
757 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
758 specified, the timestamp is converted to the platform's local date and time, and
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300759 the returned :class:`.datetime` object is naive.
Georg Brandl116aa622007-08-15 14:28:22 +0000760
Martin Panter16c7cfd2016-04-01 21:48:24 +0000761 If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` subclass, and the
762 timestamp is converted to *tz*’s time zone. In this case the result is
Georg Brandl116aa622007-08-15 14:28:22 +0000763 equivalent to
764 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
765
Victor Stinnerecc6e662012-03-14 00:39:29 +0100766 :meth:`fromtimestamp` may raise :exc:`OverflowError`, if the timestamp is out of
Georg Brandl60203b42010-10-06 10:11:56 +0000767 the range of values supported by the platform C :c:func:`localtime` or
Victor Stinnerecc6e662012-03-14 00:39:29 +0100768 :c:func:`gmtime` functions, and :exc:`OSError` on :c:func:`localtime` or
769 :c:func:`gmtime` failure.
770 It's common for this to be restricted to years in
Georg Brandl116aa622007-08-15 14:28:22 +0000771 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
772 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
773 and then it's possible to have two timestamps differing by a second that yield
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300774 identical :class:`.datetime` objects. See also :meth:`utcfromtimestamp`.
Georg Brandl116aa622007-08-15 14:28:22 +0000775
Victor Stinner5d272cc2012-03-13 13:35:55 +0100776 .. versionchanged:: 3.3
777 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
778 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100779 :c:func:`localtime` or :c:func:`gmtime` functions. Raise :exc:`OSError`
780 instead of :exc:`ValueError` on :c:func:`localtime` or :c:func:`gmtime`
781 failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100782
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400783 .. versionchanged:: 3.6
784 :meth:`fromtimestamp` may return instances with :attr:`.fold` set to 1.
Georg Brandl116aa622007-08-15 14:28:22 +0000785
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000786.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000787
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300788 Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with
Martin Panter16c7cfd2016-04-01 21:48:24 +0000789 :attr:`.tzinfo` ``None``. This may raise :exc:`OverflowError`, if the timestamp is
Victor Stinnerecc6e662012-03-14 00:39:29 +0100790 out of the range of values supported by the platform C :c:func:`gmtime` function,
791 and :exc:`OSError` on :c:func:`gmtime` failure.
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500792 It's common for this to be restricted to years in 1970 through 2038.
Georg Brandl116aa622007-08-15 14:28:22 +0000793
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500794 To get an aware :class:`.datetime` object, call :meth:`fromtimestamp`::
Alexander Belopolsky54afa552011-04-25 13:00:40 -0400795
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500796 datetime.fromtimestamp(timestamp, timezone.utc)
797
798 On the POSIX compliant platforms, it is equivalent to the following
799 expression::
800
801 datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)
802
803 except the latter formula always supports the full years range: between
804 :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
Alexander Belopolsky54afa552011-04-25 13:00:40 -0400805
Victor Stinner5d272cc2012-03-13 13:35:55 +0100806 .. versionchanged:: 3.3
807 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
808 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100809 :c:func:`gmtime` function. Raise :exc:`OSError` instead of
810 :exc:`ValueError` on :c:func:`gmtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100811
Georg Brandl116aa622007-08-15 14:28:22 +0000812
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000813.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000814
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300815 Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal,
Georg Brandl116aa622007-08-15 14:28:22 +0000816 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
817 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
Martin Panter16c7cfd2016-04-01 21:48:24 +0000818 microsecond of the result are all 0, and :attr:`.tzinfo` is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000819
820
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400821.. classmethod:: datetime.combine(date, time, tzinfo=self.tzinfo)
Georg Brandl116aa622007-08-15 14:28:22 +0000822
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300823 Return a new :class:`.datetime` object whose date components are equal to the
Alexander Belopolsky43746c32016-08-02 17:49:30 -0400824 given :class:`date` object's, and whose time components
825 are equal to the given :class:`.time` object's. If the *tzinfo*
826 argument is provided, its value is used to set the :attr:`.tzinfo` attribute
827 of the result, otherwise the :attr:`~.time.tzinfo` attribute of the *time* argument
828 is used.
829
830 For any :class:`.datetime` object *d*,
831 ``d == datetime.combine(d.date(), d.time(), d.tzinfo)``. If date is a
Martin Panter16c7cfd2016-04-01 21:48:24 +0000832 :class:`.datetime` object, its time components and :attr:`.tzinfo` attributes
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800833 are ignored.
Georg Brandl116aa622007-08-15 14:28:22 +0000834
Alexander Belopolsky43746c32016-08-02 17:49:30 -0400835 .. versionchanged:: 3.6
836 Added the *tzinfo* argument.
837
Georg Brandl116aa622007-08-15 14:28:22 +0000838
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500839.. classmethod:: datetime.fromisoformat(date_string)
840
841 Return a :class:`datetime` corresponding to a *date_string* in one of the
842 formats emitted by :meth:`date.isoformat` and :meth:`datetime.isoformat`.
843 Specifically, this function supports strings in the format(s)
Christophe Nanteuil92878822018-10-06 00:57:02 +0200844 ``YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]]``,
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500845 where ``*`` can match any single character.
846
847 .. caution::
848
849 This does not support parsing arbitrary ISO 8601 strings - it is only intended
850 as the inverse operation of :meth:`datetime.isoformat`.
851
852 .. versionadded:: 3.7
853
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000854.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000855
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300856 Return a :class:`.datetime` corresponding to *date_string*, parsed according to
Georg Brandl116aa622007-08-15 14:28:22 +0000857 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
858 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
859 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 -0400860 time tuple. For a complete list of formatting directives, see
861 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000862
Georg Brandl116aa622007-08-15 14:28:22 +0000863
Georg Brandl116aa622007-08-15 14:28:22 +0000864
865Class attributes:
866
Georg Brandl116aa622007-08-15 14:28:22 +0000867.. attribute:: datetime.min
868
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300869 The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1,
Georg Brandl116aa622007-08-15 14:28:22 +0000870 tzinfo=None)``.
871
872
873.. attribute:: datetime.max
874
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300875 The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
Georg Brandl116aa622007-08-15 14:28:22 +0000876 59, 999999, tzinfo=None)``.
877
878
879.. attribute:: datetime.resolution
880
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300881 The smallest possible difference between non-equal :class:`.datetime` objects,
Georg Brandl116aa622007-08-15 14:28:22 +0000882 ``timedelta(microseconds=1)``.
883
Georg Brandl116aa622007-08-15 14:28:22 +0000884
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000885Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000886
887.. attribute:: datetime.year
888
889 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
890
891
892.. attribute:: datetime.month
893
894 Between 1 and 12 inclusive.
895
896
897.. attribute:: datetime.day
898
899 Between 1 and the number of days in the given month of the given year.
900
901
902.. attribute:: datetime.hour
903
904 In ``range(24)``.
905
906
907.. attribute:: datetime.minute
908
909 In ``range(60)``.
910
911
912.. attribute:: datetime.second
913
914 In ``range(60)``.
915
916
917.. attribute:: datetime.microsecond
918
919 In ``range(1000000)``.
920
921
922.. attribute:: datetime.tzinfo
923
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300924 The object passed as the *tzinfo* argument to the :class:`.datetime` constructor,
Georg Brandl116aa622007-08-15 14:28:22 +0000925 or ``None`` if none was passed.
926
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000927
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400928.. attribute:: datetime.fold
929
930 In ``[0, 1]``. Used to disambiguate wall times during a repeated interval. (A
931 repeated interval occurs when clocks are rolled back at the end of daylight saving
932 time or when the UTC offset for the current zone is decreased for political reasons.)
933 The value 0 (1) represents the earlier (later) of the two moments with the same wall
934 time representation.
935
936 .. versionadded:: 3.6
937
Georg Brandl116aa622007-08-15 14:28:22 +0000938Supported operations:
939
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300940+---------------------------------------+--------------------------------+
941| Operation | Result |
942+=======================================+================================+
943| ``datetime2 = datetime1 + timedelta`` | \(1) |
944+---------------------------------------+--------------------------------+
945| ``datetime2 = datetime1 - timedelta`` | \(2) |
946+---------------------------------------+--------------------------------+
947| ``timedelta = datetime1 - datetime2`` | \(3) |
948+---------------------------------------+--------------------------------+
949| ``datetime1 < datetime2`` | Compares :class:`.datetime` to |
950| | :class:`.datetime`. (4) |
951+---------------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000952
953(1)
954 datetime2 is a duration of timedelta removed from datetime1, moving forward in
955 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
Martin Panter16c7cfd2016-04-01 21:48:24 +0000956 result has the same :attr:`~.datetime.tzinfo` attribute as the input datetime, and
Senthil Kumarana6bac952011-07-04 11:28:30 -0700957 datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
958 datetime2.year would be smaller than :const:`MINYEAR` or larger than
959 :const:`MAXYEAR`. Note that no time zone adjustments are done even if the
960 input is an aware object.
Georg Brandl116aa622007-08-15 14:28:22 +0000961
962(2)
963 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
Martin Panter16c7cfd2016-04-01 21:48:24 +0000964 addition, the result has the same :attr:`~.datetime.tzinfo` attribute as the input
Senthil Kumarana6bac952011-07-04 11:28:30 -0700965 datetime, and no time zone adjustments are done even if the input is aware.
Georg Brandl116aa622007-08-15 14:28:22 +0000966
967(3)
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300968 Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if
Georg Brandl116aa622007-08-15 14:28:22 +0000969 both operands are naive, or if both are aware. If one is aware and the other is
970 naive, :exc:`TypeError` is raised.
971
Martin Panter16c7cfd2016-04-01 21:48:24 +0000972 If both are naive, or both are aware and have the same :attr:`~.datetime.tzinfo` attribute,
973 the :attr:`~.datetime.tzinfo` attributes are ignored, and the result is a :class:`timedelta`
Georg Brandl116aa622007-08-15 14:28:22 +0000974 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
975 are done in this case.
976
Martin Panter16c7cfd2016-04-01 21:48:24 +0000977 If both are aware and have different :attr:`~.datetime.tzinfo` attributes, ``a-b`` acts
Senthil Kumarana6bac952011-07-04 11:28:30 -0700978 as if *a* and *b* were first converted to naive UTC datetimes first. The
979 result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
980 - b.utcoffset())`` except that the implementation never overflows.
Georg Brandl116aa622007-08-15 14:28:22 +0000981
982(4)
983 *datetime1* is considered less than *datetime2* when *datetime1* precedes
984 *datetime2* in time.
985
Alexander Belopolsky08313822012-06-15 20:19:47 -0400986 If one comparand is naive and the other is aware, :exc:`TypeError`
987 is raised if an order comparison is attempted. For equality
988 comparisons, naive instances are never equal to aware instances.
989
Martin Panter16c7cfd2016-04-01 21:48:24 +0000990 If both comparands are aware, and have the same :attr:`~.datetime.tzinfo` attribute, the
991 common :attr:`~.datetime.tzinfo` attribute is ignored and the base datetimes are
992 compared. If both comparands are aware and have different :attr:`~.datetime.tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -0700993 attributes, the comparands are first adjusted by subtracting their UTC
994 offsets (obtained from ``self.utcoffset()``).
Georg Brandl116aa622007-08-15 14:28:22 +0000995
Alexander Belopolsky08313822012-06-15 20:19:47 -0400996 .. versionchanged:: 3.3
Martin Panter16c7cfd2016-04-01 21:48:24 +0000997 Equality comparisons between naive and aware :class:`.datetime`
Éric Araujob0f08952012-06-24 16:22:09 -0400998 instances don't raise :exc:`TypeError`.
Alexander Belopolsky08313822012-06-15 20:19:47 -0400999
Georg Brandl116aa622007-08-15 14:28:22 +00001000 .. note::
1001
1002 In order to stop comparison from falling back to the default scheme of comparing
1003 object addresses, datetime comparison normally raises :exc:`TypeError` if the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001004 other comparand isn't also a :class:`.datetime` object. However,
Georg Brandl116aa622007-08-15 14:28:22 +00001005 ``NotImplemented`` is returned instead if the other comparand has a
1006 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001007 chance at implementing mixed-type comparison. If not, when a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +00001008 object is compared to an object of a different type, :exc:`TypeError` is raised
1009 unless the comparison is ``==`` or ``!=``. The latter cases return
1010 :const:`False` or :const:`True`, respectively.
1011
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001012:class:`.datetime` objects can be used as dictionary keys. In Boolean contexts,
1013all :class:`.datetime` objects are considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +00001014
1015Instance methods:
1016
Georg Brandl116aa622007-08-15 14:28:22 +00001017.. method:: datetime.date()
1018
1019 Return :class:`date` object with same year, month and day.
1020
1021
1022.. method:: datetime.time()
1023
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001024 Return :class:`.time` object with same hour, minute, second, microsecond and fold.
Martin Panter16c7cfd2016-04-01 21:48:24 +00001025 :attr:`.tzinfo` is ``None``. See also method :meth:`timetz`.
Georg Brandl116aa622007-08-15 14:28:22 +00001026
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001027 .. versionchanged:: 3.6
1028 The fold value is copied to the returned :class:`.time` object.
1029
Georg Brandl116aa622007-08-15 14:28:22 +00001030
1031.. method:: datetime.timetz()
1032
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001033 Return :class:`.time` object with same hour, minute, second, microsecond, fold, and
Senthil Kumarana6bac952011-07-04 11:28:30 -07001034 tzinfo attributes. See also method :meth:`time`.
Georg Brandl116aa622007-08-15 14:28:22 +00001035
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001036 .. versionchanged:: 3.6
1037 The fold value is copied to the returned :class:`.time` object.
Georg Brandl116aa622007-08-15 14:28:22 +00001038
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001039
1040.. method:: datetime.replace(year=self.year, month=self.month, day=self.day, \
1041 hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, \
1042 tzinfo=self.tzinfo, * fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001043
Senthil Kumarana6bac952011-07-04 11:28:30 -07001044 Return a datetime with the same attributes, except for those attributes given
1045 new values by whichever keyword arguments are specified. Note that
1046 ``tzinfo=None`` can be specified to create a naive datetime from an aware
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001047 datetime with no conversion of date and time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001048
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001049 .. versionadded:: 3.6
1050 Added the ``fold`` argument.
1051
Georg Brandl116aa622007-08-15 14:28:22 +00001052
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001053.. method:: datetime.astimezone(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001054
Martin Panter16c7cfd2016-04-01 21:48:24 +00001055 Return a :class:`.datetime` object with new :attr:`.tzinfo` attribute *tz*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001056 adjusting the date and time data so the result is the same UTC time as
Senthil Kumarana6bac952011-07-04 11:28:30 -07001057 *self*, but in *tz*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00001058
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001059 If provided, *tz* must be an instance of a :class:`tzinfo` subclass, and its
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001060 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. If *self*
Alexander Belopolsky877b2322018-06-10 17:02:58 -04001061 is naive, it is presumed to represent time in the system timezone.
Georg Brandl116aa622007-08-15 14:28:22 +00001062
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001063 If called without arguments (or with ``tz=None``) the system local
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001064 timezone is assumed for the target timezone. The ``.tzinfo`` attribute of the converted
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001065 datetime instance will be set to an instance of :class:`timezone`
1066 with the zone name and offset obtained from the OS.
1067
Georg Brandl116aa622007-08-15 14:28:22 +00001068 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001069 adjustment of date or time data is performed. Else the result is local
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001070 time in the timezone *tz*, representing the same UTC time as *self*: after
1071 ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will have
1072 the same date and time data as ``dt - dt.utcoffset()``.
Georg Brandl116aa622007-08-15 14:28:22 +00001073
1074 If you merely want to attach a time zone object *tz* to a datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001075 adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you
Georg Brandl116aa622007-08-15 14:28:22 +00001076 merely want to remove the time zone object from an aware datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001077 conversion of date and time data, use ``dt.replace(tzinfo=None)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001078
1079 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
1080 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
1081 Ignoring error cases, :meth:`astimezone` acts like::
1082
1083 def astimezone(self, tz):
1084 if self.tzinfo is tz:
1085 return self
1086 # Convert self to UTC, and attach the new time zone object.
1087 utc = (self - self.utcoffset()).replace(tzinfo=tz)
1088 # Convert from UTC to tz's local time.
1089 return tz.fromutc(utc)
1090
Georg Brandlee0be402012-06-26 09:14:40 +02001091 .. versionchanged:: 3.3
1092 *tz* now can be omitted.
1093
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001094 .. versionchanged:: 3.6
1095 The :meth:`astimezone` method can now be called on naive instances that
1096 are presumed to represent system local time.
1097
Georg Brandl116aa622007-08-15 14:28:22 +00001098
1099.. method:: datetime.utcoffset()
1100
Martin Panter16c7cfd2016-04-01 21:48:24 +00001101 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001102 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001103 return ``None`` or a :class:`timedelta` object with magnitude less than one day.
1104
1105 .. versionchanged:: 3.7
1106 The UTC offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001107
1108
1109.. method:: datetime.dst()
1110
Martin Panter16c7cfd2016-04-01 21:48:24 +00001111 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001112 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001113 ``None`` or a :class:`timedelta` object with magnitude less than one day.
1114
1115 .. versionchanged:: 3.7
1116 The DST offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001117
1118
1119.. method:: datetime.tzname()
1120
Martin Panter16c7cfd2016-04-01 21:48:24 +00001121 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001122 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
1123 ``None`` or a string object,
1124
1125
1126.. method:: datetime.timetuple()
1127
1128 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
1129 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
Alexander Belopolsky64912482010-06-08 18:59:20 +00001130 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
1131 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
1132 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
Martin Panter16c7cfd2016-04-01 21:48:24 +00001133 of the result is set according to the :meth:`dst` method: :attr:`.tzinfo` is
Georg Brandl682d7e02010-10-06 10:26:05 +00001134 ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
Alexander Belopolsky64912482010-06-08 18:59:20 +00001135 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
Alexander Belopolskyda62f2f2010-06-09 17:11:01 +00001136 else :attr:`tm_isdst` is set to ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +00001137
1138
1139.. method:: datetime.utctimetuple()
1140
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001141 If :class:`.datetime` instance *d* is naive, this is the same as
Georg Brandl116aa622007-08-15 14:28:22 +00001142 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
1143 ``d.dst()`` returns. DST is never in effect for a UTC time.
1144
1145 If *d* is aware, *d* is normalized to UTC time, by subtracting
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00001146 ``d.utcoffset()``, and a :class:`time.struct_time` for the
1147 normalized time is returned. :attr:`tm_isdst` is forced to 0. Note
1148 that an :exc:`OverflowError` may be raised if *d*.year was
1149 ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
Georg Brandl116aa622007-08-15 14:28:22 +00001150 boundary.
1151
1152
1153.. method:: datetime.toordinal()
1154
1155 Return the proleptic Gregorian ordinal of the date. The same as
1156 ``self.date().toordinal()``.
1157
Alexander Belopolskya4415142012-06-08 12:33:09 -04001158.. method:: datetime.timestamp()
1159
Martin Panter16c7cfd2016-04-01 21:48:24 +00001160 Return POSIX timestamp corresponding to the :class:`.datetime`
Alexander Belopolskya4415142012-06-08 12:33:09 -04001161 instance. The return value is a :class:`float` similar to that
1162 returned by :func:`time.time`.
1163
Martin Panter16c7cfd2016-04-01 21:48:24 +00001164 Naive :class:`.datetime` instances are assumed to represent local
Alexander Belopolskya4415142012-06-08 12:33:09 -04001165 time and this method relies on the platform C :c:func:`mktime`
Martin Panter16c7cfd2016-04-01 21:48:24 +00001166 function to perform the conversion. Since :class:`.datetime`
Alexander Belopolskya4415142012-06-08 12:33:09 -04001167 supports wider range of values than :c:func:`mktime` on many
1168 platforms, this method may raise :exc:`OverflowError` for times far
1169 in the past or far in the future.
1170
Martin Panter16c7cfd2016-04-01 21:48:24 +00001171 For aware :class:`.datetime` instances, the return value is computed
Alexander Belopolskya4415142012-06-08 12:33:09 -04001172 as::
1173
1174 (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
1175
1176 .. versionadded:: 3.3
1177
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001178 .. versionchanged:: 3.6
1179 The :meth:`timestamp` method uses the :attr:`.fold` attribute to
1180 disambiguate the times during a repeated interval.
1181
Alexander Belopolskya4415142012-06-08 12:33:09 -04001182 .. note::
1183
1184 There is no method to obtain the POSIX timestamp directly from a
Martin Panter16c7cfd2016-04-01 21:48:24 +00001185 naive :class:`.datetime` instance representing UTC time. If your
Alexander Belopolskya4415142012-06-08 12:33:09 -04001186 application uses this convention and your system timezone is not
1187 set to UTC, you can obtain the POSIX timestamp by supplying
1188 ``tzinfo=timezone.utc``::
1189
1190 timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
1191
1192 or by calculating the timestamp directly::
1193
1194 timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001195
1196.. method:: datetime.weekday()
1197
1198 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
1199 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
1200
1201
1202.. method:: datetime.isoweekday()
1203
1204 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
1205 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
1206 :meth:`isocalendar`.
1207
1208
1209.. method:: datetime.isocalendar()
1210
1211 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
1212 ``self.date().isocalendar()``.
1213
1214
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001215.. method:: datetime.isoformat(sep='T', timespec='auto')
Georg Brandl116aa622007-08-15 14:28:22 +00001216
1217 Return a string representing the date and time in ISO 8601 format,
Christophe Nanteuil92878822018-10-06 00:57:02 +02001218 YYYY-MM-DDTHH:MM:SS.ffffff or, if :attr:`microsecond` is 0,
Georg Brandl116aa622007-08-15 14:28:22 +00001219 YYYY-MM-DDTHH:MM:SS
1220
Christophe Nanteuil92878822018-10-06 00:57:02 +02001221 If :meth:`utcoffset` does not return ``None``, a string is
1222 appended, giving the UTC offset:
1223 YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]] or, if :attr:`microsecond`
1224 is 0 YYYY-MM-DDTHH:MM:SS+HH:MM[:SS[.ffffff]].
Georg Brandl116aa622007-08-15 14:28:22 +00001225
1226 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +00001227 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +00001228
1229 >>> from datetime import tzinfo, timedelta, datetime
1230 >>> class TZ(tzinfo):
1231 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1232 ...
1233 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1234 '2002-12-25 00:00:00-06:39'
1235
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001236 The optional argument *timespec* specifies the number of additional
1237 components of the time to include (the default is ``'auto'``).
1238 It can be one of the following:
1239
1240 - ``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0,
1241 same as ``'microseconds'`` otherwise.
1242 - ``'hours'``: Include the :attr:`hour` in the two-digit HH format.
1243 - ``'minutes'``: Include :attr:`hour` and :attr:`minute` in HH:MM format.
1244 - ``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second`
1245 in HH:MM:SS format.
1246 - ``'milliseconds'``: Include full time, but truncate fractional second
1247 part to milliseconds. HH:MM:SS.sss format.
Christophe Nanteuil92878822018-10-06 00:57:02 +02001248 - ``'microseconds'``: Include full time in HH:MM:SS.ffffff format.
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001249
1250 .. note::
1251
1252 Excluded time components are truncated, not rounded.
1253
1254 :exc:`ValueError` will be raised on an invalid *timespec* argument.
1255
1256
1257 >>> from datetime import datetime
Marco Buttu909a6f62017-03-18 17:59:33 +01001258 >>> datetime.now().isoformat(timespec='minutes') # doctest: +SKIP
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001259 '2002-12-25T00:00'
1260 >>> dt = datetime(2015, 1, 1, 12, 30, 59, 0)
1261 >>> dt.isoformat(timespec='microseconds')
1262 '2015-01-01T12:30:59.000000'
1263
1264 .. versionadded:: 3.6
1265 Added the *timespec* argument.
1266
Georg Brandl116aa622007-08-15 14:28:22 +00001267
1268.. method:: datetime.__str__()
1269
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001270 For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to
Georg Brandl116aa622007-08-15 14:28:22 +00001271 ``d.isoformat(' ')``.
1272
1273
1274.. method:: datetime.ctime()
1275
1276 Return a string representing the date and time, for example ``datetime(2002, 12,
1277 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1278 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
Georg Brandl60203b42010-10-06 10:11:56 +00001279 native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +00001280 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1281
1282
1283.. method:: datetime.strftime(format)
1284
1285 Return a string representing the date and time, controlled by an explicit format
David Wolever569a5fa2013-08-12 16:56:02 -04001286 string. For a complete list of formatting directives, see
1287 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001288
Georg Brandl116aa622007-08-15 14:28:22 +00001289
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001290.. method:: datetime.__format__(format)
1291
Martin Panterd5db1472016-02-08 01:34:09 +00001292 Same as :meth:`.datetime.strftime`. This makes it possible to specify a format
Martin Panterbc1ee462016-02-13 00:41:37 +00001293 string for a :class:`.datetime` object in :ref:`formatted string
1294 literals <f-strings>` and when using :meth:`str.format`. For a
David Wolever569a5fa2013-08-12 16:56:02 -04001295 complete list of formatting directives, see
1296 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001297
1298
Christian Heimesfe337bf2008-03-23 21:54:12 +00001299Examples of working with datetime objects:
1300
1301.. doctest::
1302
Christian Heimes895627f2007-12-08 17:28:33 +00001303 >>> from datetime import datetime, date, time
1304 >>> # Using datetime.combine()
1305 >>> d = date(2005, 7, 14)
1306 >>> t = time(12, 30)
1307 >>> datetime.combine(d, t)
1308 datetime.datetime(2005, 7, 14, 12, 30)
1309 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001310 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001311 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001312 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001313 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1314 >>> # Using datetime.strptime()
1315 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1316 >>> dt
1317 datetime.datetime(2006, 11, 21, 16, 30)
1318 >>> # Using datetime.timetuple() to get tuple of all attributes
1319 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001320 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001321 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001322 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001323 2006 # year
1324 11 # month
1325 21 # day
1326 16 # hour
1327 30 # minute
1328 0 # second
1329 1 # weekday (0 = Monday)
1330 325 # number of days since 1st January
1331 -1 # dst - method tzinfo.dst() returned None
1332 >>> # Date in ISO format
1333 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001334 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001335 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001336 ...
1337 2006 # ISO year
1338 47 # ISO week
1339 2 # ISO weekday
1340 >>> # Formatting datetime
1341 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1342 'Tuesday, 21. November 2006 04:30PM'
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001343 >>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
1344 'The day is 21, the month is November, the time is 04:30PM.'
Christian Heimes895627f2007-12-08 17:28:33 +00001345
Christian Heimesfe337bf2008-03-23 21:54:12 +00001346Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001347
1348 >>> from datetime import timedelta, datetime, tzinfo
1349 >>> class GMT1(tzinfo):
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001350 ... def utcoffset(self, dt):
1351 ... return timedelta(hours=1) + self.dst(dt)
1352 ... def dst(self, dt):
1353 ... # DST starts last Sunday in March
Christian Heimes895627f2007-12-08 17:28:33 +00001354 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1355 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001356 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001357 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001358 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1359 ... return timedelta(hours=1)
1360 ... else:
1361 ... return timedelta(0)
1362 ... def tzname(self,dt):
1363 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001364 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001365 >>> class GMT2(tzinfo):
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001366 ... def utcoffset(self, dt):
1367 ... return timedelta(hours=2) + self.dst(dt)
1368 ... def dst(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001369 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001370 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001371 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001372 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001373 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001374 ... return timedelta(hours=1)
Christian Heimes895627f2007-12-08 17:28:33 +00001375 ... else:
1376 ... return timedelta(0)
1377 ... def tzname(self,dt):
1378 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001379 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001380 >>> gmt1 = GMT1()
1381 >>> # Daylight Saving Time
1382 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1383 >>> dt1.dst()
1384 datetime.timedelta(0)
1385 >>> dt1.utcoffset()
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +02001386 datetime.timedelta(seconds=3600)
Christian Heimes895627f2007-12-08 17:28:33 +00001387 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1388 >>> dt2.dst()
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +02001389 datetime.timedelta(seconds=3600)
Christian Heimes895627f2007-12-08 17:28:33 +00001390 >>> dt2.utcoffset()
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +02001391 datetime.timedelta(seconds=7200)
Christian Heimes895627f2007-12-08 17:28:33 +00001392 >>> # Convert datetime to another time zone
1393 >>> dt3 = dt2.astimezone(GMT2())
1394 >>> dt3 # doctest: +ELLIPSIS
1395 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1396 >>> dt2 # doctest: +ELLIPSIS
1397 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1398 >>> dt2.utctimetuple() == dt3.utctimetuple()
1399 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001400
Christian Heimes895627f2007-12-08 17:28:33 +00001401
Georg Brandl116aa622007-08-15 14:28:22 +00001402
1403.. _datetime-time:
1404
Serhiy Storchakaee1b01a2016-12-02 23:13:53 +02001405:class:`.time` Objects
1406----------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001407
1408A time object represents a (local) time of day, independent of any particular
1409day, and subject to adjustment via a :class:`tzinfo` object.
1410
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001411.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001412
1413 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001414 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001415 following ranges:
1416
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001417 * ``0 <= hour < 24``,
1418 * ``0 <= minute < 60``,
1419 * ``0 <= second < 60``,
1420 * ``0 <= microsecond < 1000000``,
1421 * ``fold in [0, 1]``.
Georg Brandl116aa622007-08-15 14:28:22 +00001422
1423 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1424 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1425
1426Class attributes:
1427
1428
1429.. attribute:: time.min
1430
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001431 The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001432
1433
1434.. attribute:: time.max
1435
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001436 The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001437
1438
1439.. attribute:: time.resolution
1440
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001441 The smallest possible difference between non-equal :class:`.time` objects,
1442 ``timedelta(microseconds=1)``, although note that arithmetic on
1443 :class:`.time` objects is not supported.
Georg Brandl116aa622007-08-15 14:28:22 +00001444
Georg Brandl116aa622007-08-15 14:28:22 +00001445
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001446Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001447
1448.. attribute:: time.hour
1449
1450 In ``range(24)``.
1451
1452
1453.. attribute:: time.minute
1454
1455 In ``range(60)``.
1456
1457
1458.. attribute:: time.second
1459
1460 In ``range(60)``.
1461
1462
1463.. attribute:: time.microsecond
1464
1465 In ``range(1000000)``.
1466
1467
1468.. attribute:: time.tzinfo
1469
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001470 The object passed as the tzinfo argument to the :class:`.time` constructor, or
Georg Brandl116aa622007-08-15 14:28:22 +00001471 ``None`` if none was passed.
1472
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001473
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001474.. attribute:: time.fold
1475
1476 In ``[0, 1]``. Used to disambiguate wall times during a repeated interval. (A
1477 repeated interval occurs when clocks are rolled back at the end of daylight saving
1478 time or when the UTC offset for the current zone is decreased for political reasons.)
1479 The value 0 (1) represents the earlier (later) of the two moments with the same wall
1480 time representation.
1481
1482 .. versionadded:: 3.6
1483
1484
Georg Brandl116aa622007-08-15 14:28:22 +00001485Supported operations:
1486
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001487* comparison of :class:`.time` to :class:`.time`, where *a* is considered less
Georg Brandl116aa622007-08-15 14:28:22 +00001488 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
Alexander Belopolsky08313822012-06-15 20:19:47 -04001489 is aware, :exc:`TypeError` is raised if an order comparison is attempted. For equality
1490 comparisons, naive instances are never equal to aware instances.
1491
1492 If both comparands are aware, and have
Martin Panter16c7cfd2016-04-01 21:48:24 +00001493 the same :attr:`~time.tzinfo` attribute, the common :attr:`~time.tzinfo` attribute is
Senthil Kumarana6bac952011-07-04 11:28:30 -07001494 ignored and the base times are compared. If both comparands are aware and
Martin Panter16c7cfd2016-04-01 21:48:24 +00001495 have different :attr:`~time.tzinfo` attributes, the comparands are first adjusted by
Senthil Kumarana6bac952011-07-04 11:28:30 -07001496 subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
1497 to stop mixed-type comparisons from falling back to the default comparison by
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001498 object address, when a :class:`.time` object is compared to an object of a
Senthil Kumaran3aac1792011-07-04 11:43:51 -07001499 different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
Senthil Kumarana6bac952011-07-04 11:28:30 -07001500 ``!=``. The latter cases return :const:`False` or :const:`True`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +00001501
Alexander Belopolsky08313822012-06-15 20:19:47 -04001502 .. versionchanged:: 3.3
Serhiy Storchakaee1b01a2016-12-02 23:13:53 +02001503 Equality comparisons between naive and aware :class:`~datetime.time` instances
Éric Araujob0f08952012-06-24 16:22:09 -04001504 don't raise :exc:`TypeError`.
Alexander Belopolsky08313822012-06-15 20:19:47 -04001505
Georg Brandl116aa622007-08-15 14:28:22 +00001506* hash, use as dict key
1507
1508* efficient pickling
1509
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05001510In boolean contexts, a :class:`.time` object is always considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +00001511
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05001512.. versionchanged:: 3.5
1513 Before Python 3.5, a :class:`.time` object was considered to be false if it
1514 represented midnight in UTC. This behavior was considered obscure and
1515 error-prone and has been removed in Python 3.5. See :issue:`13936` for full
1516 details.
Georg Brandl116aa622007-08-15 14:28:22 +00001517
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001518
1519Other constructor:
1520
1521.. classmethod:: time.fromisoformat(time_string)
1522
1523 Return a :class:`time` corresponding to a *time_string* in one of the
1524 formats emitted by :meth:`time.isoformat`. Specifically, this function supports
Christophe Nanteuil92878822018-10-06 00:57:02 +02001525 strings in the format(s) ``HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]``.
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001526
1527 .. caution::
1528
1529 This does not support parsing arbitrary ISO 8601 strings - it is only intended
1530 as the inverse operation of :meth:`time.isoformat`.
1531
1532 .. versionadded:: 3.7
1533
1534
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001535Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001536
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001537.. method:: time.replace(hour=self.hour, minute=self.minute, second=self.second, \
1538 microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001539
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001540 Return a :class:`.time` with the same value, except for those attributes given
Senthil Kumarana6bac952011-07-04 11:28:30 -07001541 new values by whichever keyword arguments are specified. Note that
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001542 ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
1543 aware :class:`.time`, without conversion of the time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001544
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001545 .. versionadded:: 3.6
1546 Added the ``fold`` argument.
1547
Georg Brandl116aa622007-08-15 14:28:22 +00001548
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001549.. method:: time.isoformat(timespec='auto')
Georg Brandl116aa622007-08-15 14:28:22 +00001550
Christophe Nanteuil92878822018-10-06 00:57:02 +02001551 Return a string representing the time in ISO 8601 format, HH:MM:SS.ffffff or, if
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001552 :attr:`microsecond` is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
Christophe Nanteuil92878822018-10-06 00:57:02 +02001553 string is appended, giving the UTC offset: HH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]
1554 or, if self.microsecond is 0, HH:MM:SS+HH:MM[:SS[.ffffff]].
Georg Brandl116aa622007-08-15 14:28:22 +00001555
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001556 The optional argument *timespec* specifies the number of additional
1557 components of the time to include (the default is ``'auto'``).
1558 It can be one of the following:
1559
1560 - ``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0,
1561 same as ``'microseconds'`` otherwise.
1562 - ``'hours'``: Include the :attr:`hour` in the two-digit HH format.
1563 - ``'minutes'``: Include :attr:`hour` and :attr:`minute` in HH:MM format.
1564 - ``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second`
1565 in HH:MM:SS format.
1566 - ``'milliseconds'``: Include full time, but truncate fractional second
1567 part to milliseconds. HH:MM:SS.sss format.
Christophe Nanteuil92878822018-10-06 00:57:02 +02001568 - ``'microseconds'``: Include full time in HH:MM:SS.ffffff format.
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001569
1570 .. note::
1571
1572 Excluded time components are truncated, not rounded.
1573
1574 :exc:`ValueError` will be raised on an invalid *timespec* argument.
1575
1576
1577 >>> from datetime import time
Berker Peksag94f89a62016-06-04 21:36:53 -07001578 >>> time(hour=12, minute=34, second=56, microsecond=123456).isoformat(timespec='minutes')
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001579 '12:34'
Berker Peksag94f89a62016-06-04 21:36:53 -07001580 >>> dt = time(hour=12, minute=34, second=56, microsecond=0)
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001581 >>> dt.isoformat(timespec='microseconds')
1582 '12:34:56.000000'
1583 >>> dt.isoformat(timespec='auto')
1584 '12:34:56'
1585
1586 .. versionadded:: 3.6
1587 Added the *timespec* argument.
1588
Georg Brandl116aa622007-08-15 14:28:22 +00001589
1590.. method:: time.__str__()
1591
1592 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1593
1594
1595.. method:: time.strftime(format)
1596
David Wolever569a5fa2013-08-12 16:56:02 -04001597 Return a string representing the time, controlled by an explicit format
1598 string. For a complete list of formatting directives, see
David Woleverbbf4a462013-08-12 17:15:36 -04001599 :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001600
1601
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001602.. method:: time.__format__(format)
1603
Martin Panterd5db1472016-02-08 01:34:09 +00001604 Same as :meth:`.time.strftime`. This makes it possible to specify a format string
Martin Panterbc1ee462016-02-13 00:41:37 +00001605 for a :class:`.time` object in :ref:`formatted string
1606 literals <f-strings>` and when using :meth:`str.format`. For a
David Wolever569a5fa2013-08-12 16:56:02 -04001607 complete list of formatting directives, see
1608 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001609
1610
Georg Brandl116aa622007-08-15 14:28:22 +00001611.. method:: time.utcoffset()
1612
Martin Panter16c7cfd2016-04-01 21:48:24 +00001613 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001614 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001615 return ``None`` or a :class:`timedelta` object with magnitude less than one day.
1616
1617 .. versionchanged:: 3.7
1618 The UTC offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001619
1620
1621.. method:: time.dst()
1622
Martin Panter16c7cfd2016-04-01 21:48:24 +00001623 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001624 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001625 ``None``, or a :class:`timedelta` object with magnitude less than one day.
Georg Brandl116aa622007-08-15 14:28:22 +00001626
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001627 .. versionchanged:: 3.7
1628 The DST offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001629
1630.. method:: time.tzname()
1631
Martin Panter16c7cfd2016-04-01 21:48:24 +00001632 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001633 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1634 return ``None`` or a string object.
1635
Christian Heimesfe337bf2008-03-23 21:54:12 +00001636Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001637
Xiang Zhang6721c7c2016-12-27 12:23:59 +08001638 >>> from datetime import time, tzinfo, timedelta
Christian Heimes895627f2007-12-08 17:28:33 +00001639 >>> class GMT1(tzinfo):
1640 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001641 ... return timedelta(hours=1)
1642 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001643 ... return timedelta(0)
1644 ... def tzname(self,dt):
1645 ... return "Europe/Prague"
1646 ...
1647 >>> t = time(12, 10, 30, tzinfo=GMT1())
1648 >>> t # doctest: +ELLIPSIS
1649 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1650 >>> gmt = GMT1()
1651 >>> t.isoformat()
1652 '12:10:30+01:00'
1653 >>> t.dst()
1654 datetime.timedelta(0)
1655 >>> t.tzname()
1656 'Europe/Prague'
1657 >>> t.strftime("%H:%M:%S %Z")
1658 '12:10:30 Europe/Prague'
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001659 >>> 'The {} is {:%H:%M}.'.format("time", t)
1660 'The time is 12:10.'
Christian Heimes895627f2007-12-08 17:28:33 +00001661
Georg Brandl116aa622007-08-15 14:28:22 +00001662
1663.. _datetime-tzinfo:
1664
1665:class:`tzinfo` Objects
1666-----------------------
1667
Martin Panter16c7cfd2016-04-01 21:48:24 +00001668.. class:: tzinfo()
Georg Brandl116aa622007-08-15 14:28:22 +00001669
Martin Panter16c7cfd2016-04-01 21:48:24 +00001670 This is an abstract base class, meaning that this class should not be
1671 instantiated directly. You need to derive a concrete subclass, and (at least)
1672 supply implementations of the standard :class:`tzinfo` methods needed by the
1673 :class:`.datetime` methods you use. The :mod:`datetime` module supplies
1674 a simple concrete subclass of :class:`tzinfo`, :class:`timezone`, which can represent
1675 timezones with fixed offset from UTC such as UTC itself or North American EST and
1676 EDT.
Georg Brandl116aa622007-08-15 14:28:22 +00001677
Martin Panter16c7cfd2016-04-01 21:48:24 +00001678 An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1679 constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
1680 view their attributes as being in local time, and the :class:`tzinfo` object
1681 supports methods revealing offset of local time from UTC, the name of the time
1682 zone, and DST offset, all relative to a date or time object passed to them.
Georg Brandl116aa622007-08-15 14:28:22 +00001683
Martin Panter16c7cfd2016-04-01 21:48:24 +00001684 Special requirement for pickling: A :class:`tzinfo` subclass must have an
1685 :meth:`__init__` method that can be called with no arguments, else it can be
1686 pickled but possibly not unpickled again. This is a technical requirement that
1687 may be relaxed in the future.
1688
1689 A concrete subclass of :class:`tzinfo` may need to implement the following
1690 methods. Exactly which methods are needed depends on the uses made of aware
1691 :mod:`datetime` objects. If in doubt, simply implement all of them.
Georg Brandl116aa622007-08-15 14:28:22 +00001692
1693
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001694.. method:: tzinfo.utcoffset(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001695
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001696 Return offset of local time from UTC, as a :class:`timedelta` object that is
1697 positive east of UTC. If local time is
Georg Brandl116aa622007-08-15 14:28:22 +00001698 west of UTC, this should be negative. Note that this is intended to be the
1699 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1700 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1701 the UTC offset isn't known, return ``None``. Else the value returned must be a
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001702 :class:`timedelta` object strictly between ``-timedelta(hours=24)`` and
1703 ``timedelta(hours=24)`` (the magnitude of the offset must be less
Georg Brandl116aa622007-08-15 14:28:22 +00001704 than one day). Most implementations of :meth:`utcoffset` will probably look
1705 like one of these two::
1706
1707 return CONSTANT # fixed-offset class
1708 return CONSTANT + self.dst(dt) # daylight-aware class
1709
1710 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1711 ``None`` either.
1712
1713 The default implementation of :meth:`utcoffset` raises
1714 :exc:`NotImplementedError`.
1715
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001716 .. versionchanged:: 3.7
1717 The UTC offset is not restricted to a whole number of minutes.
1718
Georg Brandl116aa622007-08-15 14:28:22 +00001719
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001720.. method:: tzinfo.dst(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001721
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001722 Return the daylight saving time (DST) adjustment, as a :class:`timedelta`
1723 object or
Georg Brandl116aa622007-08-15 14:28:22 +00001724 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1725 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1726 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1727 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1728 no need to consult :meth:`dst` unless you're interested in obtaining DST info
Martin Panter16c7cfd2016-04-01 21:48:24 +00001729 separately. For example, :meth:`datetime.timetuple` calls its :attr:`~.datetime.tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -07001730 attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
1731 should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
1732 DST changes when crossing time zones.
Georg Brandl116aa622007-08-15 14:28:22 +00001733
1734 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1735 daylight times must be consistent in this sense:
1736
1737 ``tz.utcoffset(dt) - tz.dst(dt)``
1738
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001739 must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo ==
Georg Brandl116aa622007-08-15 14:28:22 +00001740 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1741 zone's "standard offset", which should not depend on the date or the time, but
1742 only on geographic location. The implementation of :meth:`datetime.astimezone`
1743 relies on this, but cannot detect violations; it's the programmer's
1744 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1745 this, it may be able to override the default implementation of
1746 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1747
1748 Most implementations of :meth:`dst` will probably look like one of these two::
1749
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001750 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001751 # a fixed-offset class: doesn't account for DST
1752 return timedelta(0)
1753
1754 or ::
1755
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001756 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001757 # Code to set dston and dstoff to the time zone's DST
1758 # transition times based on the input dt.year, and expressed
1759 # in standard local time. Then
1760
1761 if dston <= dt.replace(tzinfo=None) < dstoff:
1762 return timedelta(hours=1)
1763 else:
1764 return timedelta(0)
1765
1766 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1767
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001768 .. versionchanged:: 3.7
1769 The DST offset is not restricted to a whole number of minutes.
1770
Georg Brandl116aa622007-08-15 14:28:22 +00001771
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001772.. method:: tzinfo.tzname(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001773
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001774 Return the time zone name corresponding to the :class:`.datetime` object *dt*, as
Georg Brandl116aa622007-08-15 14:28:22 +00001775 a string. Nothing about string names is defined by the :mod:`datetime` module,
1776 and there's no requirement that it mean anything in particular. For example,
1777 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1778 valid replies. Return ``None`` if a string name isn't known. Note that this is
1779 a method rather than a fixed string primarily because some :class:`tzinfo`
1780 subclasses will wish to return different names depending on the specific value
1781 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1782 daylight time.
1783
1784 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1785
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001786
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001787These methods are called by a :class:`.datetime` or :class:`.time` object, in
1788response to their methods of the same names. A :class:`.datetime` object passes
1789itself as the argument, and a :class:`.time` object passes ``None`` as the
Georg Brandl116aa622007-08-15 14:28:22 +00001790argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001791accept a *dt* argument of ``None``, or of class :class:`.datetime`.
Georg Brandl116aa622007-08-15 14:28:22 +00001792
1793When ``None`` is passed, it's up to the class designer to decide the best
1794response. For example, returning ``None`` is appropriate if the class wishes to
1795say that time objects don't participate in the :class:`tzinfo` protocols. It
1796may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1797there is no other convention for discovering the standard offset.
1798
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001799When a :class:`.datetime` object is passed in response to a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +00001800method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1801rely on this, unless user code calls :class:`tzinfo` methods directly. The
1802intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1803time, and not need worry about objects in other timezones.
1804
1805There is one more :class:`tzinfo` method that a subclass may wish to override:
1806
1807
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001808.. method:: tzinfo.fromutc(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001809
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001810 This is called from the default :class:`datetime.astimezone()`
1811 implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s
1812 date and time data are to be viewed as expressing a UTC time. The purpose
1813 of :meth:`fromutc` is to adjust the date and time data, returning an
Senthil Kumarana6bac952011-07-04 11:28:30 -07001814 equivalent datetime in *self*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00001815
1816 Most :class:`tzinfo` subclasses should be able to inherit the default
1817 :meth:`fromutc` implementation without problems. It's strong enough to handle
1818 fixed-offset time zones, and time zones accounting for both standard and
1819 daylight time, and the latter even if the DST transition times differ in
1820 different years. An example of a time zone the default :meth:`fromutc`
1821 implementation may not handle correctly in all cases is one where the standard
1822 offset (from UTC) depends on the specific date and time passed, which can happen
1823 for political reasons. The default implementations of :meth:`astimezone` and
1824 :meth:`fromutc` may not produce the result you want if the result is one of the
1825 hours straddling the moment the standard offset changes.
1826
1827 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1828 like::
1829
1830 def fromutc(self, dt):
1831 # raise ValueError error if dt.tzinfo is not self
1832 dtoff = dt.utcoffset()
1833 dtdst = dt.dst()
1834 # raise ValueError if dtoff is None or dtdst is None
1835 delta = dtoff - dtdst # this is self's standard offset
1836 if delta:
1837 dt += delta # convert to standard local time
1838 dtdst = dt.dst()
1839 # raise ValueError if dtdst is None
1840 if dtdst:
1841 return dt + dtdst
1842 else:
1843 return dt
1844
Marco Buttu909a6f62017-03-18 17:59:33 +01001845In the following :download:`tzinfo_examples.py
1846<../includes/tzinfo_examples.py>` file there are some examples of
1847:class:`tzinfo` classes:
Georg Brandl116aa622007-08-15 14:28:22 +00001848
Marco Buttu909a6f62017-03-18 17:59:33 +01001849.. literalinclude:: ../includes/tzinfo_examples.py
Georg Brandl116aa622007-08-15 14:28:22 +00001850
Georg Brandl116aa622007-08-15 14:28:22 +00001851Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1852subclass accounting for both standard and daylight time, at the DST transition
1853points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00001854minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
18551:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001856
1857 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1858 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1859 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1860
1861 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1862
1863 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1864
1865When DST starts (the "start" line), the local wall clock leaps from 1:59 to
18663:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1867``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001868begins. For example, at the Spring forward transition of 2016, we get
1869
Marco Buttu909a6f62017-03-18 17:59:33 +01001870 >>> from datetime import datetime, timezone
1871 >>> from tzinfo_examples import HOUR, Eastern
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001872 >>> u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc)
1873 >>> for i in range(4):
1874 ... u = u0 + i*HOUR
1875 ... t = u.astimezone(Eastern)
1876 ... print(u.time(), 'UTC =', t.time(), t.tzname())
1877 ...
1878 05:00:00 UTC = 00:00:00 EST
1879 06:00:00 UTC = 01:00:00 EST
1880 07:00:00 UTC = 03:00:00 EDT
1881 08:00:00 UTC = 04:00:00 EDT
1882
Georg Brandl116aa622007-08-15 14:28:22 +00001883
1884When DST ends (the "end" line), there's a potentially worse problem: there's an
1885hour that can't be spelled unambiguously in local wall time: the last hour of
1886daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1887daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1888to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1889:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1890hours into the same local hour then. In the Eastern example, UTC times of the
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001891form 5:MM and 6:MM both map to 1:MM when converted to Eastern, but earlier times
1892have the :attr:`~datetime.fold` attribute set to 0 and the later times have it set to 1.
1893For example, at the Fall back transition of 2016, we get
Georg Brandl116aa622007-08-15 14:28:22 +00001894
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001895 >>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
1896 >>> for i in range(4):
1897 ... u = u0 + i*HOUR
1898 ... t = u.astimezone(Eastern)
1899 ... print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
1900 ...
1901 04:00:00 UTC = 00:00:00 EDT 0
1902 05:00:00 UTC = 01:00:00 EDT 0
1903 06:00:00 UTC = 01:00:00 EST 1
1904 07:00:00 UTC = 02:00:00 EST 0
1905
1906Note that the :class:`datetime` instances that differ only by the value of the
1907:attr:`~datetime.fold` attribute are considered equal in comparisons.
1908
1909Applications that can't bear wall-time ambiguities should explicitly check the
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001910value of the :attr:`~datetime.fold` attribute or avoid using hybrid
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001911:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`,
1912or any other fixed-offset :class:`tzinfo` subclass (such as a class representing
1913only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
1914
Sandro Tosid11d0d62012-04-24 19:46:06 +02001915.. seealso::
1916
wim glenn53f2af12017-06-06 12:54:41 -05001917 `dateutil.tz <https://dateutil.readthedocs.io/en/stable/tz.html>`_
Benjamin Peterson9b29acd2014-06-22 16:26:39 -07001918 The standard library has :class:`timezone` class for handling arbitrary
1919 fixed offsets from UTC and :attr:`timezone.utc` as UTC timezone instance.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001920
wim glenn53f2af12017-06-06 12:54:41 -05001921 *dateutil.tz* library brings the *IANA timezone database* (also known as the
Benjamin Peterson9b29acd2014-06-22 16:26:39 -07001922 Olson database) to Python and its usage is recommended.
Sandro Tosi100b8892012-04-28 11:19:37 +02001923
Serhiy Storchaka6dff0202016-05-07 10:49:07 +03001924 `IANA timezone database <https://www.iana.org/time-zones>`_
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001925 The Time Zone Database (often called tz, tzdata or zoneinfo) contains code and
Sandro Tosi100b8892012-04-28 11:19:37 +02001926 data that represent the history of local time for many representative
1927 locations around the globe. It is updated periodically to reflect changes
1928 made by political bodies to time zone boundaries, UTC offsets, and
1929 daylight-saving rules.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001930
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001931
1932.. _datetime-timezone:
1933
1934:class:`timezone` Objects
1935--------------------------
1936
Alexander Belopolsky6d3c9a62011-05-04 10:28:26 -04001937The :class:`timezone` class is a subclass of :class:`tzinfo`, each
1938instance of which represents a timezone defined by a fixed offset from
1939UTC. Note that objects of this class cannot be used to represent
1940timezone information in the locations where different offsets are used
1941in different days of the year or where historical changes have been
1942made to civil time.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001943
1944
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001945.. class:: timezone(offset, name=None)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001946
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001947 The *offset* argument must be specified as a :class:`timedelta`
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001948 object representing the difference between the local time and UTC. It must
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001949 be strictly between ``-timedelta(hours=24)`` and
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001950 ``timedelta(hours=24)``, otherwise :exc:`ValueError` is raised.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001951
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001952 The *name* argument is optional. If specified it must be a string that
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04001953 will be used as the value returned by the :meth:`datetime.tzname` method.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001954
Benjamin Peterson9b29acd2014-06-22 16:26:39 -07001955 .. versionadded:: 3.2
1956
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001957 .. versionchanged:: 3.7
1958 The UTC offset is not restricted to a whole number of minutes.
1959
1960
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001961.. method:: timezone.utcoffset(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001962
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001963 Return the fixed value specified when the :class:`timezone` instance is
1964 constructed. The *dt* argument is ignored. The return value is a
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001965 :class:`timedelta` instance equal to the difference between the
1966 local time and UTC.
1967
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001968 .. versionchanged:: 3.7
1969 The UTC offset is not restricted to a whole number of minutes.
1970
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001971.. method:: timezone.tzname(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001972
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04001973 Return the fixed value specified when the :class:`timezone` instance
1974 is constructed. If *name* is not provided in the constructor, the
1975 name returned by ``tzname(dt)`` is generated from the value of the
1976 ``offset`` as follows. If *offset* is ``timedelta(0)``, the name
1977 is "UTC", otherwise it is a string 'UTC±HH:MM', where ± is the sign
1978 of ``offset``, HH and MM are two digits of ``offset.hours`` and
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001979 ``offset.minutes`` respectively.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001980
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04001981 .. versionchanged:: 3.6
Berker Peksagdf326eb2015-09-09 18:32:50 +03001982 Name generated from ``offset=timedelta(0)`` is now plain 'UTC', not
1983 'UTC+00:00'.
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04001984
1985
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001986.. method:: timezone.dst(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001987
1988 Always returns ``None``.
1989
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001990.. method:: timezone.fromutc(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001991
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001992 Return ``dt + offset``. The *dt* argument must be an aware
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001993 :class:`.datetime` instance, with ``tzinfo`` set to ``self``.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001994
1995Class attributes:
1996
1997.. attribute:: timezone.utc
1998
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001999 The UTC timezone, ``timezone(timedelta(0))``.
Georg Brandl48310cd2009-01-03 21:18:54 +00002000
Georg Brandl116aa622007-08-15 14:28:22 +00002001
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002002.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00002003
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002004:meth:`strftime` and :meth:`strptime` Behavior
2005----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00002006
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002007:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
Georg Brandl116aa622007-08-15 14:28:22 +00002008``strftime(format)`` method, to create a string representing the time under the
2009control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
2010acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
2011although not all objects support a :meth:`timetuple` method.
2012
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002013Conversely, the :meth:`datetime.strptime` class method creates a
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002014:class:`.datetime` object from a string representing a date and time and a
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002015corresponding format string. ``datetime.strptime(date_string, format)`` is
2016equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
2017
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002018For :class:`.time` objects, the format codes for year, month, and day should not
Georg Brandl116aa622007-08-15 14:28:22 +00002019be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002020is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00002021
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002022For :class:`date` objects, the format codes for hours, minutes, seconds, and
2023microseconds should not be used, as :class:`date` objects have no such
2024values. If they're used anyway, ``0`` is substituted for them.
2025
Georg Brandl116aa622007-08-15 14:28:22 +00002026The full set of format codes supported varies across platforms, because Python
2027calls the platform C library's :func:`strftime` function, and platform
Georg Brandlb7117af2013-10-13 18:28:25 +02002028variations are common. To see the full set of format codes supported on your
2029platform, consult the :manpage:`strftime(3)` documentation.
Christian Heimes895627f2007-12-08 17:28:33 +00002030
2031The following is a list of all the format codes that the C standard (1989
2032version) requires, and these work on all platforms with a standard C
2033implementation. Note that the 1999 version of the C standard added additional
2034format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00002035
David Wolever569a5fa2013-08-12 16:56:02 -04002036+-----------+--------------------------------+------------------------+-------+
2037| Directive | Meaning | Example | Notes |
2038+===========+================================+========================+=======+
2039| ``%a`` | Weekday as locale's || Sun, Mon, ..., Sat | \(1) |
2040| | abbreviated name. | (en_US); | |
2041| | || So, Mo, ..., Sa | |
2042| | | (de_DE) | |
2043+-----------+--------------------------------+------------------------+-------+
2044| ``%A`` | Weekday as locale's full name. || Sunday, Monday, ..., | \(1) |
2045| | | Saturday (en_US); | |
2046| | || Sonntag, Montag, ..., | |
2047| | | Samstag (de_DE) | |
2048+-----------+--------------------------------+------------------------+-------+
2049| ``%w`` | Weekday as a decimal number, | 0, 1, ..., 6 | |
2050| | where 0 is Sunday and 6 is | | |
2051| | Saturday. | | |
2052+-----------+--------------------------------+------------------------+-------+
2053| ``%d`` | Day of the month as a | 01, 02, ..., 31 | |
2054| | zero-padded decimal number. | | |
2055+-----------+--------------------------------+------------------------+-------+
2056| ``%b`` | Month as locale's abbreviated || Jan, Feb, ..., Dec | \(1) |
2057| | name. | (en_US); | |
2058| | || Jan, Feb, ..., Dez | |
2059| | | (de_DE) | |
2060+-----------+--------------------------------+------------------------+-------+
2061| ``%B`` | Month as locale's full name. || January, February, | \(1) |
2062| | | ..., December (en_US);| |
2063| | || Januar, Februar, ..., | |
2064| | | Dezember (de_DE) | |
2065+-----------+--------------------------------+------------------------+-------+
2066| ``%m`` | Month as a zero-padded | 01, 02, ..., 12 | |
2067| | decimal number. | | |
2068+-----------+--------------------------------+------------------------+-------+
2069| ``%y`` | Year without century as a | 00, 01, ..., 99 | |
2070| | zero-padded decimal number. | | |
2071+-----------+--------------------------------+------------------------+-------+
2072| ``%Y`` | Year with century as a decimal | 0001, 0002, ..., 2013, | \(2) |
David Wolever5d07e702013-08-14 14:41:48 -04002073| | number. | 2014, ..., 9998, 9999 | |
David Wolever569a5fa2013-08-12 16:56:02 -04002074+-----------+--------------------------------+------------------------+-------+
2075| ``%H`` | Hour (24-hour clock) as a | 00, 01, ..., 23 | |
2076| | zero-padded decimal number. | | |
2077+-----------+--------------------------------+------------------------+-------+
2078| ``%I`` | Hour (12-hour clock) as a | 01, 02, ..., 12 | |
2079| | zero-padded decimal number. | | |
2080+-----------+--------------------------------+------------------------+-------+
2081| ``%p`` | Locale's equivalent of either || AM, PM (en_US); | \(1), |
2082| | AM or PM. || am, pm (de_DE) | \(3) |
2083+-----------+--------------------------------+------------------------+-------+
2084| ``%M`` | Minute as a zero-padded | 00, 01, ..., 59 | |
2085| | decimal number. | | |
2086+-----------+--------------------------------+------------------------+-------+
2087| ``%S`` | Second as a zero-padded | 00, 01, ..., 59 | \(4) |
2088| | decimal number. | | |
2089+-----------+--------------------------------+------------------------+-------+
2090| ``%f`` | Microsecond as a decimal | 000000, 000001, ..., | \(5) |
2091| | number, zero-padded on the | 999999 | |
2092| | left. | | |
2093+-----------+--------------------------------+------------------------+-------+
Christophe Nanteuil92878822018-10-06 00:57:02 +02002094| ``%z`` | UTC offset in the form | (empty), +0000, | \(6) |
2095| | ±HHMM[SS[.ffffff]] (empty | -0400, +1030, | |
2096| | string if the object is | +063415, | |
2097| | naive). | -030712.345216 | |
David Wolever569a5fa2013-08-12 16:56:02 -04002098+-----------+--------------------------------+------------------------+-------+
2099| ``%Z`` | Time zone name (empty string | (empty), UTC, EST, CST | |
2100| | if the object is naive). | | |
2101+-----------+--------------------------------+------------------------+-------+
2102| ``%j`` | Day of the year as a | 001, 002, ..., 366 | |
2103| | zero-padded decimal number. | | |
2104+-----------+--------------------------------+------------------------+-------+
2105| ``%U`` | Week number of the year | 00, 01, ..., 53 | \(7) |
2106| | (Sunday as the first day of | | |
2107| | the week) as a zero padded | | |
2108| | decimal number. All days in a | | |
2109| | new year preceding the first | | |
2110| | Sunday are considered to be in | | |
2111| | week 0. | | |
2112+-----------+--------------------------------+------------------------+-------+
2113| ``%W`` | Week number of the year | 00, 01, ..., 53 | \(7) |
2114| | (Monday as the first day of | | |
2115| | the week) as a decimal number. | | |
2116| | All days in a new year | | |
2117| | preceding the first Monday | | |
2118| | are considered to be in | | |
2119| | week 0. | | |
2120+-----------+--------------------------------+------------------------+-------+
2121| ``%c`` | Locale's appropriate date and || Tue Aug 16 21:30:00 | \(1) |
2122| | time representation. | 1988 (en_US); | |
2123| | || Di 16 Aug 21:30:00 | |
2124| | | 1988 (de_DE) | |
2125+-----------+--------------------------------+------------------------+-------+
2126| ``%x`` | Locale's appropriate date || 08/16/88 (None); | \(1) |
2127| | representation. || 08/16/1988 (en_US); | |
2128| | || 16.08.1988 (de_DE) | |
2129+-----------+--------------------------------+------------------------+-------+
2130| ``%X`` | Locale's appropriate time || 21:30:00 (en_US); | \(1) |
2131| | representation. || 21:30:00 (de_DE) | |
2132+-----------+--------------------------------+------------------------+-------+
2133| ``%%`` | A literal ``'%'`` character. | % | |
2134+-----------+--------------------------------+------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00002135
Alexander Belopolsky68713e42015-10-06 13:29:56 -04002136Several additional directives not required by the C89 standard are included for
2137convenience. These parameters all correspond to ISO 8601 date values. These
2138may not be available on all platforms when used with the :meth:`strftime`
2139method. The ISO 8601 year and ISO 8601 week directives are not interchangeable
2140with the year and week number directives above. Calling :meth:`strptime` with
2141incomplete or ambiguous ISO 8601 directives will raise a :exc:`ValueError`.
2142
2143+-----------+--------------------------------+------------------------+-------+
2144| Directive | Meaning | Example | Notes |
2145+===========+================================+========================+=======+
2146| ``%G`` | ISO 8601 year with century | 0001, 0002, ..., 2013, | \(8) |
2147| | representing the year that | 2014, ..., 9998, 9999 | |
2148| | contains the greater part of | | |
2149| | the ISO week (``%V``). | | |
2150+-----------+--------------------------------+------------------------+-------+
2151| ``%u`` | ISO 8601 weekday as a decimal | 1, 2, ..., 7 | |
2152| | number where 1 is Monday. | | |
2153+-----------+--------------------------------+------------------------+-------+
2154| ``%V`` | ISO 8601 week as a decimal | 01, 02, ..., 53 | \(8) |
2155| | number with Monday as | | |
2156| | the first day of the week. | | |
2157| | Week 01 is the week containing | | |
2158| | Jan 4. | | |
2159+-----------+--------------------------------+------------------------+-------+
2160
2161.. versionadded:: 3.6
2162 ``%G``, ``%u`` and ``%V`` were added.
2163
Christian Heimes895627f2007-12-08 17:28:33 +00002164Notes:
2165
2166(1)
David Wolever569a5fa2013-08-12 16:56:02 -04002167 Because the format depends on the current locale, care should be taken when
2168 making assumptions about the output value. Field orderings will vary (for
2169 example, "month/day/year" versus "day/month/year"), and the output may
2170 contain Unicode characters encoded using the locale's default encoding (for
Georg Brandlad321532013-10-29 08:05:10 +01002171 example, if the current locale is ``ja_JP``, the default encoding could be
David Wolever569a5fa2013-08-12 16:56:02 -04002172 any one of ``eucJP``, ``SJIS``, or ``utf-8``; use :meth:`locale.getlocale`
2173 to determine the current locale's encoding).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002174
2175(2)
David Wolever569a5fa2013-08-12 16:56:02 -04002176 The :meth:`strptime` method can parse years in the full [1, 9999] range, but
2177 years < 1000 must be zero-filled to 4-digit width.
Alexander Belopolsky085556a2011-01-10 23:28:33 +00002178
2179 .. versionchanged:: 3.2
2180 In previous versions, :meth:`strftime` method was restricted to
2181 years >= 1900.
2182
Alexander Belopolsky5611a1c2011-05-02 14:14:48 -04002183 .. versionchanged:: 3.3
2184 In version 3.2, :meth:`strftime` method was restricted to
2185 years >= 1000.
2186
David Wolever569a5fa2013-08-12 16:56:02 -04002187(3)
2188 When used with the :meth:`strptime` method, the ``%p`` directive only affects
2189 the output hour field if the ``%I`` directive is used to parse the hour.
Alexander Belopolskyca94f552010-06-17 18:30:34 +00002190
David Wolever569a5fa2013-08-12 16:56:02 -04002191(4)
2192 Unlike the :mod:`time` module, the :mod:`datetime` module does not support
2193 leap seconds.
2194
2195(5)
2196 When used with the :meth:`strptime` method, the ``%f`` directive
2197 accepts from one to six digits and zero pads on the right. ``%f`` is
2198 an extension to the set of format characters in the C standard (but
2199 implemented separately in datetime objects, and therefore always
2200 available).
2201
2202(6)
2203 For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
2204 strings.
2205
2206 For an aware object:
2207
2208 ``%z``
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002209 :meth:`utcoffset` is transformed into a string of the form
Christophe Nanteuil92878822018-10-06 00:57:02 +02002210 ±HHMM[SS[.ffffff]], where HH is a 2-digit string giving the number of UTC
2211 offset hours, MM is a 2-digit string giving the number of UTC offset
Serhiy Storchakabac2d5b2018-03-28 22:14:26 +03002212 minutes, SS is a 2-digit string giving the number of UTC offset
Christophe Nanteuil92878822018-10-06 00:57:02 +02002213 seconds and ffffff is a 6-digit string giving the number of UTC
2214 offset microseconds. The ffffff part is omitted when the offset is a
2215 whole number of seconds and both the ffffff and the SS part is omitted
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002216 when the offset is a whole number of minutes. For example, if
2217 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
2218 replaced with the string ``'-0330'``.
2219
2220 .. versionchanged:: 3.7
2221 The UTC offset is not restricted to a whole number of minutes.
David Wolever569a5fa2013-08-12 16:56:02 -04002222
Mario Corchero32318932017-10-26 01:35:41 +01002223 .. versionchanged:: 3.7
2224 When the ``%z`` directive is provided to the :meth:`strptime` method,
2225 the UTC offsets can have a colon as a separator between hours, minutes
2226 and seconds.
2227 For example, ``'+01:00:00'`` will be parsed as an offset of one hour.
2228 In addition, providing ``'Z'`` is identical to ``'+00:00'``.
2229
David Wolever569a5fa2013-08-12 16:56:02 -04002230 ``%Z``
2231 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty
2232 string. Otherwise ``%Z`` is replaced by the returned value, which must
2233 be a string.
2234
2235 .. versionchanged:: 3.2
2236 When the ``%z`` directive is provided to the :meth:`strptime` method, an
2237 aware :class:`.datetime` object will be produced. The ``tzinfo`` of the
2238 result will be set to a :class:`timezone` instance.
2239
2240(7)
2241 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used
Alexander Belopolsky68713e42015-10-06 13:29:56 -04002242 in calculations when the day of the week and the calendar year (``%Y``)
2243 are specified.
2244
2245(8)
2246 Similar to ``%U`` and ``%W``, ``%V`` is only used in calculations when the
2247 day of the week and the ISO year (``%G``) are specified in a
2248 :meth:`strptime` format string. Also note that ``%G`` and ``%Y`` are not
Martin Panterf1579822016-05-26 06:03:33 +00002249 interchangeable.
R David Murray9075d8b2012-05-14 22:14:46 -04002250
2251.. rubric:: Footnotes
2252
2253.. [#] If, that is, we ignore the effects of Relativity