blob: fb41aeeb5bed037f24e8f3c313a05e433870f28a [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`datetime` --- Basic date and time types
2=============================================
3
4.. module:: datetime
5 :synopsis: Basic date and time types.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Tim Peters <tim@zope.com>
8.. sectionauthor:: Tim Peters <tim@zope.com>
9.. sectionauthor:: A.M. Kuchling <amk@amk.ca>
10
Andrew Kuchling2e3743c2014-03-19 16:23:01 -040011**Source code:** :source:`Lib/datetime.py`
12
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040013--------------
14
Christian Heimes5b5e81c2007-12-31 16:14:33 +000015.. XXX what order should the types be discussed in?
Georg Brandl116aa622007-08-15 14:28:22 +000016
Georg Brandl116aa622007-08-15 14:28:22 +000017The :mod:`datetime` module supplies classes for manipulating dates and times in
18both simple and complex ways. While date and time arithmetic is supported, the
Senthil Kumarana6bac952011-07-04 11:28:30 -070019focus of the implementation is on efficient attribute extraction for output
R David Murray539f2392012-05-14 22:17:23 -040020formatting and manipulation. For related functionality, see also the
21:mod:`time` and :mod:`calendar` modules.
Georg Brandl116aa622007-08-15 14:28:22 +000022
R David Murray9075d8b2012-05-14 22:14:46 -040023There are two kinds of date and time objects: "naive" and "aware".
Georg Brandl116aa622007-08-15 14:28:22 +000024
R David Murray9075d8b2012-05-14 22:14:46 -040025An aware object has sufficient knowledge of applicable algorithmic and
26political time adjustments, such as time zone and daylight saving time
27information, to locate itself relative to other aware objects. An aware object
28is used to represent a specific moment in time that is not open to
29interpretation [#]_.
30
31A naive object does not contain enough information to unambiguously locate
32itself relative to other date/time objects. Whether a naive object represents
R David Murray539f2392012-05-14 22:17:23 -040033Coordinated Universal Time (UTC), local time, or time in some other timezone is
34purely up to the program, just like it is up to the program whether a
35particular number represents metres, miles, or mass. Naive objects are easy to
36understand and to work with, at the cost of ignoring some aspects of reality.
Georg Brandl116aa622007-08-15 14:28:22 +000037
R David Murray539f2392012-05-14 22:17:23 -040038For applications requiring aware objects, :class:`.datetime` and :class:`.time`
Martin Panter16c7cfd2016-04-01 21:48:24 +000039objects have an optional time zone information attribute, :attr:`!tzinfo`, that
R David Murray539f2392012-05-14 22:17:23 -040040can be set to an instance of a subclass of the abstract :class:`tzinfo` class.
41These :class:`tzinfo` objects capture information about the offset from UTC
42time, the time zone name, and whether Daylight Saving Time is in effect. Note
43that only one concrete :class:`tzinfo` class, the :class:`timezone` class, is
44supplied by the :mod:`datetime` module. The :class:`timezone` class can
45represent simple timezones with fixed offset from UTC, such as UTC itself or
46North American EST and EDT timezones. Supporting timezones at deeper levels of
47detail is up to the application. The rules for time adjustment across the
Alexander Belopolsky4e749a12010-06-14 14:15:50 +000048world are more political than rational, change frequently, and there is no
49standard suitable for every application aside from UTC.
Georg Brandl116aa622007-08-15 14:28:22 +000050
51The :mod:`datetime` module exports the following constants:
52
Georg Brandl116aa622007-08-15 14:28:22 +000053.. data:: MINYEAR
54
Ezio Melotti35ec7f72011-10-02 12:44:50 +030055 The smallest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl116aa622007-08-15 14:28:22 +000056 :const:`MINYEAR` is ``1``.
57
58
59.. data:: MAXYEAR
60
Ezio Melotti35ec7f72011-10-02 12:44:50 +030061 The largest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl116aa622007-08-15 14:28:22 +000062 :const:`MAXYEAR` is ``9999``.
63
64
65.. seealso::
66
67 Module :mod:`calendar`
68 General calendar related functions.
69
70 Module :mod:`time`
71 Time access and conversions.
72
73
74Available Types
75---------------
76
Georg Brandl116aa622007-08-15 14:28:22 +000077.. class:: date
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000078 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000079
80 An idealized naive date, assuming the current Gregorian calendar always was, and
81 always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and
82 :attr:`day`.
83
84
85.. class:: time
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000086 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000087
88 An idealized time, independent of any particular day, assuming that every day
89 has exactly 24\*60\*60 seconds (there is no notion of "leap seconds" here).
90 Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
Martin Panter16c7cfd2016-04-01 21:48:24 +000091 and :attr:`.tzinfo`.
Georg Brandl116aa622007-08-15 14:28:22 +000092
93
94.. class:: datetime
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000095 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000096
97 A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`,
98 :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
Martin Panter16c7cfd2016-04-01 21:48:24 +000099 and :attr:`.tzinfo`.
Georg Brandl116aa622007-08-15 14:28:22 +0000100
101
102.. class:: timedelta
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000103 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000104
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300105 A duration expressing the difference between two :class:`date`, :class:`.time`,
106 or :class:`.datetime` instances to microsecond resolution.
Georg Brandl116aa622007-08-15 14:28:22 +0000107
108
109.. class:: tzinfo
Martin Panter16c7cfd2016-04-01 21:48:24 +0000110 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000111
112 An abstract base class for time zone information objects. These are used by the
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300113 :class:`.datetime` and :class:`.time` classes to provide a customizable notion of
Georg Brandl116aa622007-08-15 14:28:22 +0000114 time adjustment (for example, to account for time zone and/or daylight saving
115 time).
116
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000117.. class:: timezone
Martin Panter16c7cfd2016-04-01 21:48:24 +0000118 :noindex:
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000119
120 A class that implements the :class:`tzinfo` abstract base class as a
121 fixed offset from the UTC.
122
123 .. versionadded:: 3.2
124
125
Georg Brandl116aa622007-08-15 14:28:22 +0000126Objects of these types are immutable.
127
128Objects of the :class:`date` type are always naive.
129
R David Murray9075d8b2012-05-14 22:14:46 -0400130An object of type :class:`.time` or :class:`.datetime` may be naive or aware.
131A :class:`.datetime` object *d* is aware if ``d.tzinfo`` is not ``None`` and
132``d.tzinfo.utcoffset(d)`` does not return ``None``. If ``d.tzinfo`` is
133``None``, or if ``d.tzinfo`` is not ``None`` but ``d.tzinfo.utcoffset(d)``
134returns ``None``, *d* is naive. A :class:`.time` object *t* is aware
135if ``t.tzinfo`` is not ``None`` and ``t.tzinfo.utcoffset(None)`` does not return
136``None``. Otherwise, *t* is naive.
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138The distinction between naive and aware doesn't apply to :class:`timedelta`
139objects.
140
141Subclass relationships::
142
143 object
144 timedelta
145 tzinfo
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000146 timezone
Georg Brandl116aa622007-08-15 14:28:22 +0000147 time
148 date
149 datetime
150
151
152.. _datetime-timedelta:
153
154:class:`timedelta` Objects
155--------------------------
156
157A :class:`timedelta` object represents a duration, the difference between two
158dates or times.
159
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000160.. class:: timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000161
Georg Brandl5c106642007-11-29 17:41:05 +0000162 All arguments are optional and default to ``0``. Arguments may be integers
Georg Brandl116aa622007-08-15 14:28:22 +0000163 or floats, and may be positive or negative.
164
165 Only *days*, *seconds* and *microseconds* are stored internally. Arguments are
166 converted to those units:
167
168 * A millisecond is converted to 1000 microseconds.
169 * A minute is converted to 60 seconds.
170 * An hour is converted to 3600 seconds.
171 * A week is converted to 7 days.
172
173 and days, seconds and microseconds are then normalized so that the
174 representation is unique, with
175
176 * ``0 <= microseconds < 1000000``
177 * ``0 <= seconds < 3600*24`` (the number of seconds in one day)
178 * ``-999999999 <= days <= 999999999``
179
Alexander Belopolsky790d2692013-08-04 14:51:35 -0400180 If any argument is a float and there are fractional microseconds,
181 the fractional microseconds left over from all arguments are
182 combined and their sum is rounded to the nearest microsecond using
183 round-half-to-even tiebreaker. If no argument is a float, the
184 conversion and normalization processes are exact (no information is
185 lost).
Georg Brandl116aa622007-08-15 14:28:22 +0000186
187 If the normalized value of days lies outside the indicated range,
188 :exc:`OverflowError` is raised.
189
190 Note that normalization of negative values may be surprising at first. For
Christian Heimesfe337bf2008-03-23 21:54:12 +0000191 example,
Georg Brandl116aa622007-08-15 14:28:22 +0000192
Christian Heimes895627f2007-12-08 17:28:33 +0000193 >>> from datetime import timedelta
Georg Brandl116aa622007-08-15 14:28:22 +0000194 >>> d = timedelta(microseconds=-1)
195 >>> (d.days, d.seconds, d.microseconds)
196 (-1, 86399, 999999)
197
Georg Brandl116aa622007-08-15 14:28:22 +0000198
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000199Class attributes are:
Georg Brandl116aa622007-08-15 14:28:22 +0000200
201.. attribute:: timedelta.min
202
203 The most negative :class:`timedelta` object, ``timedelta(-999999999)``.
204
205
206.. attribute:: timedelta.max
207
208 The most positive :class:`timedelta` object, ``timedelta(days=999999999,
209 hours=23, minutes=59, seconds=59, microseconds=999999)``.
210
211
212.. attribute:: timedelta.resolution
213
214 The smallest possible difference between non-equal :class:`timedelta` objects,
215 ``timedelta(microseconds=1)``.
216
217Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``.
218``-timedelta.max`` is not representable as a :class:`timedelta` object.
219
220Instance attributes (read-only):
221
222+------------------+--------------------------------------------+
223| Attribute | Value |
224+==================+============================================+
225| ``days`` | Between -999999999 and 999999999 inclusive |
226+------------------+--------------------------------------------+
227| ``seconds`` | Between 0 and 86399 inclusive |
228+------------------+--------------------------------------------+
229| ``microseconds`` | Between 0 and 999999 inclusive |
230+------------------+--------------------------------------------+
231
232Supported operations:
233
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000234.. XXX this table is too wide!
Georg Brandl116aa622007-08-15 14:28:22 +0000235
236+--------------------------------+-----------------------------------------------+
237| Operation | Result |
238+================================+===============================================+
239| ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == |
240| | *t3* and *t1*-*t3* == *t2* are true. (1) |
241+--------------------------------+-----------------------------------------------+
242| ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* |
243| | == *t2* - *t3* and *t2* == *t1* + *t3* are |
Farhaan Bukhsh5b6e49a2018-07-05 00:12:05 +0530244| | true. (1)(6) |
Georg Brandl116aa622007-08-15 14:28:22 +0000245+--------------------------------+-----------------------------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000246| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer. |
Georg Brandl116aa622007-08-15 14:28:22 +0000247| | Afterwards *t1* // i == *t2* is true, |
248| | provided ``i != 0``. |
249+--------------------------------+-----------------------------------------------+
250| | In general, *t1* \* i == *t1* \* (i-1) + *t1* |
251| | is true. (1) |
252+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000253| ``t1 = t2 * f or t1 = f * t2`` | Delta multiplied by a float. The result is |
254| | rounded to the nearest multiple of |
255| | timedelta.resolution using round-half-to-even.|
256+--------------------------------+-----------------------------------------------+
Yasser Af40b4a02019-03-15 23:56:58 -0400257| ``f = t2 / t3`` | Division (3) of overall duration *t2* by |
258| | interval unit *t3*. Returns a :class:`float` |
259| | object. |
Mark Dickinson7c186e22010-04-20 22:32:49 +0000260+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000261| ``t1 = t2 / f or t1 = t2 / i`` | Delta divided by a float or an int. The result|
262| | is rounded to the nearest multiple of |
263| | timedelta.resolution using round-half-to-even.|
264+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000265| ``t1 = t2 // i`` or | The floor is computed and the remainder (if |
266| ``t1 = t2 // t3`` | any) is thrown away. In the second case, an |
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000267| | integer is returned. (3) |
Mark Dickinson7c186e22010-04-20 22:32:49 +0000268+--------------------------------+-----------------------------------------------+
269| ``t1 = t2 % t3`` | The remainder is computed as a |
270| | :class:`timedelta` object. (3) |
271+--------------------------------+-----------------------------------------------+
272| ``q, r = divmod(t1, t2)`` | Computes the quotient and the remainder: |
273| | ``q = t1 // t2`` (3) and ``r = t1 % t2``. |
274| | q is an integer and r is a :class:`timedelta` |
275| | object. |
Georg Brandl116aa622007-08-15 14:28:22 +0000276+--------------------------------+-----------------------------------------------+
277| ``+t1`` | Returns a :class:`timedelta` object with the |
278| | same value. (2) |
279+--------------------------------+-----------------------------------------------+
Serhiy Storchaka3f819ca2018-10-31 02:26:06 +0200280| ``-t1`` | equivalent to |
281| | :class:`timedelta`\ (-*t1.days*, |
282| | -*t1.seconds*, -*t1.microseconds*), |
283| | and to *t1*\* -1. (1)(4) |
Georg Brandl116aa622007-08-15 14:28:22 +0000284+--------------------------------+-----------------------------------------------+
Georg Brandl495f7b52009-10-27 15:28:25 +0000285| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, and|
Georg Brandl116aa622007-08-15 14:28:22 +0000286| | to -*t* when ``t.days < 0``. (2) |
287+--------------------------------+-----------------------------------------------+
Georg Brandlf55c3152010-07-31 11:40:07 +0000288| ``str(t)`` | Returns a string in the form |
289| | ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D |
290| | is negative for negative ``t``. (5) |
291+--------------------------------+-----------------------------------------------+
Utkarsh Upadhyaycc5a65c2017-07-25 23:51:33 +0200292| ``repr(t)`` | Returns a string representation of the |
293| | :class:`timedelta` object as a constructor |
294| | call with canonical attribute values. |
Georg Brandlf55c3152010-07-31 11:40:07 +0000295+--------------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000296
Utkarsh Upadhyaycc5a65c2017-07-25 23:51:33 +0200297
Georg Brandl116aa622007-08-15 14:28:22 +0000298Notes:
299
300(1)
301 This is exact, but may overflow.
302
303(2)
304 This is exact, and cannot overflow.
305
306(3)
307 Division by 0 raises :exc:`ZeroDivisionError`.
308
309(4)
310 -*timedelta.max* is not representable as a :class:`timedelta` object.
311
Georg Brandlf55c3152010-07-31 11:40:07 +0000312(5)
313 String representations of :class:`timedelta` objects are normalized
314 similarly to their internal representation. This leads to somewhat
315 unusual results for negative timedeltas. For example:
316
317 >>> timedelta(hours=-5)
Utkarsh Upadhyay8e453182017-07-28 14:42:56 +0200318 datetime.timedelta(days=-1, seconds=68400)
Georg Brandlf55c3152010-07-31 11:40:07 +0000319 >>> print(_)
320 -1 day, 19:00:00
321
Farhaan Bukhsh5b6e49a2018-07-05 00:12:05 +0530322(6)
323 The expression ``t2 - t3`` will always be equal to the expression ``t2 + (-t3)`` except
324 when t3 is equal to ``timedelta.max``; in that case the former will produce a result
325 while the latter will overflow.
326
Georg Brandl116aa622007-08-15 14:28:22 +0000327In addition to the operations listed above :class:`timedelta` objects support
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300328certain additions and subtractions with :class:`date` and :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +0000329objects (see below).
330
Georg Brandl67b21b72010-08-17 15:07:14 +0000331.. versionchanged:: 3.2
332 Floor division and true division of a :class:`timedelta` object by another
333 :class:`timedelta` object are now supported, as are remainder operations and
334 the :func:`divmod` function. True division and multiplication of a
335 :class:`timedelta` object by a :class:`float` object are now supported.
Mark Dickinson7c186e22010-04-20 22:32:49 +0000336
337
Georg Brandl116aa622007-08-15 14:28:22 +0000338Comparisons of :class:`timedelta` objects are supported with the
339:class:`timedelta` object representing the smaller duration considered to be the
340smaller timedelta. In order to stop mixed-type comparisons from falling back to
341the default comparison by object address, when a :class:`timedelta` object is
342compared to an object of a different type, :exc:`TypeError` is raised unless the
343comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
344:const:`True`, respectively.
345
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000346:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl116aa622007-08-15 14:28:22 +0000347efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
348considered to be true if and only if it isn't equal to ``timedelta(0)``.
349
Antoine Pitroube6859d2009-11-25 23:02:32 +0000350Instance methods:
351
352.. method:: timedelta.total_seconds()
353
354 Return the total number of seconds contained in the duration. Equivalent to
Yasser Af40b4a02019-03-15 23:56:58 -0400355 ``td / timedelta(seconds=1)``. For interval units other than seconds, use the
356 division form directly (e.g. ``td / timedelta(microseconds=1)``).
Mark Dickinson0381e3f2010-05-08 14:35:02 +0000357
358 Note that for very large time intervals (greater than 270 years on
359 most platforms) this method will lose microsecond accuracy.
Antoine Pitroube6859d2009-11-25 23:02:32 +0000360
361 .. versionadded:: 3.2
362
363
Christian Heimesfe337bf2008-03-23 21:54:12 +0000364Example usage:
Georg Brandl48310cd2009-01-03 21:18:54 +0000365
Christian Heimes895627f2007-12-08 17:28:33 +0000366 >>> from datetime import timedelta
367 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000368 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Christian Heimes895627f2007-12-08 17:28:33 +0000369 ... minutes=50, seconds=600) # adds up to 365 days
Antoine Pitroube6859d2009-11-25 23:02:32 +0000370 >>> year.total_seconds()
371 31536000.0
Christian Heimes895627f2007-12-08 17:28:33 +0000372 >>> year == another_year
373 True
374 >>> ten_years = 10 * year
375 >>> ten_years, ten_years.days // 365
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +0200376 (datetime.timedelta(days=3650), 10)
Christian Heimes895627f2007-12-08 17:28:33 +0000377 >>> nine_years = ten_years - year
378 >>> nine_years, nine_years.days // 365
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +0200379 (datetime.timedelta(days=3285), 9)
delirious-lettucec7b3f0f2017-05-18 19:01:00 -0600380 >>> three_years = nine_years // 3
Christian Heimes895627f2007-12-08 17:28:33 +0000381 >>> three_years, three_years.days // 365
Utkarsh Upadhyay843ea472017-10-27 13:25:15 +0200382 (datetime.timedelta(days=1095), 3)
Christian Heimes895627f2007-12-08 17:28:33 +0000383 >>> abs(three_years - ten_years) == 2 * three_years + year
384 True
385
Georg Brandl116aa622007-08-15 14:28:22 +0000386
387.. _datetime-date:
388
389:class:`date` Objects
390---------------------
391
392A :class:`date` object represents a date (year, month and day) in an idealized
393calendar, the current Gregorian calendar indefinitely extended in both
394directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
395called day number 2, and so on. This matches the definition of the "proleptic
396Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
397where it's the base calendar for all computations. See the book for algorithms
398for converting between proleptic Gregorian ordinals and many other calendar
399systems.
400
401
402.. class:: date(year, month, day)
403
Georg Brandl5c106642007-11-29 17:41:05 +0000404 All arguments are required. Arguments may be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000405 ranges:
406
407 * ``MINYEAR <= year <= MAXYEAR``
408 * ``1 <= month <= 12``
409 * ``1 <= day <= number of days in the given month and year``
410
411 If an argument outside those ranges is given, :exc:`ValueError` is raised.
412
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000413
Georg Brandl116aa622007-08-15 14:28:22 +0000414Other constructors, all class methods:
415
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000416.. classmethod:: date.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000417
418 Return the current local date. This is equivalent to
419 ``date.fromtimestamp(time.time())``.
420
421
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000422.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000423
424 Return the local date corresponding to the POSIX timestamp, such as is returned
Victor Stinner5d272cc2012-03-13 13:35:55 +0100425 by :func:`time.time`. This may raise :exc:`OverflowError`, if the timestamp is out
Victor Stinnerecc6e662012-03-14 00:39:29 +0100426 of the range of values supported by the platform C :c:func:`localtime` function,
427 and :exc:`OSError` on :c:func:`localtime` failure.
Georg Brandl116aa622007-08-15 14:28:22 +0000428 It's common for this to be restricted to years from 1970 through 2038. Note
429 that on non-POSIX systems that include leap seconds in their notion of a
430 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
431
Victor Stinner5d272cc2012-03-13 13:35:55 +0100432 .. versionchanged:: 3.3
433 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
434 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100435 :c:func:`localtime` function. Raise :exc:`OSError` instead of
436 :exc:`ValueError` on :c:func:`localtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100437
Georg Brandl116aa622007-08-15 14:28:22 +0000438
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000439.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000440
441 Return the date corresponding to the proleptic Gregorian ordinal, where January
442 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
443 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
444 d``.
445
Georg Brandl116aa622007-08-15 14:28:22 +0000446
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500447.. classmethod:: date.fromisoformat(date_string)
448
449 Return a :class:`date` corresponding to a *date_string* in the format emitted
450 by :meth:`date.isoformat`. Specifically, this function supports strings in
451 the format(s) ``YYYY-MM-DD``.
452
453 .. caution::
454
455 This does not support parsing arbitrary ISO 8601 strings - it is only intended
456 as the inverse operation of :meth:`date.isoformat`.
457
458 .. versionadded:: 3.7
459
460
Paul Ganssle88c09372019-04-29 09:22:03 -0400461.. classmethod:: date.fromisocalendar(year, week, day)
462
463 Return a :class:`date` corresponding to the ISO calendar date specified by
464 year, week and day. This is the inverse of the function :meth:`date.isocalendar`.
465
466 .. versionadded:: 3.8
467
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500468
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000469Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000470
471.. attribute:: date.min
472
473 The earliest representable date, ``date(MINYEAR, 1, 1)``.
474
475
476.. attribute:: date.max
477
478 The latest representable date, ``date(MAXYEAR, 12, 31)``.
479
480
481.. attribute:: date.resolution
482
483 The smallest possible difference between non-equal date objects,
484 ``timedelta(days=1)``.
485
Georg Brandl116aa622007-08-15 14:28:22 +0000486
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000487Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000488
489.. attribute:: date.year
490
491 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
492
493
494.. attribute:: date.month
495
496 Between 1 and 12 inclusive.
497
498
499.. attribute:: date.day
500
501 Between 1 and the number of days in the given month of the given year.
502
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000503
Georg Brandl116aa622007-08-15 14:28:22 +0000504Supported operations:
505
506+-------------------------------+----------------------------------------------+
507| Operation | Result |
508+===============================+==============================================+
509| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
510| | from *date1*. (1) |
511+-------------------------------+----------------------------------------------+
512| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
513| | timedelta == date1``. (2) |
514+-------------------------------+----------------------------------------------+
515| ``timedelta = date1 - date2`` | \(3) |
516+-------------------------------+----------------------------------------------+
517| ``date1 < date2`` | *date1* is considered less than *date2* when |
518| | *date1* precedes *date2* in time. (4) |
519+-------------------------------+----------------------------------------------+
520
521Notes:
522
523(1)
524 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
525 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
526 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
527 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
528 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
529
530(2)
Georg Brandl116aa622007-08-15 14:28:22 +0000531 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
532
533(3)
534 This is exact, and cannot overflow. timedelta.seconds and
535 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
536
537(4)
538 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
Danish Prakash9c223792018-09-12 02:29:23 +0530539 date2.toordinal()``. Date comparison raises :exc:`TypeError` if
540 the other comparand isn't also a :class:`date` object. However,
541 ``NotImplemented`` is returned instead if the other comparand has a
Georg Brandl116aa622007-08-15 14:28:22 +0000542 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
543 chance at implementing mixed-type comparison. If not, when a :class:`date`
544 object is compared to an object of a different type, :exc:`TypeError` is raised
545 unless the comparison is ``==`` or ``!=``. The latter cases return
546 :const:`False` or :const:`True`, respectively.
547
548Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
549objects are considered to be true.
550
551Instance methods:
552
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400553.. method:: date.replace(year=self.year, month=self.month, day=self.day)
Georg Brandl116aa622007-08-15 14:28:22 +0000554
Senthil Kumarana6bac952011-07-04 11:28:30 -0700555 Return a date with the same value, except for those parameters given new
556 values by whichever keyword arguments are specified. For example, if ``d ==
557 date(2002, 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000558
559
560.. method:: date.timetuple()
561
562 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
563 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
564 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000565 d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1,
566 1).toordinal() + 1`` is the day number within the current year starting with
567 ``1`` for January 1st.
Georg Brandl116aa622007-08-15 14:28:22 +0000568
569
570.. method:: date.toordinal()
571
572 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
573 has ordinal 1. For any :class:`date` object *d*,
574 ``date.fromordinal(d.toordinal()) == d``.
575
576
577.. method:: date.weekday()
578
579 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
580 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
581 :meth:`isoweekday`.
582
583
584.. method:: date.isoweekday()
585
586 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
587 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
588 :meth:`weekday`, :meth:`isocalendar`.
589
590
591.. method:: date.isocalendar()
592
593 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
594
595 The ISO calendar is a widely used variant of the Gregorian calendar. See
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300596 https://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm for a good
Mark Dickinsonf964ac22009-11-03 16:29:10 +0000597 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000598
599 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
600 Monday and ends on a Sunday. The first week of an ISO year is the first
601 (Gregorian) calendar week of a year containing a Thursday. This is called week
602 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
603
604 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
605 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
606 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
607 4).isocalendar() == (2004, 1, 7)``.
608
609
610.. method:: date.isoformat()
611
612 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
613 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
614
615
616.. method:: date.__str__()
617
618 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
619
620
621.. method:: date.ctime()
622
623 Return a string representing the date, for example ``date(2002, 12,
624 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
625 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
Georg Brandl60203b42010-10-06 10:11:56 +0000626 :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +0000627 :meth:`date.ctime` does not invoke) conforms to the C standard.
628
629
630.. method:: date.strftime(format)
631
632 Return a string representing the date, controlled by an explicit format string.
David Wolever569a5fa2013-08-12 16:56:02 -0400633 Format codes referring to hours, minutes or seconds will see 0 values. For a
634 complete list of formatting directives, see
635 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000636
Georg Brandl116aa622007-08-15 14:28:22 +0000637
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300638.. method:: date.__format__(format)
639
Martin Panterd5db1472016-02-08 01:34:09 +0000640 Same as :meth:`.date.strftime`. This makes it possible to specify a format
Martin Panterbc1ee462016-02-13 00:41:37 +0000641 string for a :class:`.date` object in :ref:`formatted string
642 literals <f-strings>` and when using :meth:`str.format`. For a
David Wolever569a5fa2013-08-12 16:56:02 -0400643 complete list of formatting directives, see
644 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300645
646
Christian Heimes895627f2007-12-08 17:28:33 +0000647Example of counting days to an event::
648
649 >>> import time
650 >>> from datetime import date
651 >>> today = date.today()
652 >>> today
653 datetime.date(2007, 12, 5)
654 >>> today == date.fromtimestamp(time.time())
655 True
656 >>> my_birthday = date(today.year, 6, 24)
657 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000658 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000659 >>> my_birthday
660 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000661 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000662 >>> time_to_birthday.days
663 202
664
Christian Heimesfe337bf2008-03-23 21:54:12 +0000665Example of working with :class:`date`:
666
667.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000668
669 >>> from datetime import date
670 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
671 >>> d
672 datetime.date(2002, 3, 11)
673 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000674 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000675 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000676 2002 # year
677 3 # month
678 11 # day
679 0
680 0
681 0
682 0 # weekday (0 = Monday)
683 70 # 70th day in the year
684 -1
685 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000686 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000687 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000688 2002 # ISO year
689 11 # ISO week number
690 1 # ISO day number ( 1 = Monday )
691 >>> d.isoformat()
692 '2002-03-11'
693 >>> d.strftime("%d/%m/%y")
694 '11/03/02'
695 >>> d.strftime("%A %d. %B %Y")
696 'Monday 11. March 2002'
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300697 >>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")
698 'The day is 11, the month is March.'
Christian Heimes895627f2007-12-08 17:28:33 +0000699
Georg Brandl116aa622007-08-15 14:28:22 +0000700
701.. _datetime-datetime:
702
Benjamin Petersond87dd432015-04-25 14:15:16 -0400703:class:`.datetime` Objects
704--------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000705
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300706A :class:`.datetime` object is a single object containing all the information
707from a :class:`date` object and a :class:`.time` object. Like a :class:`date`
708object, :class:`.datetime` assumes the current Gregorian calendar extended in
709both directions; like a time object, :class:`.datetime` assumes there are exactly
Georg Brandl116aa622007-08-15 14:28:22 +00007103600\*24 seconds in every day.
711
712Constructor:
713
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400714.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000715
716 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000717 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
718 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000719
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400720 * ``MINYEAR <= year <= MAXYEAR``,
721 * ``1 <= month <= 12``,
722 * ``1 <= day <= number of days in the given month and year``,
723 * ``0 <= hour < 24``,
724 * ``0 <= minute < 60``,
725 * ``0 <= second < 60``,
726 * ``0 <= microsecond < 1000000``,
727 * ``fold in [0, 1]``.
Georg Brandl116aa622007-08-15 14:28:22 +0000728
729 If an argument outside those ranges is given, :exc:`ValueError` is raised.
730
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400731 .. versionadded:: 3.6
732 Added the ``fold`` argument.
733
Georg Brandl116aa622007-08-15 14:28:22 +0000734Other constructors, all class methods:
735
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000736.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000737
Martin Panter16c7cfd2016-04-01 21:48:24 +0000738 Return the current local datetime, with :attr:`.tzinfo` ``None``. This is
Georg Brandl116aa622007-08-15 14:28:22 +0000739 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
740 :meth:`fromtimestamp`.
741
742
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000743.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000744
745 Return the current local date and time. If optional argument *tz* is ``None``
746 or not specified, this is like :meth:`today`, but, if possible, supplies more
747 precision than can be gotten from going through a :func:`time.time` timestamp
748 (for example, this may be possible on platforms supplying the C
Georg Brandl60203b42010-10-06 10:11:56 +0000749 :c:func:`gettimeofday` function).
Georg Brandl116aa622007-08-15 14:28:22 +0000750
Martin Panter16c7cfd2016-04-01 21:48:24 +0000751 If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` subclass, and the
752 current date and time are converted to *tz*’s time zone. In this case the
Georg Brandl116aa622007-08-15 14:28:22 +0000753 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
754 See also :meth:`today`, :meth:`utcnow`.
755
756
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000757.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000758
Martin Panter16c7cfd2016-04-01 21:48:24 +0000759 Return the current UTC date and time, with :attr:`.tzinfo` ``None``. This is like
Georg Brandl116aa622007-08-15 14:28:22 +0000760 :meth:`now`, but returns the current UTC date and time, as a naive
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300761 :class:`.datetime` object. An aware current UTC datetime can be obtained by
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000762 calling ``datetime.now(timezone.utc)``. See also :meth:`now`.
Georg Brandl116aa622007-08-15 14:28:22 +0000763
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000764.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000765
766 Return the local date and time corresponding to the POSIX timestamp, such as is
767 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
768 specified, the timestamp is converted to the platform's local date and time, and
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300769 the returned :class:`.datetime` object is naive.
Georg Brandl116aa622007-08-15 14:28:22 +0000770
Martin Panter16c7cfd2016-04-01 21:48:24 +0000771 If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` subclass, and the
772 timestamp is converted to *tz*’s time zone. In this case the result is
Georg Brandl116aa622007-08-15 14:28:22 +0000773 equivalent to
774 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
775
Victor Stinnerecc6e662012-03-14 00:39:29 +0100776 :meth:`fromtimestamp` may raise :exc:`OverflowError`, if the timestamp is out of
Georg Brandl60203b42010-10-06 10:11:56 +0000777 the range of values supported by the platform C :c:func:`localtime` or
Victor Stinnerecc6e662012-03-14 00:39:29 +0100778 :c:func:`gmtime` functions, and :exc:`OSError` on :c:func:`localtime` or
779 :c:func:`gmtime` failure.
780 It's common for this to be restricted to years in
Georg Brandl116aa622007-08-15 14:28:22 +0000781 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
782 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
783 and then it's possible to have two timestamps differing by a second that yield
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300784 identical :class:`.datetime` objects. See also :meth:`utcfromtimestamp`.
Georg Brandl116aa622007-08-15 14:28:22 +0000785
Victor Stinner5d272cc2012-03-13 13:35:55 +0100786 .. versionchanged:: 3.3
787 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
788 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100789 :c:func:`localtime` or :c:func:`gmtime` functions. Raise :exc:`OSError`
790 instead of :exc:`ValueError` on :c:func:`localtime` or :c:func:`gmtime`
791 failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100792
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400793 .. versionchanged:: 3.6
794 :meth:`fromtimestamp` may return instances with :attr:`.fold` set to 1.
Georg Brandl116aa622007-08-15 14:28:22 +0000795
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000796.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000797
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300798 Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with
Martin Panter16c7cfd2016-04-01 21:48:24 +0000799 :attr:`.tzinfo` ``None``. This may raise :exc:`OverflowError`, if the timestamp is
Victor Stinnerecc6e662012-03-14 00:39:29 +0100800 out of the range of values supported by the platform C :c:func:`gmtime` function,
801 and :exc:`OSError` on :c:func:`gmtime` failure.
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500802 It's common for this to be restricted to years in 1970 through 2038.
Georg Brandl116aa622007-08-15 14:28:22 +0000803
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500804 To get an aware :class:`.datetime` object, call :meth:`fromtimestamp`::
Alexander Belopolsky54afa552011-04-25 13:00:40 -0400805
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500806 datetime.fromtimestamp(timestamp, timezone.utc)
807
808 On the POSIX compliant platforms, it is equivalent to the following
809 expression::
810
811 datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)
812
813 except the latter formula always supports the full years range: between
814 :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
Alexander Belopolsky54afa552011-04-25 13:00:40 -0400815
Victor Stinner5d272cc2012-03-13 13:35:55 +0100816 .. versionchanged:: 3.3
817 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
818 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100819 :c:func:`gmtime` function. Raise :exc:`OSError` instead of
820 :exc:`ValueError` on :c:func:`gmtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100821
Georg Brandl116aa622007-08-15 14:28:22 +0000822
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000823.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000824
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300825 Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal,
Georg Brandl116aa622007-08-15 14:28:22 +0000826 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
827 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
Martin Panter16c7cfd2016-04-01 21:48:24 +0000828 microsecond of the result are all 0, and :attr:`.tzinfo` is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000829
830
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400831.. classmethod:: datetime.combine(date, time, tzinfo=self.tzinfo)
Georg Brandl116aa622007-08-15 14:28:22 +0000832
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300833 Return a new :class:`.datetime` object whose date components are equal to the
Alexander Belopolsky43746c32016-08-02 17:49:30 -0400834 given :class:`date` object's, and whose time components
835 are equal to the given :class:`.time` object's. If the *tzinfo*
836 argument is provided, its value is used to set the :attr:`.tzinfo` attribute
837 of the result, otherwise the :attr:`~.time.tzinfo` attribute of the *time* argument
838 is used.
839
840 For any :class:`.datetime` object *d*,
841 ``d == datetime.combine(d.date(), d.time(), d.tzinfo)``. If date is a
Martin Panter16c7cfd2016-04-01 21:48:24 +0000842 :class:`.datetime` object, its time components and :attr:`.tzinfo` attributes
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800843 are ignored.
Georg Brandl116aa622007-08-15 14:28:22 +0000844
Alexander Belopolsky43746c32016-08-02 17:49:30 -0400845 .. versionchanged:: 3.6
846 Added the *tzinfo* argument.
847
Georg Brandl116aa622007-08-15 14:28:22 +0000848
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500849.. classmethod:: datetime.fromisoformat(date_string)
850
851 Return a :class:`datetime` corresponding to a *date_string* in one of the
852 formats emitted by :meth:`date.isoformat` and :meth:`datetime.isoformat`.
853 Specifically, this function supports strings in the format(s)
Christophe Nanteuil92878822018-10-06 00:57:02 +0200854 ``YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]]``,
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500855 where ``*`` can match any single character.
856
857 .. caution::
858
859 This does not support parsing arbitrary ISO 8601 strings - it is only intended
860 as the inverse operation of :meth:`datetime.isoformat`.
861
862 .. versionadded:: 3.7
863
Paul Ganssle88c09372019-04-29 09:22:03 -0400864
865.. classmethod:: datetime.fromisocalendar(year, week, day)
866
867 Return a :class:`datetime` corresponding to the ISO calendar date specified
868 by year, week and day. The non-date components of the datetime are populated
869 with their normal default values. This is the inverse of the function
870 :meth:`datetime.isocalendar`.
871
872 .. versionadded:: 3.8
873
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000874.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000875
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300876 Return a :class:`.datetime` corresponding to *date_string*, parsed according to
Georg Brandl116aa622007-08-15 14:28:22 +0000877 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
878 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
879 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 -0400880 time tuple. For a complete list of formatting directives, see
881 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000882
Georg Brandl116aa622007-08-15 14:28:22 +0000883
Georg Brandl116aa622007-08-15 14:28:22 +0000884
885Class attributes:
886
Georg Brandl116aa622007-08-15 14:28:22 +0000887.. attribute:: datetime.min
888
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300889 The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1,
Georg Brandl116aa622007-08-15 14:28:22 +0000890 tzinfo=None)``.
891
892
893.. attribute:: datetime.max
894
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300895 The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
Georg Brandl116aa622007-08-15 14:28:22 +0000896 59, 999999, tzinfo=None)``.
897
898
899.. attribute:: datetime.resolution
900
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300901 The smallest possible difference between non-equal :class:`.datetime` objects,
Georg Brandl116aa622007-08-15 14:28:22 +0000902 ``timedelta(microseconds=1)``.
903
Georg Brandl116aa622007-08-15 14:28:22 +0000904
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000905Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000906
907.. attribute:: datetime.year
908
909 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
910
911
912.. attribute:: datetime.month
913
914 Between 1 and 12 inclusive.
915
916
917.. attribute:: datetime.day
918
919 Between 1 and the number of days in the given month of the given year.
920
921
922.. attribute:: datetime.hour
923
924 In ``range(24)``.
925
926
927.. attribute:: datetime.minute
928
929 In ``range(60)``.
930
931
932.. attribute:: datetime.second
933
934 In ``range(60)``.
935
936
937.. attribute:: datetime.microsecond
938
939 In ``range(1000000)``.
940
941
942.. attribute:: datetime.tzinfo
943
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300944 The object passed as the *tzinfo* argument to the :class:`.datetime` constructor,
Georg Brandl116aa622007-08-15 14:28:22 +0000945 or ``None`` if none was passed.
946
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000947
Alexander Belopolsky53868aa2016-08-24 18:30:16 -0400948.. attribute:: datetime.fold
949
950 In ``[0, 1]``. Used to disambiguate wall times during a repeated interval. (A
951 repeated interval occurs when clocks are rolled back at the end of daylight saving
952 time or when the UTC offset for the current zone is decreased for political reasons.)
953 The value 0 (1) represents the earlier (later) of the two moments with the same wall
954 time representation.
955
956 .. versionadded:: 3.6
957
Georg Brandl116aa622007-08-15 14:28:22 +0000958Supported operations:
959
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300960+---------------------------------------+--------------------------------+
961| Operation | Result |
962+=======================================+================================+
963| ``datetime2 = datetime1 + timedelta`` | \(1) |
964+---------------------------------------+--------------------------------+
965| ``datetime2 = datetime1 - timedelta`` | \(2) |
966+---------------------------------------+--------------------------------+
967| ``timedelta = datetime1 - datetime2`` | \(3) |
968+---------------------------------------+--------------------------------+
969| ``datetime1 < datetime2`` | Compares :class:`.datetime` to |
970| | :class:`.datetime`. (4) |
971+---------------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000972
973(1)
974 datetime2 is a duration of timedelta removed from datetime1, moving forward in
975 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
Martin Panter16c7cfd2016-04-01 21:48:24 +0000976 result has the same :attr:`~.datetime.tzinfo` attribute as the input datetime, and
Senthil Kumarana6bac952011-07-04 11:28:30 -0700977 datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
978 datetime2.year would be smaller than :const:`MINYEAR` or larger than
979 :const:`MAXYEAR`. Note that no time zone adjustments are done even if the
980 input is an aware object.
Georg Brandl116aa622007-08-15 14:28:22 +0000981
982(2)
983 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
Martin Panter16c7cfd2016-04-01 21:48:24 +0000984 addition, the result has the same :attr:`~.datetime.tzinfo` attribute as the input
Senthil Kumarana6bac952011-07-04 11:28:30 -0700985 datetime, and no time zone adjustments are done even if the input is aware.
Georg Brandl116aa622007-08-15 14:28:22 +0000986
987(3)
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300988 Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if
Georg Brandl116aa622007-08-15 14:28:22 +0000989 both operands are naive, or if both are aware. If one is aware and the other is
990 naive, :exc:`TypeError` is raised.
991
Martin Panter16c7cfd2016-04-01 21:48:24 +0000992 If both are naive, or both are aware and have the same :attr:`~.datetime.tzinfo` attribute,
993 the :attr:`~.datetime.tzinfo` attributes are ignored, and the result is a :class:`timedelta`
Georg Brandl116aa622007-08-15 14:28:22 +0000994 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
995 are done in this case.
996
Martin Panter16c7cfd2016-04-01 21:48:24 +0000997 If both are aware and have different :attr:`~.datetime.tzinfo` attributes, ``a-b`` acts
Senthil Kumarana6bac952011-07-04 11:28:30 -0700998 as if *a* and *b* were first converted to naive UTC datetimes first. The
999 result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
1000 - b.utcoffset())`` except that the implementation never overflows.
Georg Brandl116aa622007-08-15 14:28:22 +00001001
1002(4)
1003 *datetime1* is considered less than *datetime2* when *datetime1* precedes
1004 *datetime2* in time.
1005
Alexander Belopolsky08313822012-06-15 20:19:47 -04001006 If one comparand is naive and the other is aware, :exc:`TypeError`
1007 is raised if an order comparison is attempted. For equality
1008 comparisons, naive instances are never equal to aware instances.
1009
Martin Panter16c7cfd2016-04-01 21:48:24 +00001010 If both comparands are aware, and have the same :attr:`~.datetime.tzinfo` attribute, the
1011 common :attr:`~.datetime.tzinfo` attribute is ignored and the base datetimes are
1012 compared. If both comparands are aware and have different :attr:`~.datetime.tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -07001013 attributes, the comparands are first adjusted by subtracting their UTC
1014 offsets (obtained from ``self.utcoffset()``).
Georg Brandl116aa622007-08-15 14:28:22 +00001015
Alexander Belopolsky08313822012-06-15 20:19:47 -04001016 .. versionchanged:: 3.3
Martin Panter16c7cfd2016-04-01 21:48:24 +00001017 Equality comparisons between naive and aware :class:`.datetime`
Éric Araujob0f08952012-06-24 16:22:09 -04001018 instances don't raise :exc:`TypeError`.
Alexander Belopolsky08313822012-06-15 20:19:47 -04001019
Georg Brandl116aa622007-08-15 14:28:22 +00001020 .. note::
1021
1022 In order to stop comparison from falling back to the default scheme of comparing
1023 object addresses, datetime comparison normally raises :exc:`TypeError` if the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001024 other comparand isn't also a :class:`.datetime` object. However,
Georg Brandl116aa622007-08-15 14:28:22 +00001025 ``NotImplemented`` is returned instead if the other comparand has a
1026 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001027 chance at implementing mixed-type comparison. If not, when a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +00001028 object is compared to an object of a different type, :exc:`TypeError` is raised
1029 unless the comparison is ``==`` or ``!=``. The latter cases return
1030 :const:`False` or :const:`True`, respectively.
1031
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001032:class:`.datetime` objects can be used as dictionary keys. In Boolean contexts,
1033all :class:`.datetime` objects are considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +00001034
1035Instance methods:
1036
Georg Brandl116aa622007-08-15 14:28:22 +00001037.. method:: datetime.date()
1038
1039 Return :class:`date` object with same year, month and day.
1040
1041
1042.. method:: datetime.time()
1043
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001044 Return :class:`.time` object with same hour, minute, second, microsecond and fold.
Martin Panter16c7cfd2016-04-01 21:48:24 +00001045 :attr:`.tzinfo` is ``None``. See also method :meth:`timetz`.
Georg Brandl116aa622007-08-15 14:28:22 +00001046
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001047 .. versionchanged:: 3.6
1048 The fold value is copied to the returned :class:`.time` object.
1049
Georg Brandl116aa622007-08-15 14:28:22 +00001050
1051.. method:: datetime.timetz()
1052
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001053 Return :class:`.time` object with same hour, minute, second, microsecond, fold, and
Senthil Kumarana6bac952011-07-04 11:28:30 -07001054 tzinfo attributes. See also method :meth:`time`.
Georg Brandl116aa622007-08-15 14:28:22 +00001055
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001056 .. versionchanged:: 3.6
1057 The fold value is copied to the returned :class:`.time` object.
Georg Brandl116aa622007-08-15 14:28:22 +00001058
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001059
1060.. method:: datetime.replace(year=self.year, month=self.month, day=self.day, \
1061 hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, \
1062 tzinfo=self.tzinfo, * fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001063
Senthil Kumarana6bac952011-07-04 11:28:30 -07001064 Return a datetime with the same attributes, except for those attributes given
1065 new values by whichever keyword arguments are specified. Note that
1066 ``tzinfo=None`` can be specified to create a naive datetime from an aware
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001067 datetime with no conversion of date and time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001068
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001069 .. versionadded:: 3.6
1070 Added the ``fold`` argument.
1071
Georg Brandl116aa622007-08-15 14:28:22 +00001072
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001073.. method:: datetime.astimezone(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001074
Martin Panter16c7cfd2016-04-01 21:48:24 +00001075 Return a :class:`.datetime` object with new :attr:`.tzinfo` attribute *tz*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001076 adjusting the date and time data so the result is the same UTC time as
Senthil Kumarana6bac952011-07-04 11:28:30 -07001077 *self*, but in *tz*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00001078
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001079 If provided, *tz* must be an instance of a :class:`tzinfo` subclass, and its
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001080 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. If *self*
Alexander Belopolsky877b2322018-06-10 17:02:58 -04001081 is naive, it is presumed to represent time in the system timezone.
Georg Brandl116aa622007-08-15 14:28:22 +00001082
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001083 If called without arguments (or with ``tz=None``) the system local
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001084 timezone is assumed for the target timezone. The ``.tzinfo`` attribute of the converted
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04001085 datetime instance will be set to an instance of :class:`timezone`
1086 with the zone name and offset obtained from the OS.
1087
Georg Brandl116aa622007-08-15 14:28:22 +00001088 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001089 adjustment of date or time data is performed. Else the result is local
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001090 time in the timezone *tz*, representing the same UTC time as *self*: after
1091 ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will have
1092 the same date and time data as ``dt - dt.utcoffset()``.
Georg Brandl116aa622007-08-15 14:28:22 +00001093
1094 If you merely want to attach a time zone object *tz* to a datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001095 adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you
Georg Brandl116aa622007-08-15 14:28:22 +00001096 merely want to remove the time zone object from an aware datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001097 conversion of date and time data, use ``dt.replace(tzinfo=None)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001098
1099 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
1100 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
1101 Ignoring error cases, :meth:`astimezone` acts like::
1102
1103 def astimezone(self, tz):
1104 if self.tzinfo is tz:
1105 return self
1106 # Convert self to UTC, and attach the new time zone object.
1107 utc = (self - self.utcoffset()).replace(tzinfo=tz)
1108 # Convert from UTC to tz's local time.
1109 return tz.fromutc(utc)
1110
Georg Brandlee0be402012-06-26 09:14:40 +02001111 .. versionchanged:: 3.3
1112 *tz* now can be omitted.
1113
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001114 .. versionchanged:: 3.6
1115 The :meth:`astimezone` method can now be called on naive instances that
1116 are presumed to represent system local time.
1117
Georg Brandl116aa622007-08-15 14:28:22 +00001118
1119.. method:: datetime.utcoffset()
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.utcoffset(self)``, and raises an exception if the latter doesn't
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001123 return ``None`` or a :class:`timedelta` object with magnitude less than one day.
1124
1125 .. versionchanged:: 3.7
1126 The UTC offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001127
1128
1129.. method:: datetime.dst()
1130
Martin Panter16c7cfd2016-04-01 21:48:24 +00001131 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001132 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001133 ``None`` or a :class:`timedelta` object with magnitude less than one day.
1134
1135 .. versionchanged:: 3.7
1136 The DST offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001137
1138
1139.. method:: datetime.tzname()
1140
Martin Panter16c7cfd2016-04-01 21:48:24 +00001141 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001142 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
1143 ``None`` or a string object,
1144
1145
1146.. method:: datetime.timetuple()
1147
1148 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
1149 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
Alexander Belopolsky64912482010-06-08 18:59:20 +00001150 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
1151 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
1152 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
Martin Panter16c7cfd2016-04-01 21:48:24 +00001153 of the result is set according to the :meth:`dst` method: :attr:`.tzinfo` is
Georg Brandl682d7e02010-10-06 10:26:05 +00001154 ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
Alexander Belopolsky64912482010-06-08 18:59:20 +00001155 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
Alexander Belopolskyda62f2f2010-06-09 17:11:01 +00001156 else :attr:`tm_isdst` is set to ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +00001157
1158
1159.. method:: datetime.utctimetuple()
1160
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001161 If :class:`.datetime` instance *d* is naive, this is the same as
Georg Brandl116aa622007-08-15 14:28:22 +00001162 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
1163 ``d.dst()`` returns. DST is never in effect for a UTC time.
1164
1165 If *d* is aware, *d* is normalized to UTC time, by subtracting
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00001166 ``d.utcoffset()``, and a :class:`time.struct_time` for the
1167 normalized time is returned. :attr:`tm_isdst` is forced to 0. Note
1168 that an :exc:`OverflowError` may be raised if *d*.year was
1169 ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
Georg Brandl116aa622007-08-15 14:28:22 +00001170 boundary.
1171
1172
1173.. method:: datetime.toordinal()
1174
1175 Return the proleptic Gregorian ordinal of the date. The same as
1176 ``self.date().toordinal()``.
1177
Alexander Belopolskya4415142012-06-08 12:33:09 -04001178.. method:: datetime.timestamp()
1179
Martin Panter16c7cfd2016-04-01 21:48:24 +00001180 Return POSIX timestamp corresponding to the :class:`.datetime`
Alexander Belopolskya4415142012-06-08 12:33:09 -04001181 instance. The return value is a :class:`float` similar to that
1182 returned by :func:`time.time`.
1183
Martin Panter16c7cfd2016-04-01 21:48:24 +00001184 Naive :class:`.datetime` instances are assumed to represent local
Alexander Belopolskya4415142012-06-08 12:33:09 -04001185 time and this method relies on the platform C :c:func:`mktime`
Martin Panter16c7cfd2016-04-01 21:48:24 +00001186 function to perform the conversion. Since :class:`.datetime`
Alexander Belopolskya4415142012-06-08 12:33:09 -04001187 supports wider range of values than :c:func:`mktime` on many
1188 platforms, this method may raise :exc:`OverflowError` for times far
1189 in the past or far in the future.
1190
Martin Panter16c7cfd2016-04-01 21:48:24 +00001191 For aware :class:`.datetime` instances, the return value is computed
Alexander Belopolskya4415142012-06-08 12:33:09 -04001192 as::
1193
1194 (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
1195
1196 .. versionadded:: 3.3
1197
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001198 .. versionchanged:: 3.6
1199 The :meth:`timestamp` method uses the :attr:`.fold` attribute to
1200 disambiguate the times during a repeated interval.
1201
Alexander Belopolskya4415142012-06-08 12:33:09 -04001202 .. note::
1203
1204 There is no method to obtain the POSIX timestamp directly from a
Martin Panter16c7cfd2016-04-01 21:48:24 +00001205 naive :class:`.datetime` instance representing UTC time. If your
Alexander Belopolskya4415142012-06-08 12:33:09 -04001206 application uses this convention and your system timezone is not
1207 set to UTC, you can obtain the POSIX timestamp by supplying
1208 ``tzinfo=timezone.utc``::
1209
1210 timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
1211
1212 or by calculating the timestamp directly::
1213
1214 timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001215
1216.. method:: datetime.weekday()
1217
1218 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
1219 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
1220
1221
1222.. method:: datetime.isoweekday()
1223
1224 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
1225 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
1226 :meth:`isocalendar`.
1227
1228
1229.. method:: datetime.isocalendar()
1230
1231 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
1232 ``self.date().isocalendar()``.
1233
1234
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001235.. method:: datetime.isoformat(sep='T', timespec='auto')
Georg Brandl116aa622007-08-15 14:28:22 +00001236
1237 Return a string representing the date and time in ISO 8601 format,
Christophe Nanteuil92878822018-10-06 00:57:02 +02001238 YYYY-MM-DDTHH:MM:SS.ffffff or, if :attr:`microsecond` is 0,
Georg Brandl116aa622007-08-15 14:28:22 +00001239 YYYY-MM-DDTHH:MM:SS
1240
Christophe Nanteuil92878822018-10-06 00:57:02 +02001241 If :meth:`utcoffset` does not return ``None``, a string is
1242 appended, giving the UTC offset:
1243 YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]] or, if :attr:`microsecond`
1244 is 0 YYYY-MM-DDTHH:MM:SS+HH:MM[:SS[.ffffff]].
Georg Brandl116aa622007-08-15 14:28:22 +00001245
1246 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +00001247 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +00001248
1249 >>> from datetime import tzinfo, timedelta, datetime
1250 >>> class TZ(tzinfo):
1251 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1252 ...
1253 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1254 '2002-12-25 00:00:00-06:39'
1255
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001256 The optional argument *timespec* specifies the number of additional
1257 components of the time to include (the default is ``'auto'``).
1258 It can be one of the following:
1259
1260 - ``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0,
1261 same as ``'microseconds'`` otherwise.
1262 - ``'hours'``: Include the :attr:`hour` in the two-digit HH format.
1263 - ``'minutes'``: Include :attr:`hour` and :attr:`minute` in HH:MM format.
1264 - ``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second`
1265 in HH:MM:SS format.
1266 - ``'milliseconds'``: Include full time, but truncate fractional second
1267 part to milliseconds. HH:MM:SS.sss format.
Christophe Nanteuil92878822018-10-06 00:57:02 +02001268 - ``'microseconds'``: Include full time in HH:MM:SS.ffffff format.
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001269
1270 .. note::
1271
1272 Excluded time components are truncated, not rounded.
1273
1274 :exc:`ValueError` will be raised on an invalid *timespec* argument.
1275
1276
1277 >>> from datetime import datetime
Marco Buttu909a6f62017-03-18 17:59:33 +01001278 >>> datetime.now().isoformat(timespec='minutes') # doctest: +SKIP
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001279 '2002-12-25T00:00'
1280 >>> dt = datetime(2015, 1, 1, 12, 30, 59, 0)
1281 >>> dt.isoformat(timespec='microseconds')
1282 '2015-01-01T12:30:59.000000'
1283
1284 .. versionadded:: 3.6
1285 Added the *timespec* argument.
1286
Georg Brandl116aa622007-08-15 14:28:22 +00001287
1288.. method:: datetime.__str__()
1289
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001290 For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to
Georg Brandl116aa622007-08-15 14:28:22 +00001291 ``d.isoformat(' ')``.
1292
1293
1294.. method:: datetime.ctime()
1295
1296 Return a string representing the date and time, for example ``datetime(2002, 12,
1297 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1298 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
Georg Brandl60203b42010-10-06 10:11:56 +00001299 native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +00001300 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1301
1302
1303.. method:: datetime.strftime(format)
1304
1305 Return a string representing the date and time, controlled by an explicit format
David Wolever569a5fa2013-08-12 16:56:02 -04001306 string. For a complete list of formatting directives, see
1307 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001308
Georg Brandl116aa622007-08-15 14:28:22 +00001309
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001310.. method:: datetime.__format__(format)
1311
Martin Panterd5db1472016-02-08 01:34:09 +00001312 Same as :meth:`.datetime.strftime`. This makes it possible to specify a format
Martin Panterbc1ee462016-02-13 00:41:37 +00001313 string for a :class:`.datetime` object in :ref:`formatted string
1314 literals <f-strings>` and when using :meth:`str.format`. For a
David Wolever569a5fa2013-08-12 16:56:02 -04001315 complete list of formatting directives, see
1316 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001317
1318
Christian Heimesfe337bf2008-03-23 21:54:12 +00001319Examples of working with datetime objects:
1320
1321.. doctest::
1322
Christian Heimes895627f2007-12-08 17:28:33 +00001323 >>> from datetime import datetime, date, time
1324 >>> # Using datetime.combine()
1325 >>> d = date(2005, 7, 14)
1326 >>> t = time(12, 30)
1327 >>> datetime.combine(d, t)
1328 datetime.datetime(2005, 7, 14, 12, 30)
1329 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001330 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001331 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001332 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001333 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1334 >>> # Using datetime.strptime()
1335 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1336 >>> dt
1337 datetime.datetime(2006, 11, 21, 16, 30)
1338 >>> # Using datetime.timetuple() to get tuple of all attributes
1339 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001340 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001341 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001342 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001343 2006 # year
1344 11 # month
1345 21 # day
1346 16 # hour
1347 30 # minute
1348 0 # second
1349 1 # weekday (0 = Monday)
1350 325 # number of days since 1st January
1351 -1 # dst - method tzinfo.dst() returned None
1352 >>> # Date in ISO format
1353 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001354 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001355 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001356 ...
1357 2006 # ISO year
1358 47 # ISO week
1359 2 # ISO weekday
1360 >>> # Formatting datetime
1361 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1362 'Tuesday, 21. November 2006 04:30PM'
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001363 >>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
1364 'The day is 21, the month is November, the time is 04:30PM.'
Christian Heimes895627f2007-12-08 17:28:33 +00001365
Christian Heimesfe337bf2008-03-23 21:54:12 +00001366Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001367
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001368 >>> from datetime import timedelta, datetime, tzinfo, timezone
1369 >>> class KabulTz(tzinfo):
1370 ... # Kabul used +4 until 1945, when they moved to +4:30
1371 ... UTC_MOVE_DATE = datetime(1944, 12, 31, 20, tzinfo=timezone.utc)
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001372 ... def utcoffset(self, dt):
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001373 ... if dt.year < 1945:
1374 ... return timedelta(hours=4)
1375 ... elif (1945, 1, 1, 0, 0) <= dt.timetuple()[:5] < (1945, 1, 1, 0, 30):
1376 ... # If dt falls in the imaginary range, use fold to decide how
1377 ... # to resolve. See PEP495
1378 ... return timedelta(hours=4, minutes=(30 if dt.fold else 0))
Christian Heimes895627f2007-12-08 17:28:33 +00001379 ... else:
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001380 ... return timedelta(hours=4, minutes=30)
Georg Brandl48310cd2009-01-03 21:18:54 +00001381 ...
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001382 ... def fromutc(self, dt):
1383 ... # A custom implementation is required for fromutc as
1384 ... # the input to this function is a datetime with utc values
1385 ... # but with a tzinfo set to self
1386 ... # See datetime.astimezone or fromtimestamp
1387 ...
1388 ... # Follow same validations as in datetime.tzinfo
1389 ... if not isinstance(dt, datetime):
1390 ... raise TypeError("fromutc() requires a datetime argument")
1391 ... if dt.tzinfo is not self:
1392 ... raise ValueError("dt.tzinfo is not self")
1393 ...
1394 ... if dt.replace(tzinfo=timezone.utc) >= self.UTC_MOVE_DATE:
1395 ... return dt + timedelta(hours=4, minutes=30)
Christian Heimes895627f2007-12-08 17:28:33 +00001396 ... else:
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001397 ... return dt + timedelta(hours=4)
Georg Brandl48310cd2009-01-03 21:18:54 +00001398 ...
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001399 ... def dst(self, dt):
1400 ... return timedelta(0)
1401 ...
1402 ... def tzname(self, dt):
1403 ... if dt >= self.UTC_MOVE_DATE:
1404 ... return "+04:30"
1405 ... else:
1406 ... return "+04"
1407 ...
1408 ... def __repr__(self):
1409 ... return f"{self.__class__.__name__}()"
1410 ...
1411 >>> tz1 = KabulTz()
1412 >>> # Datetime before the change
1413 >>> dt1 = datetime(1900, 11, 21, 16, 30, tzinfo=tz1)
1414 >>> print(dt1.utcoffset())
1415 4:00:00
1416 >>> # Datetime after the change
1417 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=tz1)
1418 >>> print(dt2.utcoffset())
1419 4:30:00
Christian Heimes895627f2007-12-08 17:28:33 +00001420 >>> # Convert datetime to another time zone
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001421 >>> dt3 = dt2.astimezone(timezone.utc)
1422 >>> dt3
1423 datetime.datetime(2006, 6, 14, 8, 30, tzinfo=datetime.timezone.utc)
1424 >>> dt2
1425 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=KabulTz())
Christian Heimes895627f2007-12-08 17:28:33 +00001426 >>> dt2.utctimetuple() == dt3.utctimetuple()
1427 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001428
Christian Heimes895627f2007-12-08 17:28:33 +00001429
Georg Brandl116aa622007-08-15 14:28:22 +00001430
1431.. _datetime-time:
1432
Serhiy Storchakaee1b01a2016-12-02 23:13:53 +02001433:class:`.time` Objects
1434----------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001435
1436A time object represents a (local) time of day, independent of any particular
1437day, and subject to adjustment via a :class:`tzinfo` object.
1438
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001439.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001440
1441 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001442 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001443 following ranges:
1444
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001445 * ``0 <= hour < 24``,
1446 * ``0 <= minute < 60``,
1447 * ``0 <= second < 60``,
1448 * ``0 <= microsecond < 1000000``,
1449 * ``fold in [0, 1]``.
Georg Brandl116aa622007-08-15 14:28:22 +00001450
1451 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1452 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1453
1454Class attributes:
1455
1456
1457.. attribute:: time.min
1458
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001459 The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001460
1461
1462.. attribute:: time.max
1463
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001464 The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001465
1466
1467.. attribute:: time.resolution
1468
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001469 The smallest possible difference between non-equal :class:`.time` objects,
1470 ``timedelta(microseconds=1)``, although note that arithmetic on
1471 :class:`.time` objects is not supported.
Georg Brandl116aa622007-08-15 14:28:22 +00001472
Georg Brandl116aa622007-08-15 14:28:22 +00001473
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001474Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001475
1476.. attribute:: time.hour
1477
1478 In ``range(24)``.
1479
1480
1481.. attribute:: time.minute
1482
1483 In ``range(60)``.
1484
1485
1486.. attribute:: time.second
1487
1488 In ``range(60)``.
1489
1490
1491.. attribute:: time.microsecond
1492
1493 In ``range(1000000)``.
1494
1495
1496.. attribute:: time.tzinfo
1497
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001498 The object passed as the tzinfo argument to the :class:`.time` constructor, or
Georg Brandl116aa622007-08-15 14:28:22 +00001499 ``None`` if none was passed.
1500
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001501
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001502.. attribute:: time.fold
1503
1504 In ``[0, 1]``. Used to disambiguate wall times during a repeated interval. (A
1505 repeated interval occurs when clocks are rolled back at the end of daylight saving
1506 time or when the UTC offset for the current zone is decreased for political reasons.)
1507 The value 0 (1) represents the earlier (later) of the two moments with the same wall
1508 time representation.
1509
1510 .. versionadded:: 3.6
1511
1512
Georg Brandl116aa622007-08-15 14:28:22 +00001513Supported operations:
1514
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001515* comparison of :class:`.time` to :class:`.time`, where *a* is considered less
Georg Brandl116aa622007-08-15 14:28:22 +00001516 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
Alexander Belopolsky08313822012-06-15 20:19:47 -04001517 is aware, :exc:`TypeError` is raised if an order comparison is attempted. For equality
1518 comparisons, naive instances are never equal to aware instances.
1519
1520 If both comparands are aware, and have
Martin Panter16c7cfd2016-04-01 21:48:24 +00001521 the same :attr:`~time.tzinfo` attribute, the common :attr:`~time.tzinfo` attribute is
Senthil Kumarana6bac952011-07-04 11:28:30 -07001522 ignored and the base times are compared. If both comparands are aware and
Martin Panter16c7cfd2016-04-01 21:48:24 +00001523 have different :attr:`~time.tzinfo` attributes, the comparands are first adjusted by
Senthil Kumarana6bac952011-07-04 11:28:30 -07001524 subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
1525 to stop mixed-type comparisons from falling back to the default comparison by
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001526 object address, when a :class:`.time` object is compared to an object of a
Senthil Kumaran3aac1792011-07-04 11:43:51 -07001527 different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
Senthil Kumarana6bac952011-07-04 11:28:30 -07001528 ``!=``. The latter cases return :const:`False` or :const:`True`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +00001529
Alexander Belopolsky08313822012-06-15 20:19:47 -04001530 .. versionchanged:: 3.3
Serhiy Storchakaee1b01a2016-12-02 23:13:53 +02001531 Equality comparisons between naive and aware :class:`~datetime.time` instances
Éric Araujob0f08952012-06-24 16:22:09 -04001532 don't raise :exc:`TypeError`.
Alexander Belopolsky08313822012-06-15 20:19:47 -04001533
Georg Brandl116aa622007-08-15 14:28:22 +00001534* hash, use as dict key
1535
1536* efficient pickling
1537
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05001538In boolean contexts, a :class:`.time` object is always considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +00001539
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05001540.. versionchanged:: 3.5
1541 Before Python 3.5, a :class:`.time` object was considered to be false if it
1542 represented midnight in UTC. This behavior was considered obscure and
1543 error-prone and has been removed in Python 3.5. See :issue:`13936` for full
1544 details.
Georg Brandl116aa622007-08-15 14:28:22 +00001545
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001546
1547Other constructor:
1548
1549.. classmethod:: time.fromisoformat(time_string)
1550
1551 Return a :class:`time` corresponding to a *time_string* in one of the
1552 formats emitted by :meth:`time.isoformat`. Specifically, this function supports
Christophe Nanteuil92878822018-10-06 00:57:02 +02001553 strings in the format(s) ``HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]``.
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001554
1555 .. caution::
1556
1557 This does not support parsing arbitrary ISO 8601 strings - it is only intended
1558 as the inverse operation of :meth:`time.isoformat`.
1559
1560 .. versionadded:: 3.7
1561
1562
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001563Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001564
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001565.. method:: time.replace(hour=self.hour, minute=self.minute, second=self.second, \
1566 microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001567
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001568 Return a :class:`.time` with the same value, except for those attributes given
Senthil Kumarana6bac952011-07-04 11:28:30 -07001569 new values by whichever keyword arguments are specified. Note that
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001570 ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
1571 aware :class:`.time`, without conversion of the time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001572
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001573 .. versionadded:: 3.6
1574 Added the ``fold`` argument.
1575
Georg Brandl116aa622007-08-15 14:28:22 +00001576
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001577.. method:: time.isoformat(timespec='auto')
Georg Brandl116aa622007-08-15 14:28:22 +00001578
Christophe Nanteuil92878822018-10-06 00:57:02 +02001579 Return a string representing the time in ISO 8601 format, HH:MM:SS.ffffff or, if
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001580 :attr:`microsecond` is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
Christophe Nanteuil92878822018-10-06 00:57:02 +02001581 string is appended, giving the UTC offset: HH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]
1582 or, if self.microsecond is 0, HH:MM:SS+HH:MM[:SS[.ffffff]].
Georg Brandl116aa622007-08-15 14:28:22 +00001583
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001584 The optional argument *timespec* specifies the number of additional
1585 components of the time to include (the default is ``'auto'``).
1586 It can be one of the following:
1587
1588 - ``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0,
1589 same as ``'microseconds'`` otherwise.
1590 - ``'hours'``: Include the :attr:`hour` in the two-digit HH format.
1591 - ``'minutes'``: Include :attr:`hour` and :attr:`minute` in HH:MM format.
1592 - ``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second`
1593 in HH:MM:SS format.
1594 - ``'milliseconds'``: Include full time, but truncate fractional second
1595 part to milliseconds. HH:MM:SS.sss format.
Christophe Nanteuil92878822018-10-06 00:57:02 +02001596 - ``'microseconds'``: Include full time in HH:MM:SS.ffffff format.
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001597
1598 .. note::
1599
1600 Excluded time components are truncated, not rounded.
1601
1602 :exc:`ValueError` will be raised on an invalid *timespec* argument.
1603
1604
1605 >>> from datetime import time
Berker Peksag94f89a62016-06-04 21:36:53 -07001606 >>> time(hour=12, minute=34, second=56, microsecond=123456).isoformat(timespec='minutes')
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001607 '12:34'
Berker Peksag94f89a62016-06-04 21:36:53 -07001608 >>> dt = time(hour=12, minute=34, second=56, microsecond=0)
Alexander Belopolskya2998a62016-03-06 14:58:43 -05001609 >>> dt.isoformat(timespec='microseconds')
1610 '12:34:56.000000'
1611 >>> dt.isoformat(timespec='auto')
1612 '12:34:56'
1613
1614 .. versionadded:: 3.6
1615 Added the *timespec* argument.
1616
Georg Brandl116aa622007-08-15 14:28:22 +00001617
1618.. method:: time.__str__()
1619
1620 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1621
1622
1623.. method:: time.strftime(format)
1624
David Wolever569a5fa2013-08-12 16:56:02 -04001625 Return a string representing the time, controlled by an explicit format
1626 string. For a complete list of formatting directives, see
David Woleverbbf4a462013-08-12 17:15:36 -04001627 :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001628
1629
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001630.. method:: time.__format__(format)
1631
Martin Panterd5db1472016-02-08 01:34:09 +00001632 Same as :meth:`.time.strftime`. This makes it possible to specify a format string
Martin Panterbc1ee462016-02-13 00:41:37 +00001633 for a :class:`.time` object in :ref:`formatted string
1634 literals <f-strings>` and when using :meth:`str.format`. For a
David Wolever569a5fa2013-08-12 16:56:02 -04001635 complete list of formatting directives, see
1636 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001637
1638
Georg Brandl116aa622007-08-15 14:28:22 +00001639.. method:: time.utcoffset()
1640
Martin Panter16c7cfd2016-04-01 21:48:24 +00001641 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001642 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001643 return ``None`` or a :class:`timedelta` object with magnitude less than one day.
1644
1645 .. versionchanged:: 3.7
1646 The UTC offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001647
1648
1649.. method:: time.dst()
1650
Martin Panter16c7cfd2016-04-01 21:48:24 +00001651 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001652 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001653 ``None``, or a :class:`timedelta` object with magnitude less than one day.
Georg Brandl116aa622007-08-15 14:28:22 +00001654
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001655 .. versionchanged:: 3.7
1656 The DST offset is not restricted to a whole number of minutes.
Georg Brandl116aa622007-08-15 14:28:22 +00001657
1658.. method:: time.tzname()
1659
Martin Panter16c7cfd2016-04-01 21:48:24 +00001660 If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
Georg Brandl116aa622007-08-15 14:28:22 +00001661 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1662 return ``None`` or a string object.
1663
Christian Heimesfe337bf2008-03-23 21:54:12 +00001664Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001665
Xiang Zhang6721c7c2016-12-27 12:23:59 +08001666 >>> from datetime import time, tzinfo, timedelta
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001667 >>> class TZ1(tzinfo):
Christian Heimes895627f2007-12-08 17:28:33 +00001668 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001669 ... return timedelta(hours=1)
1670 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001671 ... return timedelta(0)
1672 ... def tzname(self,dt):
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001673 ... return "+01:00"
1674 ... def __repr__(self):
1675 ... return f"{self.__class__.__name__}()"
Christian Heimes895627f2007-12-08 17:28:33 +00001676 ...
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001677 >>> t = time(12, 10, 30, tzinfo=TZ1())
1678 >>> t
1679 datetime.time(12, 10, 30, tzinfo=TZ1())
Christian Heimes895627f2007-12-08 17:28:33 +00001680 >>> t.isoformat()
1681 '12:10:30+01:00'
1682 >>> t.dst()
1683 datetime.timedelta(0)
1684 >>> t.tzname()
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001685 '+01:00'
Christian Heimes895627f2007-12-08 17:28:33 +00001686 >>> t.strftime("%H:%M:%S %Z")
Mario Corcherof0b5ae42019-06-04 16:18:11 +01001687 '12:10:30 +01:00'
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001688 >>> 'The {} is {:%H:%M}.'.format("time", t)
1689 'The time is 12:10.'
Christian Heimes895627f2007-12-08 17:28:33 +00001690
Georg Brandl116aa622007-08-15 14:28:22 +00001691
1692.. _datetime-tzinfo:
1693
1694:class:`tzinfo` Objects
1695-----------------------
1696
Martin Panter16c7cfd2016-04-01 21:48:24 +00001697.. class:: tzinfo()
Georg Brandl116aa622007-08-15 14:28:22 +00001698
Martin Panter16c7cfd2016-04-01 21:48:24 +00001699 This is an abstract base class, meaning that this class should not be
1700 instantiated directly. You need to derive a concrete subclass, and (at least)
1701 supply implementations of the standard :class:`tzinfo` methods needed by the
1702 :class:`.datetime` methods you use. The :mod:`datetime` module supplies
1703 a simple concrete subclass of :class:`tzinfo`, :class:`timezone`, which can represent
1704 timezones with fixed offset from UTC such as UTC itself or North American EST and
1705 EDT.
Georg Brandl116aa622007-08-15 14:28:22 +00001706
Martin Panter16c7cfd2016-04-01 21:48:24 +00001707 An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1708 constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
1709 view their attributes as being in local time, and the :class:`tzinfo` object
1710 supports methods revealing offset of local time from UTC, the name of the time
1711 zone, and DST offset, all relative to a date or time object passed to them.
Georg Brandl116aa622007-08-15 14:28:22 +00001712
Martin Panter16c7cfd2016-04-01 21:48:24 +00001713 Special requirement for pickling: A :class:`tzinfo` subclass must have an
1714 :meth:`__init__` method that can be called with no arguments, else it can be
1715 pickled but possibly not unpickled again. This is a technical requirement that
1716 may be relaxed in the future.
1717
1718 A concrete subclass of :class:`tzinfo` may need to implement the following
1719 methods. Exactly which methods are needed depends on the uses made of aware
1720 :mod:`datetime` objects. If in doubt, simply implement all of them.
Georg Brandl116aa622007-08-15 14:28:22 +00001721
1722
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001723.. method:: tzinfo.utcoffset(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001724
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001725 Return offset of local time from UTC, as a :class:`timedelta` object that is
1726 positive east of UTC. If local time is
Georg Brandl116aa622007-08-15 14:28:22 +00001727 west of UTC, this should be negative. Note that this is intended to be the
1728 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1729 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1730 the UTC offset isn't known, return ``None``. Else the value returned must be a
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001731 :class:`timedelta` object strictly between ``-timedelta(hours=24)`` and
1732 ``timedelta(hours=24)`` (the magnitude of the offset must be less
Georg Brandl116aa622007-08-15 14:28:22 +00001733 than one day). Most implementations of :meth:`utcoffset` will probably look
1734 like one of these two::
1735
1736 return CONSTANT # fixed-offset class
1737 return CONSTANT + self.dst(dt) # daylight-aware class
1738
1739 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1740 ``None`` either.
1741
1742 The default implementation of :meth:`utcoffset` raises
1743 :exc:`NotImplementedError`.
1744
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001745 .. versionchanged:: 3.7
1746 The UTC offset is not restricted to a whole number of minutes.
1747
Georg Brandl116aa622007-08-15 14:28:22 +00001748
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001749.. method:: tzinfo.dst(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001750
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001751 Return the daylight saving time (DST) adjustment, as a :class:`timedelta`
1752 object or
Georg Brandl116aa622007-08-15 14:28:22 +00001753 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1754 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1755 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1756 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1757 no need to consult :meth:`dst` unless you're interested in obtaining DST info
Martin Panter16c7cfd2016-04-01 21:48:24 +00001758 separately. For example, :meth:`datetime.timetuple` calls its :attr:`~.datetime.tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -07001759 attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
1760 should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
1761 DST changes when crossing time zones.
Georg Brandl116aa622007-08-15 14:28:22 +00001762
1763 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1764 daylight times must be consistent in this sense:
1765
1766 ``tz.utcoffset(dt) - tz.dst(dt)``
1767
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001768 must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo ==
Georg Brandl116aa622007-08-15 14:28:22 +00001769 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1770 zone's "standard offset", which should not depend on the date or the time, but
1771 only on geographic location. The implementation of :meth:`datetime.astimezone`
1772 relies on this, but cannot detect violations; it's the programmer's
1773 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1774 this, it may be able to override the default implementation of
1775 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1776
1777 Most implementations of :meth:`dst` will probably look like one of these two::
1778
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001779 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001780 # a fixed-offset class: doesn't account for DST
1781 return timedelta(0)
1782
1783 or ::
1784
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001785 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001786 # Code to set dston and dstoff to the time zone's DST
1787 # transition times based on the input dt.year, and expressed
1788 # in standard local time. Then
1789
1790 if dston <= dt.replace(tzinfo=None) < dstoff:
1791 return timedelta(hours=1)
1792 else:
1793 return timedelta(0)
1794
1795 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1796
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001797 .. versionchanged:: 3.7
1798 The DST offset is not restricted to a whole number of minutes.
1799
Georg Brandl116aa622007-08-15 14:28:22 +00001800
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001801.. method:: tzinfo.tzname(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001802
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001803 Return the time zone name corresponding to the :class:`.datetime` object *dt*, as
Georg Brandl116aa622007-08-15 14:28:22 +00001804 a string. Nothing about string names is defined by the :mod:`datetime` module,
1805 and there's no requirement that it mean anything in particular. For example,
1806 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1807 valid replies. Return ``None`` if a string name isn't known. Note that this is
1808 a method rather than a fixed string primarily because some :class:`tzinfo`
1809 subclasses will wish to return different names depending on the specific value
1810 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1811 daylight time.
1812
1813 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1814
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001815
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001816These methods are called by a :class:`.datetime` or :class:`.time` object, in
1817response to their methods of the same names. A :class:`.datetime` object passes
1818itself as the argument, and a :class:`.time` object passes ``None`` as the
Georg Brandl116aa622007-08-15 14:28:22 +00001819argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001820accept a *dt* argument of ``None``, or of class :class:`.datetime`.
Georg Brandl116aa622007-08-15 14:28:22 +00001821
1822When ``None`` is passed, it's up to the class designer to decide the best
1823response. For example, returning ``None`` is appropriate if the class wishes to
1824say that time objects don't participate in the :class:`tzinfo` protocols. It
1825may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1826there is no other convention for discovering the standard offset.
1827
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001828When a :class:`.datetime` object is passed in response to a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +00001829method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1830rely on this, unless user code calls :class:`tzinfo` methods directly. The
1831intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1832time, and not need worry about objects in other timezones.
1833
1834There is one more :class:`tzinfo` method that a subclass may wish to override:
1835
1836
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001837.. method:: tzinfo.fromutc(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001838
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001839 This is called from the default :class:`datetime.astimezone()`
1840 implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s
1841 date and time data are to be viewed as expressing a UTC time. The purpose
1842 of :meth:`fromutc` is to adjust the date and time data, returning an
Senthil Kumarana6bac952011-07-04 11:28:30 -07001843 equivalent datetime in *self*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00001844
1845 Most :class:`tzinfo` subclasses should be able to inherit the default
1846 :meth:`fromutc` implementation without problems. It's strong enough to handle
1847 fixed-offset time zones, and time zones accounting for both standard and
1848 daylight time, and the latter even if the DST transition times differ in
1849 different years. An example of a time zone the default :meth:`fromutc`
1850 implementation may not handle correctly in all cases is one where the standard
1851 offset (from UTC) depends on the specific date and time passed, which can happen
1852 for political reasons. The default implementations of :meth:`astimezone` and
1853 :meth:`fromutc` may not produce the result you want if the result is one of the
1854 hours straddling the moment the standard offset changes.
1855
1856 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1857 like::
1858
1859 def fromutc(self, dt):
1860 # raise ValueError error if dt.tzinfo is not self
1861 dtoff = dt.utcoffset()
1862 dtdst = dt.dst()
1863 # raise ValueError if dtoff is None or dtdst is None
1864 delta = dtoff - dtdst # this is self's standard offset
1865 if delta:
1866 dt += delta # convert to standard local time
1867 dtdst = dt.dst()
1868 # raise ValueError if dtdst is None
1869 if dtdst:
1870 return dt + dtdst
1871 else:
1872 return dt
1873
Marco Buttu909a6f62017-03-18 17:59:33 +01001874In the following :download:`tzinfo_examples.py
1875<../includes/tzinfo_examples.py>` file there are some examples of
1876:class:`tzinfo` classes:
Georg Brandl116aa622007-08-15 14:28:22 +00001877
Marco Buttu909a6f62017-03-18 17:59:33 +01001878.. literalinclude:: ../includes/tzinfo_examples.py
Georg Brandl116aa622007-08-15 14:28:22 +00001879
Georg Brandl116aa622007-08-15 14:28:22 +00001880Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1881subclass accounting for both standard and daylight time, at the DST transition
1882points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00001883minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
18841:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001885
1886 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1887 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1888 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1889
1890 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1891
1892 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1893
1894When DST starts (the "start" line), the local wall clock leaps from 1:59 to
18953:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1896``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001897begins. For example, at the Spring forward transition of 2016, we get
1898
Marco Buttu909a6f62017-03-18 17:59:33 +01001899 >>> from datetime import datetime, timezone
1900 >>> from tzinfo_examples import HOUR, Eastern
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001901 >>> u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc)
1902 >>> for i in range(4):
1903 ... u = u0 + i*HOUR
1904 ... t = u.astimezone(Eastern)
1905 ... print(u.time(), 'UTC =', t.time(), t.tzname())
1906 ...
1907 05:00:00 UTC = 00:00:00 EST
1908 06:00:00 UTC = 01:00:00 EST
1909 07:00:00 UTC = 03:00:00 EDT
1910 08:00:00 UTC = 04:00:00 EDT
1911
Georg Brandl116aa622007-08-15 14:28:22 +00001912
1913When DST ends (the "end" line), there's a potentially worse problem: there's an
1914hour that can't be spelled unambiguously in local wall time: the last hour of
1915daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1916daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1917to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1918:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1919hours into the same local hour then. In the Eastern example, UTC times of the
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001920form 5:MM and 6:MM both map to 1:MM when converted to Eastern, but earlier times
1921have the :attr:`~datetime.fold` attribute set to 0 and the later times have it set to 1.
1922For example, at the Fall back transition of 2016, we get
Georg Brandl116aa622007-08-15 14:28:22 +00001923
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001924 >>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
1925 >>> for i in range(4):
1926 ... u = u0 + i*HOUR
1927 ... t = u.astimezone(Eastern)
1928 ... print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
1929 ...
1930 04:00:00 UTC = 00:00:00 EDT 0
1931 05:00:00 UTC = 01:00:00 EDT 0
1932 06:00:00 UTC = 01:00:00 EST 1
1933 07:00:00 UTC = 02:00:00 EST 0
1934
1935Note that the :class:`datetime` instances that differ only by the value of the
1936:attr:`~datetime.fold` attribute are considered equal in comparisons.
1937
1938Applications that can't bear wall-time ambiguities should explicitly check the
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001939value of the :attr:`~datetime.fold` attribute or avoid using hybrid
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001940:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`,
1941or any other fixed-offset :class:`tzinfo` subclass (such as a class representing
1942only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
1943
Sandro Tosid11d0d62012-04-24 19:46:06 +02001944.. seealso::
1945
wim glenn53f2af12017-06-06 12:54:41 -05001946 `dateutil.tz <https://dateutil.readthedocs.io/en/stable/tz.html>`_
Benjamin Peterson9b29acd2014-06-22 16:26:39 -07001947 The standard library has :class:`timezone` class for handling arbitrary
1948 fixed offsets from UTC and :attr:`timezone.utc` as UTC timezone instance.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001949
wim glenn53f2af12017-06-06 12:54:41 -05001950 *dateutil.tz* library brings the *IANA timezone database* (also known as the
Benjamin Peterson9b29acd2014-06-22 16:26:39 -07001951 Olson database) to Python and its usage is recommended.
Sandro Tosi100b8892012-04-28 11:19:37 +02001952
Serhiy Storchaka6dff0202016-05-07 10:49:07 +03001953 `IANA timezone database <https://www.iana.org/time-zones>`_
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001954 The Time Zone Database (often called tz, tzdata or zoneinfo) contains code and
Sandro Tosi100b8892012-04-28 11:19:37 +02001955 data that represent the history of local time for many representative
1956 locations around the globe. It is updated periodically to reflect changes
1957 made by political bodies to time zone boundaries, UTC offsets, and
1958 daylight-saving rules.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001959
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001960
1961.. _datetime-timezone:
1962
1963:class:`timezone` Objects
1964--------------------------
1965
Alexander Belopolsky6d3c9a62011-05-04 10:28:26 -04001966The :class:`timezone` class is a subclass of :class:`tzinfo`, each
1967instance of which represents a timezone defined by a fixed offset from
1968UTC. Note that objects of this class cannot be used to represent
1969timezone information in the locations where different offsets are used
1970in different days of the year or where historical changes have been
1971made to civil time.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001972
1973
Alexander Belopolsky53868aa2016-08-24 18:30:16 -04001974.. class:: timezone(offset, name=None)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001975
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001976 The *offset* argument must be specified as a :class:`timedelta`
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001977 object representing the difference between the local time and UTC. It must
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001978 be strictly between ``-timedelta(hours=24)`` and
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001979 ``timedelta(hours=24)``, otherwise :exc:`ValueError` is raised.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001980
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001981 The *name* argument is optional. If specified it must be a string that
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04001982 will be used as the value returned by the :meth:`datetime.tzname` method.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001983
Benjamin Peterson9b29acd2014-06-22 16:26:39 -07001984 .. versionadded:: 3.2
1985
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001986 .. versionchanged:: 3.7
1987 The UTC offset is not restricted to a whole number of minutes.
1988
1989
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001990.. method:: timezone.utcoffset(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001991
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001992 Return the fixed value specified when the :class:`timezone` instance is
1993 constructed. The *dt* argument is ignored. The return value is a
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001994 :class:`timedelta` instance equal to the difference between the
1995 local time and UTC.
1996
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001997 .. versionchanged:: 3.7
1998 The UTC offset is not restricted to a whole number of minutes.
1999
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002000.. method:: timezone.tzname(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002001
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04002002 Return the fixed value specified when the :class:`timezone` instance
2003 is constructed. If *name* is not provided in the constructor, the
2004 name returned by ``tzname(dt)`` is generated from the value of the
2005 ``offset`` as follows. If *offset* is ``timedelta(0)``, the name
2006 is "UTC", otherwise it is a string 'UTC±HH:MM', where ± is the sign
2007 of ``offset``, HH and MM are two digits of ``offset.hours`` and
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002008 ``offset.minutes`` respectively.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002009
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04002010 .. versionchanged:: 3.6
Berker Peksagdf326eb2015-09-09 18:32:50 +03002011 Name generated from ``offset=timedelta(0)`` is now plain 'UTC', not
2012 'UTC+00:00'.
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04002013
2014
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002015.. method:: timezone.dst(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002016
2017 Always returns ``None``.
2018
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002019.. method:: timezone.fromutc(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002020
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002021 Return ``dt + offset``. The *dt* argument must be an aware
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002022 :class:`.datetime` instance, with ``tzinfo`` set to ``self``.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00002023
2024Class attributes:
2025
2026.. attribute:: timezone.utc
2027
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00002028 The UTC timezone, ``timezone(timedelta(0))``.
Georg Brandl48310cd2009-01-03 21:18:54 +00002029
Georg Brandl116aa622007-08-15 14:28:22 +00002030
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03002031.. index::
Serhiy Storchaka913876d2018-10-28 13:41:26 +02002032 single: % (percent); datetime format
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03002033
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002034.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00002035
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002036:meth:`strftime` and :meth:`strptime` Behavior
2037----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00002038
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002039:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
Georg Brandl116aa622007-08-15 14:28:22 +00002040``strftime(format)`` method, to create a string representing the time under the
2041control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
2042acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
2043although not all objects support a :meth:`timetuple` method.
2044
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002045Conversely, the :meth:`datetime.strptime` class method creates a
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002046:class:`.datetime` object from a string representing a date and time and a
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002047corresponding format string. ``datetime.strptime(date_string, format)`` is
Gus Goulartc0799ec2018-10-29 08:49:52 -03002048equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``, except
2049when the format includes sub-second components or timezone offset information,
2050which are supported in ``datetime.strptime`` but are discarded by ``time.strptime``.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002051
Ezio Melotti35ec7f72011-10-02 12:44:50 +03002052For :class:`.time` objects, the format codes for year, month, and day should not
Georg Brandl116aa622007-08-15 14:28:22 +00002053be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00002054is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00002055
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002056For :class:`date` objects, the format codes for hours, minutes, seconds, and
2057microseconds should not be used, as :class:`date` objects have no such
2058values. If they're used anyway, ``0`` is substituted for them.
2059
Abhishek Kumar Singh56027cc2019-05-19 02:06:19 +05302060For the :meth:`datetime.strptime` class method, the default value is ``1900-01-01T00:00:00.000``:
2061any components not specified in the format string will be pulled from the default value. [#]_
2062
Georg Brandl116aa622007-08-15 14:28:22 +00002063The full set of format codes supported varies across platforms, because Python
2064calls the platform C library's :func:`strftime` function, and platform
Georg Brandlb7117af2013-10-13 18:28:25 +02002065variations are common. To see the full set of format codes supported on your
2066platform, consult the :manpage:`strftime(3)` documentation.
Christian Heimes895627f2007-12-08 17:28:33 +00002067
Alexey Izbyshev1cffd0e2019-01-13 00:21:54 +07002068For the same reason, handling of format strings containing Unicode code points
2069that can't be represented in the charset of the current locale is also
2070platform-dependent. On some platforms such code points are preserved intact in
2071the output, while on others ``strftime`` may raise :exc:`UnicodeError` or return
2072an empty string instead.
2073
Christian Heimes895627f2007-12-08 17:28:33 +00002074The following is a list of all the format codes that the C standard (1989
2075version) requires, and these work on all platforms with a standard C
2076implementation. Note that the 1999 version of the C standard added additional
2077format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00002078
David Wolever569a5fa2013-08-12 16:56:02 -04002079+-----------+--------------------------------+------------------------+-------+
2080| Directive | Meaning | Example | Notes |
2081+===========+================================+========================+=======+
2082| ``%a`` | Weekday as locale's || Sun, Mon, ..., Sat | \(1) |
2083| | abbreviated name. | (en_US); | |
2084| | || So, Mo, ..., Sa | |
2085| | | (de_DE) | |
2086+-----------+--------------------------------+------------------------+-------+
2087| ``%A`` | Weekday as locale's full name. || Sunday, Monday, ..., | \(1) |
2088| | | Saturday (en_US); | |
2089| | || Sonntag, Montag, ..., | |
2090| | | Samstag (de_DE) | |
2091+-----------+--------------------------------+------------------------+-------+
2092| ``%w`` | Weekday as a decimal number, | 0, 1, ..., 6 | |
2093| | where 0 is Sunday and 6 is | | |
2094| | Saturday. | | |
2095+-----------+--------------------------------+------------------------+-------+
2096| ``%d`` | Day of the month as a | 01, 02, ..., 31 | |
2097| | zero-padded decimal number. | | |
2098+-----------+--------------------------------+------------------------+-------+
2099| ``%b`` | Month as locale's abbreviated || Jan, Feb, ..., Dec | \(1) |
2100| | name. | (en_US); | |
2101| | || Jan, Feb, ..., Dez | |
2102| | | (de_DE) | |
2103+-----------+--------------------------------+------------------------+-------+
2104| ``%B`` | Month as locale's full name. || January, February, | \(1) |
2105| | | ..., December (en_US);| |
2106| | || Januar, Februar, ..., | |
2107| | | Dezember (de_DE) | |
2108+-----------+--------------------------------+------------------------+-------+
2109| ``%m`` | Month as a zero-padded | 01, 02, ..., 12 | |
2110| | decimal number. | | |
2111+-----------+--------------------------------+------------------------+-------+
2112| ``%y`` | Year without century as a | 00, 01, ..., 99 | |
2113| | zero-padded decimal number. | | |
2114+-----------+--------------------------------+------------------------+-------+
2115| ``%Y`` | Year with century as a decimal | 0001, 0002, ..., 2013, | \(2) |
David Wolever5d07e702013-08-14 14:41:48 -04002116| | number. | 2014, ..., 9998, 9999 | |
David Wolever569a5fa2013-08-12 16:56:02 -04002117+-----------+--------------------------------+------------------------+-------+
2118| ``%H`` | Hour (24-hour clock) as a | 00, 01, ..., 23 | |
2119| | zero-padded decimal number. | | |
2120+-----------+--------------------------------+------------------------+-------+
2121| ``%I`` | Hour (12-hour clock) as a | 01, 02, ..., 12 | |
2122| | zero-padded decimal number. | | |
2123+-----------+--------------------------------+------------------------+-------+
2124| ``%p`` | Locale's equivalent of either || AM, PM (en_US); | \(1), |
2125| | AM or PM. || am, pm (de_DE) | \(3) |
2126+-----------+--------------------------------+------------------------+-------+
2127| ``%M`` | Minute as a zero-padded | 00, 01, ..., 59 | |
2128| | decimal number. | | |
2129+-----------+--------------------------------+------------------------+-------+
2130| ``%S`` | Second as a zero-padded | 00, 01, ..., 59 | \(4) |
2131| | decimal number. | | |
2132+-----------+--------------------------------+------------------------+-------+
2133| ``%f`` | Microsecond as a decimal | 000000, 000001, ..., | \(5) |
2134| | number, zero-padded on the | 999999 | |
2135| | left. | | |
2136+-----------+--------------------------------+------------------------+-------+
Christophe Nanteuil92878822018-10-06 00:57:02 +02002137| ``%z`` | UTC offset in the form | (empty), +0000, | \(6) |
2138| | ±HHMM[SS[.ffffff]] (empty | -0400, +1030, | |
2139| | string if the object is | +063415, | |
2140| | naive). | -030712.345216 | |
David Wolever569a5fa2013-08-12 16:56:02 -04002141+-----------+--------------------------------+------------------------+-------+
2142| ``%Z`` | Time zone name (empty string | (empty), UTC, EST, CST | |
2143| | if the object is naive). | | |
2144+-----------+--------------------------------+------------------------+-------+
2145| ``%j`` | Day of the year as a | 001, 002, ..., 366 | |
2146| | zero-padded decimal number. | | |
2147+-----------+--------------------------------+------------------------+-------+
2148| ``%U`` | Week number of the year | 00, 01, ..., 53 | \(7) |
2149| | (Sunday as the first day of | | |
2150| | the week) as a zero padded | | |
2151| | decimal number. All days in a | | |
2152| | new year preceding the first | | |
2153| | Sunday are considered to be in | | |
2154| | week 0. | | |
2155+-----------+--------------------------------+------------------------+-------+
2156| ``%W`` | Week number of the year | 00, 01, ..., 53 | \(7) |
2157| | (Monday as the first day of | | |
2158| | the week) as a decimal number. | | |
2159| | All days in a new year | | |
2160| | preceding the first Monday | | |
2161| | are considered to be in | | |
2162| | week 0. | | |
2163+-----------+--------------------------------+------------------------+-------+
2164| ``%c`` | Locale's appropriate date and || Tue Aug 16 21:30:00 | \(1) |
2165| | time representation. | 1988 (en_US); | |
2166| | || Di 16 Aug 21:30:00 | |
2167| | | 1988 (de_DE) | |
2168+-----------+--------------------------------+------------------------+-------+
2169| ``%x`` | Locale's appropriate date || 08/16/88 (None); | \(1) |
2170| | representation. || 08/16/1988 (en_US); | |
2171| | || 16.08.1988 (de_DE) | |
2172+-----------+--------------------------------+------------------------+-------+
2173| ``%X`` | Locale's appropriate time || 21:30:00 (en_US); | \(1) |
2174| | representation. || 21:30:00 (de_DE) | |
2175+-----------+--------------------------------+------------------------+-------+
2176| ``%%`` | A literal ``'%'`` character. | % | |
2177+-----------+--------------------------------+------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00002178
Alexander Belopolsky68713e42015-10-06 13:29:56 -04002179Several additional directives not required by the C89 standard are included for
2180convenience. These parameters all correspond to ISO 8601 date values. These
2181may not be available on all platforms when used with the :meth:`strftime`
2182method. The ISO 8601 year and ISO 8601 week directives are not interchangeable
2183with the year and week number directives above. Calling :meth:`strptime` with
2184incomplete or ambiguous ISO 8601 directives will raise a :exc:`ValueError`.
2185
2186+-----------+--------------------------------+------------------------+-------+
2187| Directive | Meaning | Example | Notes |
2188+===========+================================+========================+=======+
2189| ``%G`` | ISO 8601 year with century | 0001, 0002, ..., 2013, | \(8) |
2190| | representing the year that | 2014, ..., 9998, 9999 | |
2191| | contains the greater part of | | |
2192| | the ISO week (``%V``). | | |
2193+-----------+--------------------------------+------------------------+-------+
2194| ``%u`` | ISO 8601 weekday as a decimal | 1, 2, ..., 7 | |
2195| | number where 1 is Monday. | | |
2196+-----------+--------------------------------+------------------------+-------+
2197| ``%V`` | ISO 8601 week as a decimal | 01, 02, ..., 53 | \(8) |
2198| | number with Monday as | | |
2199| | the first day of the week. | | |
2200| | Week 01 is the week containing | | |
2201| | Jan 4. | | |
2202+-----------+--------------------------------+------------------------+-------+
2203
2204.. versionadded:: 3.6
2205 ``%G``, ``%u`` and ``%V`` were added.
2206
Christian Heimes895627f2007-12-08 17:28:33 +00002207Notes:
2208
2209(1)
David Wolever569a5fa2013-08-12 16:56:02 -04002210 Because the format depends on the current locale, care should be taken when
2211 making assumptions about the output value. Field orderings will vary (for
2212 example, "month/day/year" versus "day/month/year"), and the output may
2213 contain Unicode characters encoded using the locale's default encoding (for
Georg Brandlad321532013-10-29 08:05:10 +01002214 example, if the current locale is ``ja_JP``, the default encoding could be
David Wolever569a5fa2013-08-12 16:56:02 -04002215 any one of ``eucJP``, ``SJIS``, or ``utf-8``; use :meth:`locale.getlocale`
2216 to determine the current locale's encoding).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002217
2218(2)
David Wolever569a5fa2013-08-12 16:56:02 -04002219 The :meth:`strptime` method can parse years in the full [1, 9999] range, but
2220 years < 1000 must be zero-filled to 4-digit width.
Alexander Belopolsky085556a2011-01-10 23:28:33 +00002221
2222 .. versionchanged:: 3.2
2223 In previous versions, :meth:`strftime` method was restricted to
2224 years >= 1900.
2225
Alexander Belopolsky5611a1c2011-05-02 14:14:48 -04002226 .. versionchanged:: 3.3
2227 In version 3.2, :meth:`strftime` method was restricted to
2228 years >= 1000.
2229
David Wolever569a5fa2013-08-12 16:56:02 -04002230(3)
2231 When used with the :meth:`strptime` method, the ``%p`` directive only affects
2232 the output hour field if the ``%I`` directive is used to parse the hour.
Alexander Belopolskyca94f552010-06-17 18:30:34 +00002233
David Wolever569a5fa2013-08-12 16:56:02 -04002234(4)
2235 Unlike the :mod:`time` module, the :mod:`datetime` module does not support
2236 leap seconds.
2237
2238(5)
2239 When used with the :meth:`strptime` method, the ``%f`` directive
2240 accepts from one to six digits and zero pads on the right. ``%f`` is
2241 an extension to the set of format characters in the C standard (but
2242 implemented separately in datetime objects, and therefore always
2243 available).
2244
2245(6)
2246 For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
2247 strings.
2248
2249 For an aware object:
2250
2251 ``%z``
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002252 :meth:`utcoffset` is transformed into a string of the form
Christophe Nanteuil92878822018-10-06 00:57:02 +02002253 ±HHMM[SS[.ffffff]], where HH is a 2-digit string giving the number of UTC
2254 offset hours, MM is a 2-digit string giving the number of UTC offset
Serhiy Storchakabac2d5b2018-03-28 22:14:26 +03002255 minutes, SS is a 2-digit string giving the number of UTC offset
Christophe Nanteuil92878822018-10-06 00:57:02 +02002256 seconds and ffffff is a 6-digit string giving the number of UTC
2257 offset microseconds. The ffffff part is omitted when the offset is a
2258 whole number of seconds and both the ffffff and the SS part is omitted
Alexander Belopolsky018d3532017-07-31 10:26:50 -04002259 when the offset is a whole number of minutes. For example, if
2260 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
2261 replaced with the string ``'-0330'``.
2262
2263 .. versionchanged:: 3.7
2264 The UTC offset is not restricted to a whole number of minutes.
David Wolever569a5fa2013-08-12 16:56:02 -04002265
Mario Corchero32318932017-10-26 01:35:41 +01002266 .. versionchanged:: 3.7
2267 When the ``%z`` directive is provided to the :meth:`strptime` method,
2268 the UTC offsets can have a colon as a separator between hours, minutes
2269 and seconds.
2270 For example, ``'+01:00:00'`` will be parsed as an offset of one hour.
2271 In addition, providing ``'Z'`` is identical to ``'+00:00'``.
2272
David Wolever569a5fa2013-08-12 16:56:02 -04002273 ``%Z``
2274 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty
2275 string. Otherwise ``%Z`` is replaced by the returned value, which must
2276 be a string.
2277
2278 .. versionchanged:: 3.2
2279 When the ``%z`` directive is provided to the :meth:`strptime` method, an
2280 aware :class:`.datetime` object will be produced. The ``tzinfo`` of the
2281 result will be set to a :class:`timezone` instance.
2282
2283(7)
2284 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used
Alexander Belopolsky68713e42015-10-06 13:29:56 -04002285 in calculations when the day of the week and the calendar year (``%Y``)
2286 are specified.
2287
2288(8)
2289 Similar to ``%U`` and ``%W``, ``%V`` is only used in calculations when the
2290 day of the week and the ISO year (``%G``) are specified in a
2291 :meth:`strptime` format string. Also note that ``%G`` and ``%Y`` are not
Martin Panterf1579822016-05-26 06:03:33 +00002292 interchangeable.
R David Murray9075d8b2012-05-14 22:14:46 -04002293
2294.. rubric:: Footnotes
2295
2296.. [#] If, that is, we ignore the effects of Relativity
Abhishek Kumar Singh56027cc2019-05-19 02:06:19 +05302297.. [#] Passing ``datetime.strptime('Feb 29', '%b %d')`` will fail since ``1900`` is not a leap year.