blob: cf5d5b85436f4b187ea2e81013eedc473956db2b [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.
6.. moduleauthor:: Tim Peters <tim@zope.com>
7.. sectionauthor:: Tim Peters <tim@zope.com>
8.. sectionauthor:: A.M. Kuchling <amk@amk.ca>
9
Andrew Kuchling2e3743c2014-03-19 16:23:01 -040010**Source code:** :source:`Lib/datetime.py`
11
Christian Heimes5b5e81c2007-12-31 16:14:33 +000012.. XXX what order should the types be discussed in?
Georg Brandl116aa622007-08-15 14:28:22 +000013
Georg Brandl116aa622007-08-15 14:28:22 +000014The :mod:`datetime` module supplies classes for manipulating dates and times in
15both simple and complex ways. While date and time arithmetic is supported, the
Senthil Kumarana6bac952011-07-04 11:28:30 -070016focus of the implementation is on efficient attribute extraction for output
R David Murray539f2392012-05-14 22:17:23 -040017formatting and manipulation. For related functionality, see also the
18:mod:`time` and :mod:`calendar` modules.
Georg Brandl116aa622007-08-15 14:28:22 +000019
R David Murray9075d8b2012-05-14 22:14:46 -040020There are two kinds of date and time objects: "naive" and "aware".
Georg Brandl116aa622007-08-15 14:28:22 +000021
R David Murray9075d8b2012-05-14 22:14:46 -040022An aware object has sufficient knowledge of applicable algorithmic and
23political time adjustments, such as time zone and daylight saving time
24information, to locate itself relative to other aware objects. An aware object
25is used to represent a specific moment in time that is not open to
26interpretation [#]_.
27
28A naive object does not contain enough information to unambiguously locate
29itself relative to other date/time objects. Whether a naive object represents
R David Murray539f2392012-05-14 22:17:23 -040030Coordinated Universal Time (UTC), local time, or time in some other timezone is
31purely up to the program, just like it is up to the program whether a
32particular number represents metres, miles, or mass. Naive objects are easy to
33understand and to work with, at the cost of ignoring some aspects of reality.
Georg Brandl116aa622007-08-15 14:28:22 +000034
R David Murray539f2392012-05-14 22:17:23 -040035For applications requiring aware objects, :class:`.datetime` and :class:`.time`
36objects have an optional time zone information attribute, :attr:`tzinfo`, that
37can be set to an instance of a subclass of the abstract :class:`tzinfo` class.
38These :class:`tzinfo` objects capture information about the offset from UTC
39time, the time zone name, and whether Daylight Saving Time is in effect. Note
40that only one concrete :class:`tzinfo` class, the :class:`timezone` class, is
41supplied by the :mod:`datetime` module. The :class:`timezone` class can
42represent simple timezones with fixed offset from UTC, such as UTC itself or
43North American EST and EDT timezones. Supporting timezones at deeper levels of
44detail is up to the application. The rules for time adjustment across the
Alexander Belopolsky4e749a12010-06-14 14:15:50 +000045world are more political than rational, change frequently, and there is no
46standard suitable for every application aside from UTC.
Georg Brandl116aa622007-08-15 14:28:22 +000047
48The :mod:`datetime` module exports the following constants:
49
Georg Brandl116aa622007-08-15 14:28:22 +000050.. data:: MINYEAR
51
Ezio Melotti35ec7f72011-10-02 12:44:50 +030052 The smallest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl116aa622007-08-15 14:28:22 +000053 :const:`MINYEAR` is ``1``.
54
55
56.. data:: MAXYEAR
57
Ezio Melotti35ec7f72011-10-02 12:44:50 +030058 The largest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl116aa622007-08-15 14:28:22 +000059 :const:`MAXYEAR` is ``9999``.
60
61
62.. seealso::
63
64 Module :mod:`calendar`
65 General calendar related functions.
66
67 Module :mod:`time`
68 Time access and conversions.
69
70
71Available Types
72---------------
73
Georg Brandl116aa622007-08-15 14:28:22 +000074.. class:: date
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000075 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000076
77 An idealized naive date, assuming the current Gregorian calendar always was, and
78 always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and
79 :attr:`day`.
80
81
82.. class:: time
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000083 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000084
85 An idealized time, independent of any particular day, assuming that every day
86 has exactly 24\*60\*60 seconds (there is no notion of "leap seconds" here).
87 Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
88 and :attr:`tzinfo`.
89
90
91.. class:: datetime
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000092 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000093
94 A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`,
95 :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
96 and :attr:`tzinfo`.
97
98
99.. class:: timedelta
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000100 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000101
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300102 A duration expressing the difference between two :class:`date`, :class:`.time`,
103 or :class:`.datetime` instances to microsecond resolution.
Georg Brandl116aa622007-08-15 14:28:22 +0000104
105
106.. class:: tzinfo
107
108 An abstract base class for time zone information objects. These are used by the
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300109 :class:`.datetime` and :class:`.time` classes to provide a customizable notion of
Georg Brandl116aa622007-08-15 14:28:22 +0000110 time adjustment (for example, to account for time zone and/or daylight saving
111 time).
112
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000113.. class:: timezone
114
115 A class that implements the :class:`tzinfo` abstract base class as a
116 fixed offset from the UTC.
117
118 .. versionadded:: 3.2
119
120
Georg Brandl116aa622007-08-15 14:28:22 +0000121Objects of these types are immutable.
122
123Objects of the :class:`date` type are always naive.
124
R David Murray9075d8b2012-05-14 22:14:46 -0400125An object of type :class:`.time` or :class:`.datetime` may be naive or aware.
126A :class:`.datetime` object *d* is aware if ``d.tzinfo`` is not ``None`` and
127``d.tzinfo.utcoffset(d)`` does not return ``None``. If ``d.tzinfo`` is
128``None``, or if ``d.tzinfo`` is not ``None`` but ``d.tzinfo.utcoffset(d)``
129returns ``None``, *d* is naive. A :class:`.time` object *t* is aware
130if ``t.tzinfo`` is not ``None`` and ``t.tzinfo.utcoffset(None)`` does not return
131``None``. Otherwise, *t* is naive.
Georg Brandl116aa622007-08-15 14:28:22 +0000132
133The distinction between naive and aware doesn't apply to :class:`timedelta`
134objects.
135
136Subclass relationships::
137
138 object
139 timedelta
140 tzinfo
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000141 timezone
Georg Brandl116aa622007-08-15 14:28:22 +0000142 time
143 date
144 datetime
145
146
147.. _datetime-timedelta:
148
149:class:`timedelta` Objects
150--------------------------
151
152A :class:`timedelta` object represents a duration, the difference between two
153dates or times.
154
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000155.. class:: timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000156
Georg Brandl5c106642007-11-29 17:41:05 +0000157 All arguments are optional and default to ``0``. Arguments may be integers
Georg Brandl116aa622007-08-15 14:28:22 +0000158 or floats, and may be positive or negative.
159
160 Only *days*, *seconds* and *microseconds* are stored internally. Arguments are
161 converted to those units:
162
163 * A millisecond is converted to 1000 microseconds.
164 * A minute is converted to 60 seconds.
165 * An hour is converted to 3600 seconds.
166 * A week is converted to 7 days.
167
168 and days, seconds and microseconds are then normalized so that the
169 representation is unique, with
170
171 * ``0 <= microseconds < 1000000``
172 * ``0 <= seconds < 3600*24`` (the number of seconds in one day)
173 * ``-999999999 <= days <= 999999999``
174
Alexander Belopolsky790d2692013-08-04 14:51:35 -0400175 If any argument is a float and there are fractional microseconds,
176 the fractional microseconds left over from all arguments are
177 combined and their sum is rounded to the nearest microsecond using
178 round-half-to-even tiebreaker. If no argument is a float, the
179 conversion and normalization processes are exact (no information is
180 lost).
Georg Brandl116aa622007-08-15 14:28:22 +0000181
182 If the normalized value of days lies outside the indicated range,
183 :exc:`OverflowError` is raised.
184
185 Note that normalization of negative values may be surprising at first. For
Christian Heimesfe337bf2008-03-23 21:54:12 +0000186 example,
Georg Brandl116aa622007-08-15 14:28:22 +0000187
Christian Heimes895627f2007-12-08 17:28:33 +0000188 >>> from datetime import timedelta
Georg Brandl116aa622007-08-15 14:28:22 +0000189 >>> d = timedelta(microseconds=-1)
190 >>> (d.days, d.seconds, d.microseconds)
191 (-1, 86399, 999999)
192
Georg Brandl116aa622007-08-15 14:28:22 +0000193
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000194Class attributes are:
Georg Brandl116aa622007-08-15 14:28:22 +0000195
196.. attribute:: timedelta.min
197
198 The most negative :class:`timedelta` object, ``timedelta(-999999999)``.
199
200
201.. attribute:: timedelta.max
202
203 The most positive :class:`timedelta` object, ``timedelta(days=999999999,
204 hours=23, minutes=59, seconds=59, microseconds=999999)``.
205
206
207.. attribute:: timedelta.resolution
208
209 The smallest possible difference between non-equal :class:`timedelta` objects,
210 ``timedelta(microseconds=1)``.
211
212Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``.
213``-timedelta.max`` is not representable as a :class:`timedelta` object.
214
215Instance attributes (read-only):
216
217+------------------+--------------------------------------------+
218| Attribute | Value |
219+==================+============================================+
220| ``days`` | Between -999999999 and 999999999 inclusive |
221+------------------+--------------------------------------------+
222| ``seconds`` | Between 0 and 86399 inclusive |
223+------------------+--------------------------------------------+
224| ``microseconds`` | Between 0 and 999999 inclusive |
225+------------------+--------------------------------------------+
226
227Supported operations:
228
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000229.. XXX this table is too wide!
Georg Brandl116aa622007-08-15 14:28:22 +0000230
231+--------------------------------+-----------------------------------------------+
232| Operation | Result |
233+================================+===============================================+
234| ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == |
235| | *t3* and *t1*-*t3* == *t2* are true. (1) |
236+--------------------------------+-----------------------------------------------+
237| ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* |
238| | == *t2* - *t3* and *t2* == *t1* + *t3* are |
239| | true. (1) |
240+--------------------------------+-----------------------------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000241| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer. |
Georg Brandl116aa622007-08-15 14:28:22 +0000242| | Afterwards *t1* // i == *t2* is true, |
243| | provided ``i != 0``. |
244+--------------------------------+-----------------------------------------------+
245| | In general, *t1* \* i == *t1* \* (i-1) + *t1* |
246| | is true. (1) |
247+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000248| ``t1 = t2 * f or t1 = f * t2`` | Delta multiplied by a float. The result is |
249| | rounded to the nearest multiple of |
250| | timedelta.resolution using round-half-to-even.|
251+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000252| ``f = t2 / t3`` | Division (3) of *t2* by *t3*. Returns a |
253| | :class:`float` object. |
254+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000255| ``t1 = t2 / f or t1 = t2 / i`` | Delta divided by a float or an int. The result|
256| | is rounded to the nearest multiple of |
257| | timedelta.resolution using round-half-to-even.|
258+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000259| ``t1 = t2 // i`` or | The floor is computed and the remainder (if |
260| ``t1 = t2 // t3`` | any) is thrown away. In the second case, an |
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000261| | integer is returned. (3) |
Mark Dickinson7c186e22010-04-20 22:32:49 +0000262+--------------------------------+-----------------------------------------------+
263| ``t1 = t2 % t3`` | The remainder is computed as a |
264| | :class:`timedelta` object. (3) |
265+--------------------------------+-----------------------------------------------+
266| ``q, r = divmod(t1, t2)`` | Computes the quotient and the remainder: |
267| | ``q = t1 // t2`` (3) and ``r = t1 % t2``. |
268| | q is an integer and r is a :class:`timedelta` |
269| | object. |
Georg Brandl116aa622007-08-15 14:28:22 +0000270+--------------------------------+-----------------------------------------------+
271| ``+t1`` | Returns a :class:`timedelta` object with the |
272| | same value. (2) |
273+--------------------------------+-----------------------------------------------+
274| ``-t1`` | equivalent to :class:`timedelta`\ |
275| | (-*t1.days*, -*t1.seconds*, |
276| | -*t1.microseconds*), and to *t1*\* -1. (1)(4) |
277+--------------------------------+-----------------------------------------------+
Georg Brandl495f7b52009-10-27 15:28:25 +0000278| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, and|
Georg Brandl116aa622007-08-15 14:28:22 +0000279| | to -*t* when ``t.days < 0``. (2) |
280+--------------------------------+-----------------------------------------------+
Georg Brandlf55c3152010-07-31 11:40:07 +0000281| ``str(t)`` | Returns a string in the form |
282| | ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D |
283| | is negative for negative ``t``. (5) |
284+--------------------------------+-----------------------------------------------+
285| ``repr(t)`` | Returns a string in the form |
286| | ``datetime.timedelta(D[, S[, U]])``, where D |
287| | is negative for negative ``t``. (5) |
288+--------------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000289
290Notes:
291
292(1)
293 This is exact, but may overflow.
294
295(2)
296 This is exact, and cannot overflow.
297
298(3)
299 Division by 0 raises :exc:`ZeroDivisionError`.
300
301(4)
302 -*timedelta.max* is not representable as a :class:`timedelta` object.
303
Georg Brandlf55c3152010-07-31 11:40:07 +0000304(5)
305 String representations of :class:`timedelta` objects are normalized
306 similarly to their internal representation. This leads to somewhat
307 unusual results for negative timedeltas. For example:
308
309 >>> timedelta(hours=-5)
310 datetime.timedelta(-1, 68400)
311 >>> print(_)
312 -1 day, 19:00:00
313
Georg Brandl116aa622007-08-15 14:28:22 +0000314In addition to the operations listed above :class:`timedelta` objects support
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300315certain additions and subtractions with :class:`date` and :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +0000316objects (see below).
317
Georg Brandl67b21b72010-08-17 15:07:14 +0000318.. versionchanged:: 3.2
319 Floor division and true division of a :class:`timedelta` object by another
320 :class:`timedelta` object are now supported, as are remainder operations and
321 the :func:`divmod` function. True division and multiplication of a
322 :class:`timedelta` object by a :class:`float` object are now supported.
Mark Dickinson7c186e22010-04-20 22:32:49 +0000323
324
Georg Brandl116aa622007-08-15 14:28:22 +0000325Comparisons of :class:`timedelta` objects are supported with the
326:class:`timedelta` object representing the smaller duration considered to be the
327smaller timedelta. In order to stop mixed-type comparisons from falling back to
328the default comparison by object address, when a :class:`timedelta` object is
329compared to an object of a different type, :exc:`TypeError` is raised unless the
330comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
331:const:`True`, respectively.
332
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000333:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl116aa622007-08-15 14:28:22 +0000334efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
335considered to be true if and only if it isn't equal to ``timedelta(0)``.
336
Antoine Pitroube6859d2009-11-25 23:02:32 +0000337Instance methods:
338
339.. method:: timedelta.total_seconds()
340
341 Return the total number of seconds contained in the duration. Equivalent to
Mark Dickinson0381e3f2010-05-08 14:35:02 +0000342 ``td / timedelta(seconds=1)``.
343
344 Note that for very large time intervals (greater than 270 years on
345 most platforms) this method will lose microsecond accuracy.
Antoine Pitroube6859d2009-11-25 23:02:32 +0000346
347 .. versionadded:: 3.2
348
349
Christian Heimesfe337bf2008-03-23 21:54:12 +0000350Example usage:
Georg Brandl48310cd2009-01-03 21:18:54 +0000351
Christian Heimes895627f2007-12-08 17:28:33 +0000352 >>> from datetime import timedelta
353 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000354 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Christian Heimes895627f2007-12-08 17:28:33 +0000355 ... minutes=50, seconds=600) # adds up to 365 days
Antoine Pitroube6859d2009-11-25 23:02:32 +0000356 >>> year.total_seconds()
357 31536000.0
Christian Heimes895627f2007-12-08 17:28:33 +0000358 >>> year == another_year
359 True
360 >>> ten_years = 10 * year
361 >>> ten_years, ten_years.days // 365
362 (datetime.timedelta(3650), 10)
363 >>> nine_years = ten_years - year
364 >>> nine_years, nine_years.days // 365
365 (datetime.timedelta(3285), 9)
366 >>> three_years = nine_years // 3;
367 >>> three_years, three_years.days // 365
368 (datetime.timedelta(1095), 3)
369 >>> abs(three_years - ten_years) == 2 * three_years + year
370 True
371
Georg Brandl116aa622007-08-15 14:28:22 +0000372
373.. _datetime-date:
374
375:class:`date` Objects
376---------------------
377
378A :class:`date` object represents a date (year, month and day) in an idealized
379calendar, the current Gregorian calendar indefinitely extended in both
380directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
381called day number 2, and so on. This matches the definition of the "proleptic
382Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
383where it's the base calendar for all computations. See the book for algorithms
384for converting between proleptic Gregorian ordinals and many other calendar
385systems.
386
387
388.. class:: date(year, month, day)
389
Georg Brandl5c106642007-11-29 17:41:05 +0000390 All arguments are required. Arguments may be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000391 ranges:
392
393 * ``MINYEAR <= year <= MAXYEAR``
394 * ``1 <= month <= 12``
395 * ``1 <= day <= number of days in the given month and year``
396
397 If an argument outside those ranges is given, :exc:`ValueError` is raised.
398
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000399
Georg Brandl116aa622007-08-15 14:28:22 +0000400Other constructors, all class methods:
401
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000402.. classmethod:: date.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000403
404 Return the current local date. This is equivalent to
405 ``date.fromtimestamp(time.time())``.
406
407
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000408.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000409
410 Return the local date corresponding to the POSIX timestamp, such as is returned
Victor Stinner5d272cc2012-03-13 13:35:55 +0100411 by :func:`time.time`. This may raise :exc:`OverflowError`, if the timestamp is out
Victor Stinnerecc6e662012-03-14 00:39:29 +0100412 of the range of values supported by the platform C :c:func:`localtime` function,
413 and :exc:`OSError` on :c:func:`localtime` failure.
Georg Brandl116aa622007-08-15 14:28:22 +0000414 It's common for this to be restricted to years from 1970 through 2038. Note
415 that on non-POSIX systems that include leap seconds in their notion of a
416 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
417
Victor Stinner5d272cc2012-03-13 13:35:55 +0100418 .. versionchanged:: 3.3
419 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
420 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100421 :c:func:`localtime` function. Raise :exc:`OSError` instead of
422 :exc:`ValueError` on :c:func:`localtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100423
Georg Brandl116aa622007-08-15 14:28:22 +0000424
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000425.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000426
427 Return the date corresponding to the proleptic Gregorian ordinal, where January
428 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
429 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
430 d``.
431
Georg Brandl116aa622007-08-15 14:28:22 +0000432
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000433Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000434
435.. attribute:: date.min
436
437 The earliest representable date, ``date(MINYEAR, 1, 1)``.
438
439
440.. attribute:: date.max
441
442 The latest representable date, ``date(MAXYEAR, 12, 31)``.
443
444
445.. attribute:: date.resolution
446
447 The smallest possible difference between non-equal date objects,
448 ``timedelta(days=1)``.
449
Georg Brandl116aa622007-08-15 14:28:22 +0000450
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000451Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000452
453.. attribute:: date.year
454
455 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
456
457
458.. attribute:: date.month
459
460 Between 1 and 12 inclusive.
461
462
463.. attribute:: date.day
464
465 Between 1 and the number of days in the given month of the given year.
466
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000467
Georg Brandl116aa622007-08-15 14:28:22 +0000468Supported operations:
469
470+-------------------------------+----------------------------------------------+
471| Operation | Result |
472+===============================+==============================================+
473| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
474| | from *date1*. (1) |
475+-------------------------------+----------------------------------------------+
476| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
477| | timedelta == date1``. (2) |
478+-------------------------------+----------------------------------------------+
479| ``timedelta = date1 - date2`` | \(3) |
480+-------------------------------+----------------------------------------------+
481| ``date1 < date2`` | *date1* is considered less than *date2* when |
482| | *date1* precedes *date2* in time. (4) |
483+-------------------------------+----------------------------------------------+
484
485Notes:
486
487(1)
488 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
489 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
490 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
491 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
492 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
493
494(2)
495 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
496 isolation can overflow in cases where date1 - timedelta does not.
497 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
498
499(3)
500 This is exact, and cannot overflow. timedelta.seconds and
501 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
502
503(4)
504 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
505 date2.toordinal()``. In order to stop comparison from falling back to the
506 default scheme of comparing object addresses, date comparison normally raises
507 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
508 However, ``NotImplemented`` is returned instead if the other comparand has a
509 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
510 chance at implementing mixed-type comparison. If not, when a :class:`date`
511 object is compared to an object of a different type, :exc:`TypeError` is raised
512 unless the comparison is ``==`` or ``!=``. The latter cases return
513 :const:`False` or :const:`True`, respectively.
514
515Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
516objects are considered to be true.
517
518Instance methods:
519
Georg Brandl116aa622007-08-15 14:28:22 +0000520.. method:: date.replace(year, month, day)
521
Senthil Kumarana6bac952011-07-04 11:28:30 -0700522 Return a date with the same value, except for those parameters given new
523 values by whichever keyword arguments are specified. For example, if ``d ==
524 date(2002, 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000525
526
527.. method:: date.timetuple()
528
529 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
530 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
531 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000532 d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1,
533 1).toordinal() + 1`` is the day number within the current year starting with
534 ``1`` for January 1st.
Georg Brandl116aa622007-08-15 14:28:22 +0000535
536
537.. method:: date.toordinal()
538
539 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
540 has ordinal 1. For any :class:`date` object *d*,
541 ``date.fromordinal(d.toordinal()) == d``.
542
543
544.. method:: date.weekday()
545
546 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
547 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
548 :meth:`isoweekday`.
549
550
551.. method:: date.isoweekday()
552
553 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
554 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
555 :meth:`weekday`, :meth:`isocalendar`.
556
557
558.. method:: date.isocalendar()
559
560 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
561
562 The ISO calendar is a widely used variant of the Gregorian calendar. See
Georg Brandlb7354a62014-10-29 10:57:37 +0100563 http://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm for a good
Mark Dickinsonf964ac22009-11-03 16:29:10 +0000564 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000565
566 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
567 Monday and ends on a Sunday. The first week of an ISO year is the first
568 (Gregorian) calendar week of a year containing a Thursday. This is called week
569 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
570
571 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
572 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
573 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
574 4).isocalendar() == (2004, 1, 7)``.
575
576
577.. method:: date.isoformat()
578
579 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
580 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
581
582
583.. method:: date.__str__()
584
585 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
586
587
588.. method:: date.ctime()
589
590 Return a string representing the date, for example ``date(2002, 12,
591 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
592 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
Georg Brandl60203b42010-10-06 10:11:56 +0000593 :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +0000594 :meth:`date.ctime` does not invoke) conforms to the C standard.
595
596
597.. method:: date.strftime(format)
598
599 Return a string representing the date, controlled by an explicit format string.
David Wolever569a5fa2013-08-12 16:56:02 -0400600 Format codes referring to hours, minutes or seconds will see 0 values. For a
601 complete list of formatting directives, see
602 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000603
Georg Brandl116aa622007-08-15 14:28:22 +0000604
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300605.. method:: date.__format__(format)
606
607 Same as :meth:`.date.strftime`. This makes it possible to specify format
David Wolever569a5fa2013-08-12 16:56:02 -0400608 string for a :class:`.date` object when using :meth:`str.format`. For a
609 complete list of formatting directives, see
610 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300611
612
Christian Heimes895627f2007-12-08 17:28:33 +0000613Example of counting days to an event::
614
615 >>> import time
616 >>> from datetime import date
617 >>> today = date.today()
618 >>> today
619 datetime.date(2007, 12, 5)
620 >>> today == date.fromtimestamp(time.time())
621 True
622 >>> my_birthday = date(today.year, 6, 24)
623 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000624 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000625 >>> my_birthday
626 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000627 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000628 >>> time_to_birthday.days
629 202
630
Christian Heimesfe337bf2008-03-23 21:54:12 +0000631Example of working with :class:`date`:
632
633.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000634
635 >>> from datetime import date
636 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
637 >>> d
638 datetime.date(2002, 3, 11)
639 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000640 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000641 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000642 2002 # year
643 3 # month
644 11 # day
645 0
646 0
647 0
648 0 # weekday (0 = Monday)
649 70 # 70th day in the year
650 -1
651 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000652 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000653 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000654 2002 # ISO year
655 11 # ISO week number
656 1 # ISO day number ( 1 = Monday )
657 >>> d.isoformat()
658 '2002-03-11'
659 >>> d.strftime("%d/%m/%y")
660 '11/03/02'
661 >>> d.strftime("%A %d. %B %Y")
662 'Monday 11. March 2002'
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300663 >>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")
664 'The day is 11, the month is March.'
Christian Heimes895627f2007-12-08 17:28:33 +0000665
Georg Brandl116aa622007-08-15 14:28:22 +0000666
667.. _datetime-datetime:
668
Benjamin Petersond87dd432015-04-25 14:15:16 -0400669:class:`.datetime` Objects
670--------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000671
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300672A :class:`.datetime` object is a single object containing all the information
673from a :class:`date` object and a :class:`.time` object. Like a :class:`date`
674object, :class:`.datetime` assumes the current Gregorian calendar extended in
675both directions; like a time object, :class:`.datetime` assumes there are exactly
Georg Brandl116aa622007-08-15 14:28:22 +00006763600\*24 seconds in every day.
677
678Constructor:
679
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000680.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000681
682 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000683 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
684 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000685
686 * ``MINYEAR <= year <= MAXYEAR``
687 * ``1 <= month <= 12``
688 * ``1 <= day <= number of days in the given month and year``
689 * ``0 <= hour < 24``
690 * ``0 <= minute < 60``
691 * ``0 <= second < 60``
692 * ``0 <= microsecond < 1000000``
693
694 If an argument outside those ranges is given, :exc:`ValueError` is raised.
695
696Other constructors, all class methods:
697
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000698.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000699
700 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
701 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
702 :meth:`fromtimestamp`.
703
704
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000705.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000706
707 Return the current local date and time. If optional argument *tz* is ``None``
708 or not specified, this is like :meth:`today`, but, if possible, supplies more
709 precision than can be gotten from going through a :func:`time.time` timestamp
710 (for example, this may be possible on platforms supplying the C
Georg Brandl60203b42010-10-06 10:11:56 +0000711 :c:func:`gettimeofday` function).
Georg Brandl116aa622007-08-15 14:28:22 +0000712
713 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
714 current date and time are converted to *tz*'s time zone. In this case the
715 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
716 See also :meth:`today`, :meth:`utcnow`.
717
718
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000719.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000720
721 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
722 :meth:`now`, but returns the current UTC date and time, as a naive
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300723 :class:`.datetime` object. An aware current UTC datetime can be obtained by
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000724 calling ``datetime.now(timezone.utc)``. See also :meth:`now`.
Georg Brandl116aa622007-08-15 14:28:22 +0000725
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000726.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000727
728 Return the local date and time corresponding to the POSIX timestamp, such as is
729 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
730 specified, the timestamp is converted to the platform's local date and time, and
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300731 the returned :class:`.datetime` object is naive.
Georg Brandl116aa622007-08-15 14:28:22 +0000732
733 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
734 timestamp is converted to *tz*'s time zone. In this case the result is
735 equivalent to
736 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
737
Victor Stinnerecc6e662012-03-14 00:39:29 +0100738 :meth:`fromtimestamp` may raise :exc:`OverflowError`, if the timestamp is out of
Georg Brandl60203b42010-10-06 10:11:56 +0000739 the range of values supported by the platform C :c:func:`localtime` or
Victor Stinnerecc6e662012-03-14 00:39:29 +0100740 :c:func:`gmtime` functions, and :exc:`OSError` on :c:func:`localtime` or
741 :c:func:`gmtime` failure.
742 It's common for this to be restricted to years in
Georg Brandl116aa622007-08-15 14:28:22 +0000743 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
744 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
745 and then it's possible to have two timestamps differing by a second that yield
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300746 identical :class:`.datetime` objects. See also :meth:`utcfromtimestamp`.
Georg Brandl116aa622007-08-15 14:28:22 +0000747
Victor Stinner5d272cc2012-03-13 13:35:55 +0100748 .. versionchanged:: 3.3
749 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
750 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100751 :c:func:`localtime` or :c:func:`gmtime` functions. Raise :exc:`OSError`
752 instead of :exc:`ValueError` on :c:func:`localtime` or :c:func:`gmtime`
753 failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100754
Georg Brandl116aa622007-08-15 14:28:22 +0000755
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000756.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000757
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300758 Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with
Victor Stinnerecc6e662012-03-14 00:39:29 +0100759 :attr:`tzinfo` ``None``. This may raise :exc:`OverflowError`, if the timestamp is
760 out of the range of values supported by the platform C :c:func:`gmtime` function,
761 and :exc:`OSError` on :c:func:`gmtime` failure.
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500762 It's common for this to be restricted to years in 1970 through 2038.
Georg Brandl116aa622007-08-15 14:28:22 +0000763
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500764 To get an aware :class:`.datetime` object, call :meth:`fromtimestamp`::
Alexander Belopolsky54afa552011-04-25 13:00:40 -0400765
Alexander Belopolskye2e178e2015-03-01 14:52:07 -0500766 datetime.fromtimestamp(timestamp, timezone.utc)
767
768 On the POSIX compliant platforms, it is equivalent to the following
769 expression::
770
771 datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)
772
773 except the latter formula always supports the full years range: between
774 :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
Alexander Belopolsky54afa552011-04-25 13:00:40 -0400775
Victor Stinner5d272cc2012-03-13 13:35:55 +0100776 .. versionchanged:: 3.3
777 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
778 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100779 :c:func:`gmtime` function. Raise :exc:`OSError` instead of
780 :exc:`ValueError` on :c:func:`gmtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100781
Georg Brandl116aa622007-08-15 14:28:22 +0000782
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000783.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000784
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300785 Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal,
Georg Brandl116aa622007-08-15 14:28:22 +0000786 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
787 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
788 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
789
790
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000791.. classmethod:: datetime.combine(date, time)
Georg Brandl116aa622007-08-15 14:28:22 +0000792
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300793 Return a new :class:`.datetime` object whose date components are equal to the
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800794 given :class:`date` object's, and whose time components and :attr:`tzinfo`
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300795 attributes are equal to the given :class:`.time` object's. For any
796 :class:`.datetime` object *d*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800797 ``d == datetime.combine(d.date(), d.timetz())``. If date is a
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300798 :class:`.datetime` object, its time components and :attr:`tzinfo` attributes
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800799 are ignored.
Georg Brandl116aa622007-08-15 14:28:22 +0000800
801
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000802.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000803
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300804 Return a :class:`.datetime` corresponding to *date_string*, parsed according to
Georg Brandl116aa622007-08-15 14:28:22 +0000805 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
806 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
807 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 -0400808 time tuple. For a complete list of formatting directives, see
809 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000810
Georg Brandl116aa622007-08-15 14:28:22 +0000811
Georg Brandl116aa622007-08-15 14:28:22 +0000812
813Class attributes:
814
Georg Brandl116aa622007-08-15 14:28:22 +0000815.. attribute:: datetime.min
816
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300817 The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1,
Georg Brandl116aa622007-08-15 14:28:22 +0000818 tzinfo=None)``.
819
820
821.. attribute:: datetime.max
822
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300823 The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
Georg Brandl116aa622007-08-15 14:28:22 +0000824 59, 999999, tzinfo=None)``.
825
826
827.. attribute:: datetime.resolution
828
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300829 The smallest possible difference between non-equal :class:`.datetime` objects,
Georg Brandl116aa622007-08-15 14:28:22 +0000830 ``timedelta(microseconds=1)``.
831
Georg Brandl116aa622007-08-15 14:28:22 +0000832
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000833Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000834
835.. attribute:: datetime.year
836
837 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
838
839
840.. attribute:: datetime.month
841
842 Between 1 and 12 inclusive.
843
844
845.. attribute:: datetime.day
846
847 Between 1 and the number of days in the given month of the given year.
848
849
850.. attribute:: datetime.hour
851
852 In ``range(24)``.
853
854
855.. attribute:: datetime.minute
856
857 In ``range(60)``.
858
859
860.. attribute:: datetime.second
861
862 In ``range(60)``.
863
864
865.. attribute:: datetime.microsecond
866
867 In ``range(1000000)``.
868
869
870.. attribute:: datetime.tzinfo
871
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300872 The object passed as the *tzinfo* argument to the :class:`.datetime` constructor,
Georg Brandl116aa622007-08-15 14:28:22 +0000873 or ``None`` if none was passed.
874
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000875
Georg Brandl116aa622007-08-15 14:28:22 +0000876Supported operations:
877
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300878+---------------------------------------+--------------------------------+
879| Operation | Result |
880+=======================================+================================+
881| ``datetime2 = datetime1 + timedelta`` | \(1) |
882+---------------------------------------+--------------------------------+
883| ``datetime2 = datetime1 - timedelta`` | \(2) |
884+---------------------------------------+--------------------------------+
885| ``timedelta = datetime1 - datetime2`` | \(3) |
886+---------------------------------------+--------------------------------+
887| ``datetime1 < datetime2`` | Compares :class:`.datetime` to |
888| | :class:`.datetime`. (4) |
889+---------------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000890
891(1)
892 datetime2 is a duration of timedelta removed from datetime1, moving forward in
893 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
Senthil Kumarana6bac952011-07-04 11:28:30 -0700894 result has the same :attr:`tzinfo` attribute as the input datetime, and
895 datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
896 datetime2.year would be smaller than :const:`MINYEAR` or larger than
897 :const:`MAXYEAR`. Note that no time zone adjustments are done even if the
898 input is an aware object.
Georg Brandl116aa622007-08-15 14:28:22 +0000899
900(2)
901 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
Senthil Kumarana6bac952011-07-04 11:28:30 -0700902 addition, the result has the same :attr:`tzinfo` attribute as the input
903 datetime, and no time zone adjustments are done even if the input is aware.
904 This isn't quite equivalent to datetime1 + (-timedelta), because -timedelta
905 in isolation can overflow in cases where datetime1 - timedelta does not.
Georg Brandl116aa622007-08-15 14:28:22 +0000906
907(3)
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300908 Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if
Georg Brandl116aa622007-08-15 14:28:22 +0000909 both operands are naive, or if both are aware. If one is aware and the other is
910 naive, :exc:`TypeError` is raised.
911
Senthil Kumarana6bac952011-07-04 11:28:30 -0700912 If both are naive, or both are aware and have the same :attr:`tzinfo` attribute,
913 the :attr:`tzinfo` attributes are ignored, and the result is a :class:`timedelta`
Georg Brandl116aa622007-08-15 14:28:22 +0000914 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
915 are done in this case.
916
Senthil Kumarana6bac952011-07-04 11:28:30 -0700917 If both are aware and have different :attr:`tzinfo` attributes, ``a-b`` acts
918 as if *a* and *b* were first converted to naive UTC datetimes first. The
919 result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
920 - b.utcoffset())`` except that the implementation never overflows.
Georg Brandl116aa622007-08-15 14:28:22 +0000921
922(4)
923 *datetime1* is considered less than *datetime2* when *datetime1* precedes
924 *datetime2* in time.
925
Alexander Belopolsky08313822012-06-15 20:19:47 -0400926 If one comparand is naive and the other is aware, :exc:`TypeError`
927 is raised if an order comparison is attempted. For equality
928 comparisons, naive instances are never equal to aware instances.
929
Senthil Kumarana6bac952011-07-04 11:28:30 -0700930 If both comparands are aware, and have the same :attr:`tzinfo` attribute, the
931 common :attr:`tzinfo` attribute is ignored and the base datetimes are
932 compared. If both comparands are aware and have different :attr:`tzinfo`
933 attributes, the comparands are first adjusted by subtracting their UTC
934 offsets (obtained from ``self.utcoffset()``).
Georg Brandl116aa622007-08-15 14:28:22 +0000935
Alexander Belopolsky08313822012-06-15 20:19:47 -0400936 .. versionchanged:: 3.3
Éric Araujob0f08952012-06-24 16:22:09 -0400937 Equality comparisons between naive and aware :class:`datetime`
938 instances don't raise :exc:`TypeError`.
Alexander Belopolsky08313822012-06-15 20:19:47 -0400939
Georg Brandl116aa622007-08-15 14:28:22 +0000940 .. note::
941
942 In order to stop comparison from falling back to the default scheme of comparing
943 object addresses, datetime comparison normally raises :exc:`TypeError` if the
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300944 other comparand isn't also a :class:`.datetime` object. However,
Georg Brandl116aa622007-08-15 14:28:22 +0000945 ``NotImplemented`` is returned instead if the other comparand has a
946 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300947 chance at implementing mixed-type comparison. If not, when a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +0000948 object is compared to an object of a different type, :exc:`TypeError` is raised
949 unless the comparison is ``==`` or ``!=``. The latter cases return
950 :const:`False` or :const:`True`, respectively.
951
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300952:class:`.datetime` objects can be used as dictionary keys. In Boolean contexts,
953all :class:`.datetime` objects are considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +0000954
955Instance methods:
956
Georg Brandl116aa622007-08-15 14:28:22 +0000957.. method:: datetime.date()
958
959 Return :class:`date` object with same year, month and day.
960
961
962.. method:: datetime.time()
963
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300964 Return :class:`.time` object with same hour, minute, second and microsecond.
Georg Brandl116aa622007-08-15 14:28:22 +0000965 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
966
967
968.. method:: datetime.timetz()
969
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300970 Return :class:`.time` object with same hour, minute, second, microsecond, and
Senthil Kumarana6bac952011-07-04 11:28:30 -0700971 tzinfo attributes. See also method :meth:`time`.
Georg Brandl116aa622007-08-15 14:28:22 +0000972
973
974.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
975
Senthil Kumarana6bac952011-07-04 11:28:30 -0700976 Return a datetime with the same attributes, except for those attributes given
977 new values by whichever keyword arguments are specified. Note that
978 ``tzinfo=None`` can be specified to create a naive datetime from an aware
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800979 datetime with no conversion of date and time data.
Georg Brandl116aa622007-08-15 14:28:22 +0000980
981
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -0400982.. method:: datetime.astimezone(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000983
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -0400984 Return a :class:`datetime` object with new :attr:`tzinfo` attribute *tz*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800985 adjusting the date and time data so the result is the same UTC time as
Senthil Kumarana6bac952011-07-04 11:28:30 -0700986 *self*, but in *tz*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +0000987
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -0400988 If provided, *tz* must be an instance of a :class:`tzinfo` subclass, and its
Georg Brandl116aa622007-08-15 14:28:22 +0000989 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
990 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
991 not return ``None``).
992
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -0400993 If called without arguments (or with ``tz=None``) the system local
994 timezone is assumed. The ``tzinfo`` attribute of the converted
995 datetime instance will be set to an instance of :class:`timezone`
996 with the zone name and offset obtained from the OS.
997
Georg Brandl116aa622007-08-15 14:28:22 +0000998 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800999 adjustment of date or time data is performed. Else the result is local
Senthil Kumarana6bac952011-07-04 11:28:30 -07001000 time in time zone *tz*, representing the same UTC time as *self*: after
1001 ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001002 the same date and time data as ``dt - dt.utcoffset()``. The discussion
Senthil Kumarana6bac952011-07-04 11:28:30 -07001003 of class :class:`tzinfo` explains the cases at Daylight Saving Time transition
1004 boundaries where this cannot be achieved (an issue only if *tz* models both
1005 standard and daylight time).
Georg Brandl116aa622007-08-15 14:28:22 +00001006
1007 If you merely want to attach a time zone object *tz* to a datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001008 adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you
Georg Brandl116aa622007-08-15 14:28:22 +00001009 merely want to remove the time zone object from an aware datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001010 conversion of date and time data, use ``dt.replace(tzinfo=None)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001011
1012 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
1013 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
1014 Ignoring error cases, :meth:`astimezone` acts like::
1015
1016 def astimezone(self, tz):
1017 if self.tzinfo is tz:
1018 return self
1019 # Convert self to UTC, and attach the new time zone object.
1020 utc = (self - self.utcoffset()).replace(tzinfo=tz)
1021 # Convert from UTC to tz's local time.
1022 return tz.fromutc(utc)
1023
Georg Brandlee0be402012-06-26 09:14:40 +02001024 .. versionchanged:: 3.3
1025 *tz* now can be omitted.
1026
Georg Brandl116aa622007-08-15 14:28:22 +00001027
1028.. method:: datetime.utcoffset()
1029
1030 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1031 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
1032 return ``None``, or a :class:`timedelta` object representing a whole number of
1033 minutes with magnitude less than one day.
1034
1035
1036.. method:: datetime.dst()
1037
1038 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1039 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
1040 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1041 with magnitude less than one day.
1042
1043
1044.. method:: datetime.tzname()
1045
1046 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1047 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
1048 ``None`` or a string object,
1049
1050
1051.. method:: datetime.timetuple()
1052
1053 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
1054 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
Alexander Belopolsky64912482010-06-08 18:59:20 +00001055 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
1056 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
1057 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
1058 of the result is set according to the :meth:`dst` method: :attr:`tzinfo` is
Georg Brandl682d7e02010-10-06 10:26:05 +00001059 ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
Alexander Belopolsky64912482010-06-08 18:59:20 +00001060 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
Alexander Belopolskyda62f2f2010-06-09 17:11:01 +00001061 else :attr:`tm_isdst` is set to ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +00001062
1063
1064.. method:: datetime.utctimetuple()
1065
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001066 If :class:`.datetime` instance *d* is naive, this is the same as
Georg Brandl116aa622007-08-15 14:28:22 +00001067 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
1068 ``d.dst()`` returns. DST is never in effect for a UTC time.
1069
1070 If *d* is aware, *d* is normalized to UTC time, by subtracting
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00001071 ``d.utcoffset()``, and a :class:`time.struct_time` for the
1072 normalized time is returned. :attr:`tm_isdst` is forced to 0. Note
1073 that an :exc:`OverflowError` may be raised if *d*.year was
1074 ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
Georg Brandl116aa622007-08-15 14:28:22 +00001075 boundary.
1076
1077
1078.. method:: datetime.toordinal()
1079
1080 Return the proleptic Gregorian ordinal of the date. The same as
1081 ``self.date().toordinal()``.
1082
Alexander Belopolskya4415142012-06-08 12:33:09 -04001083.. method:: datetime.timestamp()
1084
1085 Return POSIX timestamp corresponding to the :class:`datetime`
1086 instance. The return value is a :class:`float` similar to that
1087 returned by :func:`time.time`.
1088
1089 Naive :class:`datetime` instances are assumed to represent local
1090 time and this method relies on the platform C :c:func:`mktime`
1091 function to perform the conversion. Since :class:`datetime`
1092 supports wider range of values than :c:func:`mktime` on many
1093 platforms, this method may raise :exc:`OverflowError` for times far
1094 in the past or far in the future.
1095
1096 For aware :class:`datetime` instances, the return value is computed
1097 as::
1098
1099 (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
1100
1101 .. versionadded:: 3.3
1102
1103 .. note::
1104
1105 There is no method to obtain the POSIX timestamp directly from a
1106 naive :class:`datetime` instance representing UTC time. If your
1107 application uses this convention and your system timezone is not
1108 set to UTC, you can obtain the POSIX timestamp by supplying
1109 ``tzinfo=timezone.utc``::
1110
1111 timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
1112
1113 or by calculating the timestamp directly::
1114
1115 timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001116
1117.. method:: datetime.weekday()
1118
1119 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
1120 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
1121
1122
1123.. method:: datetime.isoweekday()
1124
1125 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
1126 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
1127 :meth:`isocalendar`.
1128
1129
1130.. method:: datetime.isocalendar()
1131
1132 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
1133 ``self.date().isocalendar()``.
1134
1135
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001136.. method:: datetime.isoformat(sep='T')
Georg Brandl116aa622007-08-15 14:28:22 +00001137
1138 Return a string representing the date and time in ISO 8601 format,
1139 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
1140 YYYY-MM-DDTHH:MM:SS
1141
1142 If :meth:`utcoffset` does not return ``None``, a 6-character string is
1143 appended, giving the UTC offset in (signed) hours and minutes:
1144 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
1145 YYYY-MM-DDTHH:MM:SS+HH:MM
1146
1147 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +00001148 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +00001149
1150 >>> from datetime import tzinfo, timedelta, datetime
1151 >>> class TZ(tzinfo):
1152 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1153 ...
1154 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1155 '2002-12-25 00:00:00-06:39'
1156
1157
1158.. method:: datetime.__str__()
1159
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001160 For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to
Georg Brandl116aa622007-08-15 14:28:22 +00001161 ``d.isoformat(' ')``.
1162
1163
1164.. method:: datetime.ctime()
1165
1166 Return a string representing the date and time, for example ``datetime(2002, 12,
1167 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1168 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
Georg Brandl60203b42010-10-06 10:11:56 +00001169 native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +00001170 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1171
1172
1173.. method:: datetime.strftime(format)
1174
1175 Return a string representing the date and time, controlled by an explicit format
David Wolever569a5fa2013-08-12 16:56:02 -04001176 string. For a complete list of formatting directives, see
1177 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001178
Georg Brandl116aa622007-08-15 14:28:22 +00001179
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001180.. method:: datetime.__format__(format)
1181
1182 Same as :meth:`.datetime.strftime`. This makes it possible to specify format
David Wolever569a5fa2013-08-12 16:56:02 -04001183 string for a :class:`.datetime` object when using :meth:`str.format`. For a
1184 complete list of formatting directives, see
1185 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001186
1187
Christian Heimesfe337bf2008-03-23 21:54:12 +00001188Examples of working with datetime objects:
1189
1190.. doctest::
1191
Christian Heimes895627f2007-12-08 17:28:33 +00001192 >>> from datetime import datetime, date, time
1193 >>> # Using datetime.combine()
1194 >>> d = date(2005, 7, 14)
1195 >>> t = time(12, 30)
1196 >>> datetime.combine(d, t)
1197 datetime.datetime(2005, 7, 14, 12, 30)
1198 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001199 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001200 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001201 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001202 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1203 >>> # Using datetime.strptime()
1204 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1205 >>> dt
1206 datetime.datetime(2006, 11, 21, 16, 30)
1207 >>> # Using datetime.timetuple() to get tuple of all attributes
1208 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001209 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001210 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001211 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001212 2006 # year
1213 11 # month
1214 21 # day
1215 16 # hour
1216 30 # minute
1217 0 # second
1218 1 # weekday (0 = Monday)
1219 325 # number of days since 1st January
1220 -1 # dst - method tzinfo.dst() returned None
1221 >>> # Date in ISO format
1222 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001223 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001224 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001225 ...
1226 2006 # ISO year
1227 47 # ISO week
1228 2 # ISO weekday
1229 >>> # Formatting datetime
1230 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1231 'Tuesday, 21. November 2006 04:30PM'
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001232 >>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
1233 'The day is 21, the month is November, the time is 04:30PM.'
Christian Heimes895627f2007-12-08 17:28:33 +00001234
Christian Heimesfe337bf2008-03-23 21:54:12 +00001235Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001236
1237 >>> from datetime import timedelta, datetime, tzinfo
1238 >>> class GMT1(tzinfo):
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001239 ... def utcoffset(self, dt):
1240 ... return timedelta(hours=1) + self.dst(dt)
1241 ... def dst(self, dt):
1242 ... # DST starts last Sunday in March
Christian Heimes895627f2007-12-08 17:28:33 +00001243 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1244 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001245 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001246 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001247 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1248 ... return timedelta(hours=1)
1249 ... else:
1250 ... return timedelta(0)
1251 ... def tzname(self,dt):
1252 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001253 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001254 >>> class GMT2(tzinfo):
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001255 ... def utcoffset(self, dt):
1256 ... return timedelta(hours=2) + self.dst(dt)
1257 ... def dst(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001258 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001259 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001260 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001261 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001262 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001263 ... return timedelta(hours=1)
Christian Heimes895627f2007-12-08 17:28:33 +00001264 ... else:
1265 ... return timedelta(0)
1266 ... def tzname(self,dt):
1267 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001268 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001269 >>> gmt1 = GMT1()
1270 >>> # Daylight Saving Time
1271 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1272 >>> dt1.dst()
1273 datetime.timedelta(0)
1274 >>> dt1.utcoffset()
1275 datetime.timedelta(0, 3600)
1276 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1277 >>> dt2.dst()
1278 datetime.timedelta(0, 3600)
1279 >>> dt2.utcoffset()
1280 datetime.timedelta(0, 7200)
1281 >>> # Convert datetime to another time zone
1282 >>> dt3 = dt2.astimezone(GMT2())
1283 >>> dt3 # doctest: +ELLIPSIS
1284 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1285 >>> dt2 # doctest: +ELLIPSIS
1286 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1287 >>> dt2.utctimetuple() == dt3.utctimetuple()
1288 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001289
Christian Heimes895627f2007-12-08 17:28:33 +00001290
Georg Brandl116aa622007-08-15 14:28:22 +00001291
1292.. _datetime-time:
1293
1294:class:`time` Objects
1295---------------------
1296
1297A time object represents a (local) time of day, independent of any particular
1298day, and subject to adjustment via a :class:`tzinfo` object.
1299
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001300.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001301
1302 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001303 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001304 following ranges:
1305
1306 * ``0 <= hour < 24``
1307 * ``0 <= minute < 60``
1308 * ``0 <= second < 60``
1309 * ``0 <= microsecond < 1000000``.
1310
1311 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1312 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1313
1314Class attributes:
1315
1316
1317.. attribute:: time.min
1318
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001319 The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001320
1321
1322.. attribute:: time.max
1323
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001324 The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001325
1326
1327.. attribute:: time.resolution
1328
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001329 The smallest possible difference between non-equal :class:`.time` objects,
1330 ``timedelta(microseconds=1)``, although note that arithmetic on
1331 :class:`.time` objects is not supported.
Georg Brandl116aa622007-08-15 14:28:22 +00001332
Georg Brandl116aa622007-08-15 14:28:22 +00001333
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001334Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001335
1336.. attribute:: time.hour
1337
1338 In ``range(24)``.
1339
1340
1341.. attribute:: time.minute
1342
1343 In ``range(60)``.
1344
1345
1346.. attribute:: time.second
1347
1348 In ``range(60)``.
1349
1350
1351.. attribute:: time.microsecond
1352
1353 In ``range(1000000)``.
1354
1355
1356.. attribute:: time.tzinfo
1357
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001358 The object passed as the tzinfo argument to the :class:`.time` constructor, or
Georg Brandl116aa622007-08-15 14:28:22 +00001359 ``None`` if none was passed.
1360
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001361
Georg Brandl116aa622007-08-15 14:28:22 +00001362Supported operations:
1363
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001364* comparison of :class:`.time` to :class:`.time`, where *a* is considered less
Georg Brandl116aa622007-08-15 14:28:22 +00001365 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
Alexander Belopolsky08313822012-06-15 20:19:47 -04001366 is aware, :exc:`TypeError` is raised if an order comparison is attempted. For equality
1367 comparisons, naive instances are never equal to aware instances.
1368
1369 If both comparands are aware, and have
Senthil Kumarana6bac952011-07-04 11:28:30 -07001370 the same :attr:`tzinfo` attribute, the common :attr:`tzinfo` attribute is
1371 ignored and the base times are compared. If both comparands are aware and
1372 have different :attr:`tzinfo` attributes, the comparands are first adjusted by
1373 subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
1374 to stop mixed-type comparisons from falling back to the default comparison by
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001375 object address, when a :class:`.time` object is compared to an object of a
Senthil Kumaran3aac1792011-07-04 11:43:51 -07001376 different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
Senthil Kumarana6bac952011-07-04 11:28:30 -07001377 ``!=``. The latter cases return :const:`False` or :const:`True`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +00001378
Alexander Belopolsky08313822012-06-15 20:19:47 -04001379 .. versionchanged:: 3.3
Éric Araujob0f08952012-06-24 16:22:09 -04001380 Equality comparisons between naive and aware :class:`time` instances
1381 don't raise :exc:`TypeError`.
Alexander Belopolsky08313822012-06-15 20:19:47 -04001382
Georg Brandl116aa622007-08-15 14:28:22 +00001383* hash, use as dict key
1384
1385* efficient pickling
1386
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05001387In boolean contexts, a :class:`.time` object is always considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +00001388
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05001389.. versionchanged:: 3.5
1390 Before Python 3.5, a :class:`.time` object was considered to be false if it
1391 represented midnight in UTC. This behavior was considered obscure and
1392 error-prone and has been removed in Python 3.5. See :issue:`13936` for full
1393 details.
Georg Brandl116aa622007-08-15 14:28:22 +00001394
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001395Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001396
1397.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1398
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001399 Return a :class:`.time` with the same value, except for those attributes given
Senthil Kumarana6bac952011-07-04 11:28:30 -07001400 new values by whichever keyword arguments are specified. Note that
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001401 ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
1402 aware :class:`.time`, without conversion of the time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001403
1404
1405.. method:: time.isoformat()
1406
1407 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1408 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1409 6-character string is appended, giving the UTC offset in (signed) hours and
1410 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1411
1412
1413.. method:: time.__str__()
1414
1415 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1416
1417
1418.. method:: time.strftime(format)
1419
David Wolever569a5fa2013-08-12 16:56:02 -04001420 Return a string representing the time, controlled by an explicit format
1421 string. For a complete list of formatting directives, see
David Woleverbbf4a462013-08-12 17:15:36 -04001422 :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001423
1424
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001425.. method:: time.__format__(format)
1426
1427 Same as :meth:`.time.strftime`. This makes it possible to specify format string
David Wolever569a5fa2013-08-12 16:56:02 -04001428 for a :class:`.time` object when using :meth:`str.format`. For a
1429 complete list of formatting directives, see
1430 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001431
1432
Georg Brandl116aa622007-08-15 14:28:22 +00001433.. method:: time.utcoffset()
1434
1435 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1436 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1437 return ``None`` or a :class:`timedelta` object representing a whole number of
1438 minutes with magnitude less than one day.
1439
1440
1441.. method:: time.dst()
1442
1443 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1444 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1445 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1446 with magnitude less than one day.
1447
1448
1449.. method:: time.tzname()
1450
1451 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1452 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1453 return ``None`` or a string object.
1454
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001455
Christian Heimesfe337bf2008-03-23 21:54:12 +00001456Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001457
Christian Heimes895627f2007-12-08 17:28:33 +00001458 >>> from datetime import time, tzinfo
1459 >>> class GMT1(tzinfo):
1460 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001461 ... return timedelta(hours=1)
1462 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001463 ... return timedelta(0)
1464 ... def tzname(self,dt):
1465 ... return "Europe/Prague"
1466 ...
1467 >>> t = time(12, 10, 30, tzinfo=GMT1())
1468 >>> t # doctest: +ELLIPSIS
1469 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1470 >>> gmt = GMT1()
1471 >>> t.isoformat()
1472 '12:10:30+01:00'
1473 >>> t.dst()
1474 datetime.timedelta(0)
1475 >>> t.tzname()
1476 'Europe/Prague'
1477 >>> t.strftime("%H:%M:%S %Z")
1478 '12:10:30 Europe/Prague'
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001479 >>> 'The {} is {:%H:%M}.'.format("time", t)
1480 'The time is 12:10.'
Christian Heimes895627f2007-12-08 17:28:33 +00001481
Georg Brandl116aa622007-08-15 14:28:22 +00001482
1483.. _datetime-tzinfo:
1484
1485:class:`tzinfo` Objects
1486-----------------------
1487
Brett Cannone1327f72009-01-29 04:10:21 +00001488:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001489instantiated directly. You need to derive a concrete subclass, and (at least)
1490supply implementations of the standard :class:`tzinfo` methods needed by the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001491:class:`.datetime` methods you use. The :mod:`datetime` module supplies
Andrew Svetlovdfe109e2012-12-17 13:42:04 +02001492a simple concrete subclass of :class:`tzinfo` :class:`timezone` which can represent
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001493timezones with fixed offset from UTC such as UTC itself or North American EST and
1494EDT.
Georg Brandl116aa622007-08-15 14:28:22 +00001495
1496An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001497constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
Senthil Kumarana6bac952011-07-04 11:28:30 -07001498view their attributes as being in local time, and the :class:`tzinfo` object
Georg Brandl116aa622007-08-15 14:28:22 +00001499supports methods revealing offset of local time from UTC, the name of the time
1500zone, and DST offset, all relative to a date or time object passed to them.
1501
1502Special requirement for pickling: A :class:`tzinfo` subclass must have an
1503:meth:`__init__` method that can be called with no arguments, else it can be
1504pickled but possibly not unpickled again. This is a technical requirement that
1505may be relaxed in the future.
1506
1507A concrete subclass of :class:`tzinfo` may need to implement the following
1508methods. Exactly which methods are needed depends on the uses made of aware
1509:mod:`datetime` objects. If in doubt, simply implement all of them.
1510
1511
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001512.. method:: tzinfo.utcoffset(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001513
1514 Return offset of local time from UTC, in minutes east of UTC. If local time is
1515 west of UTC, this should be negative. Note that this is intended to be the
1516 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1517 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1518 the UTC offset isn't known, return ``None``. Else the value returned must be a
1519 :class:`timedelta` object specifying a whole number of minutes in the range
1520 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1521 than one day). Most implementations of :meth:`utcoffset` will probably look
1522 like one of these two::
1523
1524 return CONSTANT # fixed-offset class
1525 return CONSTANT + self.dst(dt) # daylight-aware class
1526
1527 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1528 ``None`` either.
1529
1530 The default implementation of :meth:`utcoffset` raises
1531 :exc:`NotImplementedError`.
1532
1533
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001534.. method:: tzinfo.dst(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001535
1536 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1537 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1538 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1539 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1540 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1541 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1542 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -07001543 attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
1544 should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
1545 DST changes when crossing time zones.
Georg Brandl116aa622007-08-15 14:28:22 +00001546
1547 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1548 daylight times must be consistent in this sense:
1549
1550 ``tz.utcoffset(dt) - tz.dst(dt)``
1551
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001552 must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo ==
Georg Brandl116aa622007-08-15 14:28:22 +00001553 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1554 zone's "standard offset", which should not depend on the date or the time, but
1555 only on geographic location. The implementation of :meth:`datetime.astimezone`
1556 relies on this, but cannot detect violations; it's the programmer's
1557 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1558 this, it may be able to override the default implementation of
1559 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1560
1561 Most implementations of :meth:`dst` will probably look like one of these two::
1562
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001563 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001564 # a fixed-offset class: doesn't account for DST
1565 return timedelta(0)
1566
1567 or ::
1568
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001569 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001570 # Code to set dston and dstoff to the time zone's DST
1571 # transition times based on the input dt.year, and expressed
1572 # in standard local time. Then
1573
1574 if dston <= dt.replace(tzinfo=None) < dstoff:
1575 return timedelta(hours=1)
1576 else:
1577 return timedelta(0)
1578
1579 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1580
1581
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001582.. method:: tzinfo.tzname(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001583
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001584 Return the time zone name corresponding to the :class:`.datetime` object *dt*, as
Georg Brandl116aa622007-08-15 14:28:22 +00001585 a string. Nothing about string names is defined by the :mod:`datetime` module,
1586 and there's no requirement that it mean anything in particular. For example,
1587 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1588 valid replies. Return ``None`` if a string name isn't known. Note that this is
1589 a method rather than a fixed string primarily because some :class:`tzinfo`
1590 subclasses will wish to return different names depending on the specific value
1591 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1592 daylight time.
1593
1594 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1595
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001596
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001597These methods are called by a :class:`.datetime` or :class:`.time` object, in
1598response to their methods of the same names. A :class:`.datetime` object passes
1599itself as the argument, and a :class:`.time` object passes ``None`` as the
Georg Brandl116aa622007-08-15 14:28:22 +00001600argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001601accept a *dt* argument of ``None``, or of class :class:`.datetime`.
Georg Brandl116aa622007-08-15 14:28:22 +00001602
1603When ``None`` is passed, it's up to the class designer to decide the best
1604response. For example, returning ``None`` is appropriate if the class wishes to
1605say that time objects don't participate in the :class:`tzinfo` protocols. It
1606may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1607there is no other convention for discovering the standard offset.
1608
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001609When a :class:`.datetime` object is passed in response to a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +00001610method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1611rely on this, unless user code calls :class:`tzinfo` methods directly. The
1612intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1613time, and not need worry about objects in other timezones.
1614
1615There is one more :class:`tzinfo` method that a subclass may wish to override:
1616
1617
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001618.. method:: tzinfo.fromutc(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001619
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001620 This is called from the default :class:`datetime.astimezone()`
1621 implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s
1622 date and time data are to be viewed as expressing a UTC time. The purpose
1623 of :meth:`fromutc` is to adjust the date and time data, returning an
Senthil Kumarana6bac952011-07-04 11:28:30 -07001624 equivalent datetime in *self*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00001625
1626 Most :class:`tzinfo` subclasses should be able to inherit the default
1627 :meth:`fromutc` implementation without problems. It's strong enough to handle
1628 fixed-offset time zones, and time zones accounting for both standard and
1629 daylight time, and the latter even if the DST transition times differ in
1630 different years. An example of a time zone the default :meth:`fromutc`
1631 implementation may not handle correctly in all cases is one where the standard
1632 offset (from UTC) depends on the specific date and time passed, which can happen
1633 for political reasons. The default implementations of :meth:`astimezone` and
1634 :meth:`fromutc` may not produce the result you want if the result is one of the
1635 hours straddling the moment the standard offset changes.
1636
1637 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1638 like::
1639
1640 def fromutc(self, dt):
1641 # raise ValueError error if dt.tzinfo is not self
1642 dtoff = dt.utcoffset()
1643 dtdst = dt.dst()
1644 # raise ValueError if dtoff is None or dtdst is None
1645 delta = dtoff - dtdst # this is self's standard offset
1646 if delta:
1647 dt += delta # convert to standard local time
1648 dtdst = dt.dst()
1649 # raise ValueError if dtdst is None
1650 if dtdst:
1651 return dt + dtdst
1652 else:
1653 return dt
1654
1655Example :class:`tzinfo` classes:
1656
1657.. literalinclude:: ../includes/tzinfo-examples.py
1658
Georg Brandl116aa622007-08-15 14:28:22 +00001659Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1660subclass accounting for both standard and daylight time, at the DST transition
1661points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00001662minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
16631:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001664
1665 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1666 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1667 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1668
1669 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1670
1671 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1672
1673When DST starts (the "start" line), the local wall clock leaps from 1:59 to
16743:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1675``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1676begins. In order for :meth:`astimezone` to make this guarantee, the
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001677:meth:`tzinfo.dst` method must consider times in the "missing hour" (2:MM for
Georg Brandl116aa622007-08-15 14:28:22 +00001678Eastern) to be in daylight time.
1679
1680When DST ends (the "end" line), there's a potentially worse problem: there's an
1681hour that can't be spelled unambiguously in local wall time: the last hour of
1682daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1683daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1684to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1685:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1686hours into the same local hour then. In the Eastern example, UTC times of the
1687form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1688:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1689consider times in the "repeated hour" to be in standard time. This is easily
1690arranged, as in the example, by expressing DST switch times in the time zone's
1691standard local time.
1692
1693Applications that can't bear such ambiguities should avoid using hybrid
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001694:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`,
1695or any other fixed-offset :class:`tzinfo` subclass (such as a class representing
1696only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
1697
Sandro Tosid11d0d62012-04-24 19:46:06 +02001698.. seealso::
1699
Georg Brandle73778c2014-10-29 08:36:35 +01001700 `pytz <https://pypi.python.org/pypi/pytz/>`_
Benjamin Peterson9b29acd2014-06-22 16:26:39 -07001701 The standard library has :class:`timezone` class for handling arbitrary
1702 fixed offsets from UTC and :attr:`timezone.utc` as UTC timezone instance.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001703
Benjamin Peterson9b29acd2014-06-22 16:26:39 -07001704 *pytz* library brings the *IANA timezone database* (also known as the
1705 Olson database) to Python and its usage is recommended.
Sandro Tosi100b8892012-04-28 11:19:37 +02001706
1707 `IANA timezone database <http://www.iana.org/time-zones>`_
1708 The Time Zone Database (often called tz or zoneinfo) contains code and
1709 data that represent the history of local time for many representative
1710 locations around the globe. It is updated periodically to reflect changes
1711 made by political bodies to time zone boundaries, UTC offsets, and
1712 daylight-saving rules.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001713
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001714
1715.. _datetime-timezone:
1716
1717:class:`timezone` Objects
1718--------------------------
1719
Alexander Belopolsky6d3c9a62011-05-04 10:28:26 -04001720The :class:`timezone` class is a subclass of :class:`tzinfo`, each
1721instance of which represents a timezone defined by a fixed offset from
1722UTC. Note that objects of this class cannot be used to represent
1723timezone information in the locations where different offsets are used
1724in different days of the year or where historical changes have been
1725made to civil time.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001726
1727
1728.. class:: timezone(offset[, name])
1729
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001730 The *offset* argument must be specified as a :class:`timedelta`
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001731 object representing the difference between the local time and UTC. It must
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001732 be strictly between ``-timedelta(hours=24)`` and
1733 ``timedelta(hours=24)`` and represent a whole number of minutes,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001734 otherwise :exc:`ValueError` is raised.
1735
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001736 The *name* argument is optional. If specified it must be a string that
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04001737 will be used as the value returned by the :meth:`datetime.tzname` method.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001738
Benjamin Peterson9b29acd2014-06-22 16:26:39 -07001739 .. versionadded:: 3.2
1740
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001741.. method:: timezone.utcoffset(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001742
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001743 Return the fixed value specified when the :class:`timezone` instance is
1744 constructed. The *dt* argument is ignored. The return value is a
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001745 :class:`timedelta` instance equal to the difference between the
1746 local time and UTC.
1747
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001748.. method:: timezone.tzname(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001749
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04001750 Return the fixed value specified when the :class:`timezone` instance
1751 is constructed. If *name* is not provided in the constructor, the
1752 name returned by ``tzname(dt)`` is generated from the value of the
1753 ``offset`` as follows. If *offset* is ``timedelta(0)``, the name
1754 is "UTC", otherwise it is a string 'UTC±HH:MM', where ± is the sign
1755 of ``offset``, HH and MM are two digits of ``offset.hours`` and
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001756 ``offset.minutes`` respectively.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001757
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04001758 .. versionchanged:: 3.6
Berker Peksagdf326eb2015-09-09 18:32:50 +03001759 Name generated from ``offset=timedelta(0)`` is now plain 'UTC', not
1760 'UTC+00:00'.
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04001761
1762
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001763.. method:: timezone.dst(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001764
1765 Always returns ``None``.
1766
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001767.. method:: timezone.fromutc(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001768
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001769 Return ``dt + offset``. The *dt* argument must be an aware
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001770 :class:`.datetime` instance, with ``tzinfo`` set to ``self``.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001771
1772Class attributes:
1773
1774.. attribute:: timezone.utc
1775
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001776 The UTC timezone, ``timezone(timedelta(0))``.
Georg Brandl48310cd2009-01-03 21:18:54 +00001777
Georg Brandl116aa622007-08-15 14:28:22 +00001778
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001779.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00001780
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001781:meth:`strftime` and :meth:`strptime` Behavior
1782----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001783
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001784:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
Georg Brandl116aa622007-08-15 14:28:22 +00001785``strftime(format)`` method, to create a string representing the time under the
1786control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1787acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1788although not all objects support a :meth:`timetuple` method.
1789
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001790Conversely, the :meth:`datetime.strptime` class method creates a
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001791:class:`.datetime` object from a string representing a date and time and a
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001792corresponding format string. ``datetime.strptime(date_string, format)`` is
1793equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1794
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001795For :class:`.time` objects, the format codes for year, month, and day should not
Georg Brandl116aa622007-08-15 14:28:22 +00001796be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001797is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00001798
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001799For :class:`date` objects, the format codes for hours, minutes, seconds, and
1800microseconds should not be used, as :class:`date` objects have no such
1801values. If they're used anyway, ``0`` is substituted for them.
1802
Georg Brandl116aa622007-08-15 14:28:22 +00001803The full set of format codes supported varies across platforms, because Python
1804calls the platform C library's :func:`strftime` function, and platform
Georg Brandlb7117af2013-10-13 18:28:25 +02001805variations are common. To see the full set of format codes supported on your
1806platform, consult the :manpage:`strftime(3)` documentation.
Christian Heimes895627f2007-12-08 17:28:33 +00001807
1808The following is a list of all the format codes that the C standard (1989
1809version) requires, and these work on all platforms with a standard C
1810implementation. Note that the 1999 version of the C standard added additional
1811format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001812
David Wolever569a5fa2013-08-12 16:56:02 -04001813+-----------+--------------------------------+------------------------+-------+
1814| Directive | Meaning | Example | Notes |
1815+===========+================================+========================+=======+
1816| ``%a`` | Weekday as locale's || Sun, Mon, ..., Sat | \(1) |
1817| | abbreviated name. | (en_US); | |
1818| | || So, Mo, ..., Sa | |
1819| | | (de_DE) | |
1820+-----------+--------------------------------+------------------------+-------+
1821| ``%A`` | Weekday as locale's full name. || Sunday, Monday, ..., | \(1) |
1822| | | Saturday (en_US); | |
1823| | || Sonntag, Montag, ..., | |
1824| | | Samstag (de_DE) | |
1825+-----------+--------------------------------+------------------------+-------+
1826| ``%w`` | Weekday as a decimal number, | 0, 1, ..., 6 | |
1827| | where 0 is Sunday and 6 is | | |
1828| | Saturday. | | |
1829+-----------+--------------------------------+------------------------+-------+
1830| ``%d`` | Day of the month as a | 01, 02, ..., 31 | |
1831| | zero-padded decimal number. | | |
1832+-----------+--------------------------------+------------------------+-------+
1833| ``%b`` | Month as locale's abbreviated || Jan, Feb, ..., Dec | \(1) |
1834| | name. | (en_US); | |
1835| | || Jan, Feb, ..., Dez | |
1836| | | (de_DE) | |
1837+-----------+--------------------------------+------------------------+-------+
1838| ``%B`` | Month as locale's full name. || January, February, | \(1) |
1839| | | ..., December (en_US);| |
1840| | || Januar, Februar, ..., | |
1841| | | Dezember (de_DE) | |
1842+-----------+--------------------------------+------------------------+-------+
1843| ``%m`` | Month as a zero-padded | 01, 02, ..., 12 | |
1844| | decimal number. | | |
1845+-----------+--------------------------------+------------------------+-------+
1846| ``%y`` | Year without century as a | 00, 01, ..., 99 | |
1847| | zero-padded decimal number. | | |
1848+-----------+--------------------------------+------------------------+-------+
1849| ``%Y`` | Year with century as a decimal | 0001, 0002, ..., 2013, | \(2) |
David Wolever5d07e702013-08-14 14:41:48 -04001850| | number. | 2014, ..., 9998, 9999 | |
David Wolever569a5fa2013-08-12 16:56:02 -04001851+-----------+--------------------------------+------------------------+-------+
1852| ``%H`` | Hour (24-hour clock) as a | 00, 01, ..., 23 | |
1853| | zero-padded decimal number. | | |
1854+-----------+--------------------------------+------------------------+-------+
1855| ``%I`` | Hour (12-hour clock) as a | 01, 02, ..., 12 | |
1856| | zero-padded decimal number. | | |
1857+-----------+--------------------------------+------------------------+-------+
1858| ``%p`` | Locale's equivalent of either || AM, PM (en_US); | \(1), |
1859| | AM or PM. || am, pm (de_DE) | \(3) |
1860+-----------+--------------------------------+------------------------+-------+
1861| ``%M`` | Minute as a zero-padded | 00, 01, ..., 59 | |
1862| | decimal number. | | |
1863+-----------+--------------------------------+------------------------+-------+
1864| ``%S`` | Second as a zero-padded | 00, 01, ..., 59 | \(4) |
1865| | decimal number. | | |
1866+-----------+--------------------------------+------------------------+-------+
1867| ``%f`` | Microsecond as a decimal | 000000, 000001, ..., | \(5) |
1868| | number, zero-padded on the | 999999 | |
1869| | left. | | |
1870+-----------+--------------------------------+------------------------+-------+
1871| ``%z`` | UTC offset in the form +HHMM | (empty), +0000, -0400, | \(6) |
1872| | or -HHMM (empty string if the | +1030 | |
1873| | the object is naive). | | |
1874+-----------+--------------------------------+------------------------+-------+
1875| ``%Z`` | Time zone name (empty string | (empty), UTC, EST, CST | |
1876| | if the object is naive). | | |
1877+-----------+--------------------------------+------------------------+-------+
1878| ``%j`` | Day of the year as a | 001, 002, ..., 366 | |
1879| | zero-padded decimal number. | | |
1880+-----------+--------------------------------+------------------------+-------+
1881| ``%U`` | Week number of the year | 00, 01, ..., 53 | \(7) |
1882| | (Sunday as the first day of | | |
1883| | the week) as a zero padded | | |
1884| | decimal number. All days in a | | |
1885| | new year preceding the first | | |
1886| | Sunday are considered to be in | | |
1887| | week 0. | | |
1888+-----------+--------------------------------+------------------------+-------+
1889| ``%W`` | Week number of the year | 00, 01, ..., 53 | \(7) |
1890| | (Monday as the first day of | | |
1891| | the week) as a decimal number. | | |
1892| | All days in a new year | | |
1893| | preceding the first Monday | | |
1894| | are considered to be in | | |
1895| | week 0. | | |
1896+-----------+--------------------------------+------------------------+-------+
1897| ``%c`` | Locale's appropriate date and || Tue Aug 16 21:30:00 | \(1) |
1898| | time representation. | 1988 (en_US); | |
1899| | || Di 16 Aug 21:30:00 | |
1900| | | 1988 (de_DE) | |
1901+-----------+--------------------------------+------------------------+-------+
1902| ``%x`` | Locale's appropriate date || 08/16/88 (None); | \(1) |
1903| | representation. || 08/16/1988 (en_US); | |
1904| | || 16.08.1988 (de_DE) | |
1905+-----------+--------------------------------+------------------------+-------+
1906| ``%X`` | Locale's appropriate time || 21:30:00 (en_US); | \(1) |
1907| | representation. || 21:30:00 (de_DE) | |
1908+-----------+--------------------------------+------------------------+-------+
1909| ``%%`` | A literal ``'%'`` character. | % | |
1910+-----------+--------------------------------+------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001911
Alexander Belopolsky68713e42015-10-06 13:29:56 -04001912Several additional directives not required by the C89 standard are included for
1913convenience. These parameters all correspond to ISO 8601 date values. These
1914may not be available on all platforms when used with the :meth:`strftime`
1915method. The ISO 8601 year and ISO 8601 week directives are not interchangeable
1916with the year and week number directives above. Calling :meth:`strptime` with
1917incomplete or ambiguous ISO 8601 directives will raise a :exc:`ValueError`.
1918
1919+-----------+--------------------------------+------------------------+-------+
1920| Directive | Meaning | Example | Notes |
1921+===========+================================+========================+=======+
1922| ``%G`` | ISO 8601 year with century | 0001, 0002, ..., 2013, | \(8) |
1923| | representing the year that | 2014, ..., 9998, 9999 | |
1924| | contains the greater part of | | |
1925| | the ISO week (``%V``). | | |
1926+-----------+--------------------------------+------------------------+-------+
1927| ``%u`` | ISO 8601 weekday as a decimal | 1, 2, ..., 7 | |
1928| | number where 1 is Monday. | | |
1929+-----------+--------------------------------+------------------------+-------+
1930| ``%V`` | ISO 8601 week as a decimal | 01, 02, ..., 53 | \(8) |
1931| | number with Monday as | | |
1932| | the first day of the week. | | |
1933| | Week 01 is the week containing | | |
1934| | Jan 4. | | |
1935+-----------+--------------------------------+------------------------+-------+
1936
1937.. versionadded:: 3.6
1938 ``%G``, ``%u`` and ``%V`` were added.
1939
Christian Heimes895627f2007-12-08 17:28:33 +00001940Notes:
1941
1942(1)
David Wolever569a5fa2013-08-12 16:56:02 -04001943 Because the format depends on the current locale, care should be taken when
1944 making assumptions about the output value. Field orderings will vary (for
1945 example, "month/day/year" versus "day/month/year"), and the output may
1946 contain Unicode characters encoded using the locale's default encoding (for
Georg Brandlad321532013-10-29 08:05:10 +01001947 example, if the current locale is ``ja_JP``, the default encoding could be
David Wolever569a5fa2013-08-12 16:56:02 -04001948 any one of ``eucJP``, ``SJIS``, or ``utf-8``; use :meth:`locale.getlocale`
1949 to determine the current locale's encoding).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001950
1951(2)
David Wolever569a5fa2013-08-12 16:56:02 -04001952 The :meth:`strptime` method can parse years in the full [1, 9999] range, but
1953 years < 1000 must be zero-filled to 4-digit width.
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001954
1955 .. versionchanged:: 3.2
1956 In previous versions, :meth:`strftime` method was restricted to
1957 years >= 1900.
1958
Alexander Belopolsky5611a1c2011-05-02 14:14:48 -04001959 .. versionchanged:: 3.3
1960 In version 3.2, :meth:`strftime` method was restricted to
1961 years >= 1000.
1962
David Wolever569a5fa2013-08-12 16:56:02 -04001963(3)
1964 When used with the :meth:`strptime` method, the ``%p`` directive only affects
1965 the output hour field if the ``%I`` directive is used to parse the hour.
Alexander Belopolskyca94f552010-06-17 18:30:34 +00001966
David Wolever569a5fa2013-08-12 16:56:02 -04001967(4)
1968 Unlike the :mod:`time` module, the :mod:`datetime` module does not support
1969 leap seconds.
1970
1971(5)
1972 When used with the :meth:`strptime` method, the ``%f`` directive
1973 accepts from one to six digits and zero pads on the right. ``%f`` is
1974 an extension to the set of format characters in the C standard (but
1975 implemented separately in datetime objects, and therefore always
1976 available).
1977
1978(6)
1979 For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1980 strings.
1981
1982 For an aware object:
1983
1984 ``%z``
1985 :meth:`utcoffset` is transformed into a 5-character string of the form
1986 +HHMM or -HHMM, where HH is a 2-digit string giving the number of UTC
1987 offset hours, and MM is a 2-digit string giving the number of UTC offset
1988 minutes. For example, if :meth:`utcoffset` returns
1989 ``timedelta(hours=-3, minutes=-30)``, ``%z`` is replaced with the string
1990 ``'-0330'``.
1991
1992 ``%Z``
1993 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty
1994 string. Otherwise ``%Z`` is replaced by the returned value, which must
1995 be a string.
1996
1997 .. versionchanged:: 3.2
1998 When the ``%z`` directive is provided to the :meth:`strptime` method, an
1999 aware :class:`.datetime` object will be produced. The ``tzinfo`` of the
2000 result will be set to a :class:`timezone` instance.
2001
2002(7)
2003 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used
Alexander Belopolsky68713e42015-10-06 13:29:56 -04002004 in calculations when the day of the week and the calendar year (``%Y``)
2005 are specified.
2006
2007(8)
2008 Similar to ``%U`` and ``%W``, ``%V`` is only used in calculations when the
2009 day of the week and the ISO year (``%G``) are specified in a
2010 :meth:`strptime` format string. Also note that ``%G`` and ``%Y`` are not
2011 interchangable.
R David Murray9075d8b2012-05-14 22:14:46 -04002012
2013.. rubric:: Footnotes
2014
2015.. [#] If, that is, we ignore the effects of Relativity