blob: 7a9f93cd238fe85531b251351efa8fb67666bf4c [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
669:class:`datetime` Objects
670-------------------------
671
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.
Georg Brandl116aa622007-08-15 14:28:22 +0000762 It's common for this to be restricted to years in 1970 through 2038. See also
763 :meth:`fromtimestamp`.
764
Alexander Belopolsky54afa552011-04-25 13:00:40 -0400765 On the POSIX compliant platforms, ``utcfromtimestamp(timestamp)``
766 is equivalent to the following expression::
767
768 datetime(1970, 1, 1) + timedelta(seconds=timestamp)
769
Victor Stinner5d272cc2012-03-13 13:35:55 +0100770 .. versionchanged:: 3.3
771 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
772 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100773 :c:func:`gmtime` function. Raise :exc:`OSError` instead of
774 :exc:`ValueError` on :c:func:`gmtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100775
Georg Brandl116aa622007-08-15 14:28:22 +0000776
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000777.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000778
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300779 Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal,
Georg Brandl116aa622007-08-15 14:28:22 +0000780 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
781 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
782 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
783
784
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000785.. classmethod:: datetime.combine(date, time)
Georg Brandl116aa622007-08-15 14:28:22 +0000786
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300787 Return a new :class:`.datetime` object whose date components are equal to the
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800788 given :class:`date` object's, and whose time components and :attr:`tzinfo`
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300789 attributes are equal to the given :class:`.time` object's. For any
790 :class:`.datetime` object *d*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800791 ``d == datetime.combine(d.date(), d.timetz())``. If date is a
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300792 :class:`.datetime` object, its time components and :attr:`tzinfo` attributes
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800793 are ignored.
Georg Brandl116aa622007-08-15 14:28:22 +0000794
795
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000796.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000797
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300798 Return a :class:`.datetime` corresponding to *date_string*, parsed according to
Georg Brandl116aa622007-08-15 14:28:22 +0000799 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
800 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
801 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 -0400802 time tuple. For a complete list of formatting directives, see
803 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000804
Georg Brandl116aa622007-08-15 14:28:22 +0000805
Georg Brandl116aa622007-08-15 14:28:22 +0000806
807Class attributes:
808
Georg Brandl116aa622007-08-15 14:28:22 +0000809.. attribute:: datetime.min
810
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300811 The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1,
Georg Brandl116aa622007-08-15 14:28:22 +0000812 tzinfo=None)``.
813
814
815.. attribute:: datetime.max
816
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300817 The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
Georg Brandl116aa622007-08-15 14:28:22 +0000818 59, 999999, tzinfo=None)``.
819
820
821.. attribute:: datetime.resolution
822
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300823 The smallest possible difference between non-equal :class:`.datetime` objects,
Georg Brandl116aa622007-08-15 14:28:22 +0000824 ``timedelta(microseconds=1)``.
825
Georg Brandl116aa622007-08-15 14:28:22 +0000826
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000827Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000828
829.. attribute:: datetime.year
830
831 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
832
833
834.. attribute:: datetime.month
835
836 Between 1 and 12 inclusive.
837
838
839.. attribute:: datetime.day
840
841 Between 1 and the number of days in the given month of the given year.
842
843
844.. attribute:: datetime.hour
845
846 In ``range(24)``.
847
848
849.. attribute:: datetime.minute
850
851 In ``range(60)``.
852
853
854.. attribute:: datetime.second
855
856 In ``range(60)``.
857
858
859.. attribute:: datetime.microsecond
860
861 In ``range(1000000)``.
862
863
864.. attribute:: datetime.tzinfo
865
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300866 The object passed as the *tzinfo* argument to the :class:`.datetime` constructor,
Georg Brandl116aa622007-08-15 14:28:22 +0000867 or ``None`` if none was passed.
868
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000869
Georg Brandl116aa622007-08-15 14:28:22 +0000870Supported operations:
871
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300872+---------------------------------------+--------------------------------+
873| Operation | Result |
874+=======================================+================================+
875| ``datetime2 = datetime1 + timedelta`` | \(1) |
876+---------------------------------------+--------------------------------+
877| ``datetime2 = datetime1 - timedelta`` | \(2) |
878+---------------------------------------+--------------------------------+
879| ``timedelta = datetime1 - datetime2`` | \(3) |
880+---------------------------------------+--------------------------------+
881| ``datetime1 < datetime2`` | Compares :class:`.datetime` to |
882| | :class:`.datetime`. (4) |
883+---------------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000884
885(1)
886 datetime2 is a duration of timedelta removed from datetime1, moving forward in
887 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
Senthil Kumarana6bac952011-07-04 11:28:30 -0700888 result has the same :attr:`tzinfo` attribute as the input datetime, and
889 datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
890 datetime2.year would be smaller than :const:`MINYEAR` or larger than
891 :const:`MAXYEAR`. Note that no time zone adjustments are done even if the
892 input is an aware object.
Georg Brandl116aa622007-08-15 14:28:22 +0000893
894(2)
895 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
Senthil Kumarana6bac952011-07-04 11:28:30 -0700896 addition, the result has the same :attr:`tzinfo` attribute as the input
897 datetime, and no time zone adjustments are done even if the input is aware.
898 This isn't quite equivalent to datetime1 + (-timedelta), because -timedelta
899 in isolation can overflow in cases where datetime1 - timedelta does not.
Georg Brandl116aa622007-08-15 14:28:22 +0000900
901(3)
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300902 Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if
Georg Brandl116aa622007-08-15 14:28:22 +0000903 both operands are naive, or if both are aware. If one is aware and the other is
904 naive, :exc:`TypeError` is raised.
905
Senthil Kumarana6bac952011-07-04 11:28:30 -0700906 If both are naive, or both are aware and have the same :attr:`tzinfo` attribute,
907 the :attr:`tzinfo` attributes are ignored, and the result is a :class:`timedelta`
Georg Brandl116aa622007-08-15 14:28:22 +0000908 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
909 are done in this case.
910
Senthil Kumarana6bac952011-07-04 11:28:30 -0700911 If both are aware and have different :attr:`tzinfo` attributes, ``a-b`` acts
912 as if *a* and *b* were first converted to naive UTC datetimes first. The
913 result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
914 - b.utcoffset())`` except that the implementation never overflows.
Georg Brandl116aa622007-08-15 14:28:22 +0000915
916(4)
917 *datetime1* is considered less than *datetime2* when *datetime1* precedes
918 *datetime2* in time.
919
Alexander Belopolsky08313822012-06-15 20:19:47 -0400920 If one comparand is naive and the other is aware, :exc:`TypeError`
921 is raised if an order comparison is attempted. For equality
922 comparisons, naive instances are never equal to aware instances.
923
Senthil Kumarana6bac952011-07-04 11:28:30 -0700924 If both comparands are aware, and have the same :attr:`tzinfo` attribute, the
925 common :attr:`tzinfo` attribute is ignored and the base datetimes are
926 compared. If both comparands are aware and have different :attr:`tzinfo`
927 attributes, the comparands are first adjusted by subtracting their UTC
928 offsets (obtained from ``self.utcoffset()``).
Georg Brandl116aa622007-08-15 14:28:22 +0000929
Alexander Belopolsky08313822012-06-15 20:19:47 -0400930 .. versionchanged:: 3.3
Éric Araujob0f08952012-06-24 16:22:09 -0400931 Equality comparisons between naive and aware :class:`datetime`
932 instances don't raise :exc:`TypeError`.
Alexander Belopolsky08313822012-06-15 20:19:47 -0400933
Georg Brandl116aa622007-08-15 14:28:22 +0000934 .. note::
935
936 In order to stop comparison from falling back to the default scheme of comparing
937 object addresses, datetime comparison normally raises :exc:`TypeError` if the
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300938 other comparand isn't also a :class:`.datetime` object. However,
Georg Brandl116aa622007-08-15 14:28:22 +0000939 ``NotImplemented`` is returned instead if the other comparand has a
940 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300941 chance at implementing mixed-type comparison. If not, when a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +0000942 object is compared to an object of a different type, :exc:`TypeError` is raised
943 unless the comparison is ``==`` or ``!=``. The latter cases return
944 :const:`False` or :const:`True`, respectively.
945
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300946:class:`.datetime` objects can be used as dictionary keys. In Boolean contexts,
947all :class:`.datetime` objects are considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +0000948
949Instance methods:
950
Georg Brandl116aa622007-08-15 14:28:22 +0000951.. method:: datetime.date()
952
953 Return :class:`date` object with same year, month and day.
954
955
956.. method:: datetime.time()
957
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300958 Return :class:`.time` object with same hour, minute, second and microsecond.
Georg Brandl116aa622007-08-15 14:28:22 +0000959 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
960
961
962.. method:: datetime.timetz()
963
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300964 Return :class:`.time` object with same hour, minute, second, microsecond, and
Senthil Kumarana6bac952011-07-04 11:28:30 -0700965 tzinfo attributes. See also method :meth:`time`.
Georg Brandl116aa622007-08-15 14:28:22 +0000966
967
968.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
969
Senthil Kumarana6bac952011-07-04 11:28:30 -0700970 Return a datetime with the same attributes, except for those attributes given
971 new values by whichever keyword arguments are specified. Note that
972 ``tzinfo=None`` can be specified to create a naive datetime from an aware
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800973 datetime with no conversion of date and time data.
Georg Brandl116aa622007-08-15 14:28:22 +0000974
975
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -0400976.. method:: datetime.astimezone(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000977
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -0400978 Return a :class:`datetime` object with new :attr:`tzinfo` attribute *tz*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800979 adjusting the date and time data so the result is the same UTC time as
Senthil Kumarana6bac952011-07-04 11:28:30 -0700980 *self*, but in *tz*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +0000981
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -0400982 If provided, *tz* must be an instance of a :class:`tzinfo` subclass, and its
Georg Brandl116aa622007-08-15 14:28:22 +0000983 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
984 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
985 not return ``None``).
986
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -0400987 If called without arguments (or with ``tz=None``) the system local
988 timezone is assumed. The ``tzinfo`` attribute of the converted
989 datetime instance will be set to an instance of :class:`timezone`
990 with the zone name and offset obtained from the OS.
991
Georg Brandl116aa622007-08-15 14:28:22 +0000992 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800993 adjustment of date or time data is performed. Else the result is local
Senthil Kumarana6bac952011-07-04 11:28:30 -0700994 time in time zone *tz*, representing the same UTC time as *self*: after
995 ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800996 the same date and time data as ``dt - dt.utcoffset()``. The discussion
Senthil Kumarana6bac952011-07-04 11:28:30 -0700997 of class :class:`tzinfo` explains the cases at Daylight Saving Time transition
998 boundaries where this cannot be achieved (an issue only if *tz* models both
999 standard and daylight time).
Georg Brandl116aa622007-08-15 14:28:22 +00001000
1001 If you merely want to attach a time zone object *tz* to a datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001002 adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you
Georg Brandl116aa622007-08-15 14:28:22 +00001003 merely want to remove the time zone object from an aware datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001004 conversion of date and time data, use ``dt.replace(tzinfo=None)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001005
1006 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
1007 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
1008 Ignoring error cases, :meth:`astimezone` acts like::
1009
1010 def astimezone(self, tz):
1011 if self.tzinfo is tz:
1012 return self
1013 # Convert self to UTC, and attach the new time zone object.
1014 utc = (self - self.utcoffset()).replace(tzinfo=tz)
1015 # Convert from UTC to tz's local time.
1016 return tz.fromutc(utc)
1017
Georg Brandlee0be402012-06-26 09:14:40 +02001018 .. versionchanged:: 3.3
1019 *tz* now can be omitted.
1020
Georg Brandl116aa622007-08-15 14:28:22 +00001021
1022.. method:: datetime.utcoffset()
1023
1024 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1025 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
1026 return ``None``, or a :class:`timedelta` object representing a whole number of
1027 minutes with magnitude less than one day.
1028
1029
1030.. method:: datetime.dst()
1031
1032 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1033 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
1034 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1035 with magnitude less than one day.
1036
1037
1038.. method:: datetime.tzname()
1039
1040 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1041 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
1042 ``None`` or a string object,
1043
1044
1045.. method:: datetime.timetuple()
1046
1047 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
1048 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
Alexander Belopolsky64912482010-06-08 18:59:20 +00001049 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
1050 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
1051 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
1052 of the result is set according to the :meth:`dst` method: :attr:`tzinfo` is
Georg Brandl682d7e02010-10-06 10:26:05 +00001053 ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
Alexander Belopolsky64912482010-06-08 18:59:20 +00001054 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
Alexander Belopolskyda62f2f2010-06-09 17:11:01 +00001055 else :attr:`tm_isdst` is set to ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +00001056
1057
1058.. method:: datetime.utctimetuple()
1059
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001060 If :class:`.datetime` instance *d* is naive, this is the same as
Georg Brandl116aa622007-08-15 14:28:22 +00001061 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
1062 ``d.dst()`` returns. DST is never in effect for a UTC time.
1063
1064 If *d* is aware, *d* is normalized to UTC time, by subtracting
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00001065 ``d.utcoffset()``, and a :class:`time.struct_time` for the
1066 normalized time is returned. :attr:`tm_isdst` is forced to 0. Note
1067 that an :exc:`OverflowError` may be raised if *d*.year was
1068 ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
Georg Brandl116aa622007-08-15 14:28:22 +00001069 boundary.
1070
1071
1072.. method:: datetime.toordinal()
1073
1074 Return the proleptic Gregorian ordinal of the date. The same as
1075 ``self.date().toordinal()``.
1076
Alexander Belopolskya4415142012-06-08 12:33:09 -04001077.. method:: datetime.timestamp()
1078
1079 Return POSIX timestamp corresponding to the :class:`datetime`
1080 instance. The return value is a :class:`float` similar to that
1081 returned by :func:`time.time`.
1082
1083 Naive :class:`datetime` instances are assumed to represent local
1084 time and this method relies on the platform C :c:func:`mktime`
1085 function to perform the conversion. Since :class:`datetime`
1086 supports wider range of values than :c:func:`mktime` on many
1087 platforms, this method may raise :exc:`OverflowError` for times far
1088 in the past or far in the future.
1089
1090 For aware :class:`datetime` instances, the return value is computed
1091 as::
1092
1093 (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
1094
1095 .. versionadded:: 3.3
1096
1097 .. note::
1098
1099 There is no method to obtain the POSIX timestamp directly from a
1100 naive :class:`datetime` instance representing UTC time. If your
1101 application uses this convention and your system timezone is not
1102 set to UTC, you can obtain the POSIX timestamp by supplying
1103 ``tzinfo=timezone.utc``::
1104
1105 timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
1106
1107 or by calculating the timestamp directly::
1108
1109 timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001110
1111.. method:: datetime.weekday()
1112
1113 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
1114 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
1115
1116
1117.. method:: datetime.isoweekday()
1118
1119 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
1120 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
1121 :meth:`isocalendar`.
1122
1123
1124.. method:: datetime.isocalendar()
1125
1126 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
1127 ``self.date().isocalendar()``.
1128
1129
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001130.. method:: datetime.isoformat(sep='T')
Georg Brandl116aa622007-08-15 14:28:22 +00001131
1132 Return a string representing the date and time in ISO 8601 format,
1133 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
1134 YYYY-MM-DDTHH:MM:SS
1135
1136 If :meth:`utcoffset` does not return ``None``, a 6-character string is
1137 appended, giving the UTC offset in (signed) hours and minutes:
1138 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
1139 YYYY-MM-DDTHH:MM:SS+HH:MM
1140
1141 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +00001142 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +00001143
1144 >>> from datetime import tzinfo, timedelta, datetime
1145 >>> class TZ(tzinfo):
1146 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1147 ...
1148 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1149 '2002-12-25 00:00:00-06:39'
1150
1151
1152.. method:: datetime.__str__()
1153
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001154 For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to
Georg Brandl116aa622007-08-15 14:28:22 +00001155 ``d.isoformat(' ')``.
1156
1157
1158.. method:: datetime.ctime()
1159
1160 Return a string representing the date and time, for example ``datetime(2002, 12,
1161 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1162 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
Georg Brandl60203b42010-10-06 10:11:56 +00001163 native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +00001164 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1165
1166
1167.. method:: datetime.strftime(format)
1168
1169 Return a string representing the date and time, controlled by an explicit format
David Wolever569a5fa2013-08-12 16:56:02 -04001170 string. For a complete list of formatting directives, see
1171 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001172
Georg Brandl116aa622007-08-15 14:28:22 +00001173
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001174.. method:: datetime.__format__(format)
1175
1176 Same as :meth:`.datetime.strftime`. This makes it possible to specify format
David Wolever569a5fa2013-08-12 16:56:02 -04001177 string for a :class:`.datetime` object when using :meth:`str.format`. For a
1178 complete list of formatting directives, see
1179 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001180
1181
Christian Heimesfe337bf2008-03-23 21:54:12 +00001182Examples of working with datetime objects:
1183
1184.. doctest::
1185
Christian Heimes895627f2007-12-08 17:28:33 +00001186 >>> from datetime import datetime, date, time
1187 >>> # Using datetime.combine()
1188 >>> d = date(2005, 7, 14)
1189 >>> t = time(12, 30)
1190 >>> datetime.combine(d, t)
1191 datetime.datetime(2005, 7, 14, 12, 30)
1192 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001193 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001194 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001195 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001196 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1197 >>> # Using datetime.strptime()
1198 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1199 >>> dt
1200 datetime.datetime(2006, 11, 21, 16, 30)
1201 >>> # Using datetime.timetuple() to get tuple of all attributes
1202 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001203 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001204 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001205 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001206 2006 # year
1207 11 # month
1208 21 # day
1209 16 # hour
1210 30 # minute
1211 0 # second
1212 1 # weekday (0 = Monday)
1213 325 # number of days since 1st January
1214 -1 # dst - method tzinfo.dst() returned None
1215 >>> # Date in ISO format
1216 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001217 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001218 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001219 ...
1220 2006 # ISO year
1221 47 # ISO week
1222 2 # ISO weekday
1223 >>> # Formatting datetime
1224 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1225 'Tuesday, 21. November 2006 04:30PM'
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001226 >>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
1227 'The day is 21, the month is November, the time is 04:30PM.'
Christian Heimes895627f2007-12-08 17:28:33 +00001228
Christian Heimesfe337bf2008-03-23 21:54:12 +00001229Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001230
1231 >>> from datetime import timedelta, datetime, tzinfo
1232 >>> class GMT1(tzinfo):
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001233 ... def utcoffset(self, dt):
1234 ... return timedelta(hours=1) + self.dst(dt)
1235 ... def dst(self, dt):
1236 ... # DST starts last Sunday in March
Christian Heimes895627f2007-12-08 17:28:33 +00001237 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1238 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001239 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001240 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001241 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1242 ... return timedelta(hours=1)
1243 ... else:
1244 ... return timedelta(0)
1245 ... def tzname(self,dt):
1246 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001247 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001248 >>> class GMT2(tzinfo):
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001249 ... def utcoffset(self, dt):
1250 ... return timedelta(hours=2) + self.dst(dt)
1251 ... def dst(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001252 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001253 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001254 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001255 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001256 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001257 ... return timedelta(hours=1)
Christian Heimes895627f2007-12-08 17:28:33 +00001258 ... else:
1259 ... return timedelta(0)
1260 ... def tzname(self,dt):
1261 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001262 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001263 >>> gmt1 = GMT1()
1264 >>> # Daylight Saving Time
1265 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1266 >>> dt1.dst()
1267 datetime.timedelta(0)
1268 >>> dt1.utcoffset()
1269 datetime.timedelta(0, 3600)
1270 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1271 >>> dt2.dst()
1272 datetime.timedelta(0, 3600)
1273 >>> dt2.utcoffset()
1274 datetime.timedelta(0, 7200)
1275 >>> # Convert datetime to another time zone
1276 >>> dt3 = dt2.astimezone(GMT2())
1277 >>> dt3 # doctest: +ELLIPSIS
1278 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1279 >>> dt2 # doctest: +ELLIPSIS
1280 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1281 >>> dt2.utctimetuple() == dt3.utctimetuple()
1282 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001283
Christian Heimes895627f2007-12-08 17:28:33 +00001284
Georg Brandl116aa622007-08-15 14:28:22 +00001285
1286.. _datetime-time:
1287
1288:class:`time` Objects
1289---------------------
1290
1291A time object represents a (local) time of day, independent of any particular
1292day, and subject to adjustment via a :class:`tzinfo` object.
1293
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001294.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001295
1296 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001297 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001298 following ranges:
1299
1300 * ``0 <= hour < 24``
1301 * ``0 <= minute < 60``
1302 * ``0 <= second < 60``
1303 * ``0 <= microsecond < 1000000``.
1304
1305 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1306 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1307
1308Class attributes:
1309
1310
1311.. attribute:: time.min
1312
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001313 The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001314
1315
1316.. attribute:: time.max
1317
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001318 The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001319
1320
1321.. attribute:: time.resolution
1322
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001323 The smallest possible difference between non-equal :class:`.time` objects,
1324 ``timedelta(microseconds=1)``, although note that arithmetic on
1325 :class:`.time` objects is not supported.
Georg Brandl116aa622007-08-15 14:28:22 +00001326
Georg Brandl116aa622007-08-15 14:28:22 +00001327
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001328Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001329
1330.. attribute:: time.hour
1331
1332 In ``range(24)``.
1333
1334
1335.. attribute:: time.minute
1336
1337 In ``range(60)``.
1338
1339
1340.. attribute:: time.second
1341
1342 In ``range(60)``.
1343
1344
1345.. attribute:: time.microsecond
1346
1347 In ``range(1000000)``.
1348
1349
1350.. attribute:: time.tzinfo
1351
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001352 The object passed as the tzinfo argument to the :class:`.time` constructor, or
Georg Brandl116aa622007-08-15 14:28:22 +00001353 ``None`` if none was passed.
1354
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001355
Georg Brandl116aa622007-08-15 14:28:22 +00001356Supported operations:
1357
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001358* comparison of :class:`.time` to :class:`.time`, where *a* is considered less
Georg Brandl116aa622007-08-15 14:28:22 +00001359 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
Alexander Belopolsky08313822012-06-15 20:19:47 -04001360 is aware, :exc:`TypeError` is raised if an order comparison is attempted. For equality
1361 comparisons, naive instances are never equal to aware instances.
1362
1363 If both comparands are aware, and have
Senthil Kumarana6bac952011-07-04 11:28:30 -07001364 the same :attr:`tzinfo` attribute, the common :attr:`tzinfo` attribute is
1365 ignored and the base times are compared. If both comparands are aware and
1366 have different :attr:`tzinfo` attributes, the comparands are first adjusted by
1367 subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
1368 to stop mixed-type comparisons from falling back to the default comparison by
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001369 object address, when a :class:`.time` object is compared to an object of a
Senthil Kumaran3aac1792011-07-04 11:43:51 -07001370 different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
Senthil Kumarana6bac952011-07-04 11:28:30 -07001371 ``!=``. The latter cases return :const:`False` or :const:`True`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +00001372
Alexander Belopolsky08313822012-06-15 20:19:47 -04001373 .. versionchanged:: 3.3
Éric Araujob0f08952012-06-24 16:22:09 -04001374 Equality comparisons between naive and aware :class:`time` instances
1375 don't raise :exc:`TypeError`.
Alexander Belopolsky08313822012-06-15 20:19:47 -04001376
Georg Brandl116aa622007-08-15 14:28:22 +00001377* hash, use as dict key
1378
1379* efficient pickling
1380
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05001381In boolean contexts, a :class:`.time` object is always considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +00001382
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05001383.. versionchanged:: 3.5
1384 Before Python 3.5, a :class:`.time` object was considered to be false if it
1385 represented midnight in UTC. This behavior was considered obscure and
1386 error-prone and has been removed in Python 3.5. See :issue:`13936` for full
1387 details.
Georg Brandl116aa622007-08-15 14:28:22 +00001388
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001389Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001390
1391.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1392
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001393 Return a :class:`.time` with the same value, except for those attributes given
Senthil Kumarana6bac952011-07-04 11:28:30 -07001394 new values by whichever keyword arguments are specified. Note that
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001395 ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
1396 aware :class:`.time`, without conversion of the time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001397
1398
1399.. method:: time.isoformat()
1400
1401 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1402 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1403 6-character string is appended, giving the UTC offset in (signed) hours and
1404 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1405
1406
1407.. method:: time.__str__()
1408
1409 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1410
1411
1412.. method:: time.strftime(format)
1413
David Wolever569a5fa2013-08-12 16:56:02 -04001414 Return a string representing the time, controlled by an explicit format
1415 string. For a complete list of formatting directives, see
David Woleverbbf4a462013-08-12 17:15:36 -04001416 :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001417
1418
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001419.. method:: time.__format__(format)
1420
1421 Same as :meth:`.time.strftime`. This makes it possible to specify format string
David Wolever569a5fa2013-08-12 16:56:02 -04001422 for a :class:`.time` object when using :meth:`str.format`. For a
1423 complete list of formatting directives, see
1424 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001425
1426
Georg Brandl116aa622007-08-15 14:28:22 +00001427.. method:: time.utcoffset()
1428
1429 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1430 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1431 return ``None`` or a :class:`timedelta` object representing a whole number of
1432 minutes with magnitude less than one day.
1433
1434
1435.. method:: time.dst()
1436
1437 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1438 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1439 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1440 with magnitude less than one day.
1441
1442
1443.. method:: time.tzname()
1444
1445 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1446 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1447 return ``None`` or a string object.
1448
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001449
Christian Heimesfe337bf2008-03-23 21:54:12 +00001450Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001451
Christian Heimes895627f2007-12-08 17:28:33 +00001452 >>> from datetime import time, tzinfo
1453 >>> class GMT1(tzinfo):
1454 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001455 ... return timedelta(hours=1)
1456 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001457 ... return timedelta(0)
1458 ... def tzname(self,dt):
1459 ... return "Europe/Prague"
1460 ...
1461 >>> t = time(12, 10, 30, tzinfo=GMT1())
1462 >>> t # doctest: +ELLIPSIS
1463 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1464 >>> gmt = GMT1()
1465 >>> t.isoformat()
1466 '12:10:30+01:00'
1467 >>> t.dst()
1468 datetime.timedelta(0)
1469 >>> t.tzname()
1470 'Europe/Prague'
1471 >>> t.strftime("%H:%M:%S %Z")
1472 '12:10:30 Europe/Prague'
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001473 >>> 'The {} is {:%H:%M}.'.format("time", t)
1474 'The time is 12:10.'
Christian Heimes895627f2007-12-08 17:28:33 +00001475
Georg Brandl116aa622007-08-15 14:28:22 +00001476
1477.. _datetime-tzinfo:
1478
1479:class:`tzinfo` Objects
1480-----------------------
1481
Brett Cannone1327f72009-01-29 04:10:21 +00001482:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001483instantiated directly. You need to derive a concrete subclass, and (at least)
1484supply implementations of the standard :class:`tzinfo` methods needed by the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001485:class:`.datetime` methods you use. The :mod:`datetime` module supplies
Andrew Svetlovdfe109e2012-12-17 13:42:04 +02001486a simple concrete subclass of :class:`tzinfo` :class:`timezone` which can represent
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001487timezones with fixed offset from UTC such as UTC itself or North American EST and
1488EDT.
Georg Brandl116aa622007-08-15 14:28:22 +00001489
1490An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001491constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
Senthil Kumarana6bac952011-07-04 11:28:30 -07001492view their attributes as being in local time, and the :class:`tzinfo` object
Georg Brandl116aa622007-08-15 14:28:22 +00001493supports methods revealing offset of local time from UTC, the name of the time
1494zone, and DST offset, all relative to a date or time object passed to them.
1495
1496Special requirement for pickling: A :class:`tzinfo` subclass must have an
1497:meth:`__init__` method that can be called with no arguments, else it can be
1498pickled but possibly not unpickled again. This is a technical requirement that
1499may be relaxed in the future.
1500
1501A concrete subclass of :class:`tzinfo` may need to implement the following
1502methods. Exactly which methods are needed depends on the uses made of aware
1503:mod:`datetime` objects. If in doubt, simply implement all of them.
1504
1505
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001506.. method:: tzinfo.utcoffset(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001507
1508 Return offset of local time from UTC, in minutes east of UTC. If local time is
1509 west of UTC, this should be negative. Note that this is intended to be the
1510 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1511 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1512 the UTC offset isn't known, return ``None``. Else the value returned must be a
1513 :class:`timedelta` object specifying a whole number of minutes in the range
1514 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1515 than one day). Most implementations of :meth:`utcoffset` will probably look
1516 like one of these two::
1517
1518 return CONSTANT # fixed-offset class
1519 return CONSTANT + self.dst(dt) # daylight-aware class
1520
1521 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1522 ``None`` either.
1523
1524 The default implementation of :meth:`utcoffset` raises
1525 :exc:`NotImplementedError`.
1526
1527
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001528.. method:: tzinfo.dst(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001529
1530 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1531 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1532 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1533 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1534 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1535 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1536 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -07001537 attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
1538 should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
1539 DST changes when crossing time zones.
Georg Brandl116aa622007-08-15 14:28:22 +00001540
1541 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1542 daylight times must be consistent in this sense:
1543
1544 ``tz.utcoffset(dt) - tz.dst(dt)``
1545
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001546 must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo ==
Georg Brandl116aa622007-08-15 14:28:22 +00001547 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1548 zone's "standard offset", which should not depend on the date or the time, but
1549 only on geographic location. The implementation of :meth:`datetime.astimezone`
1550 relies on this, but cannot detect violations; it's the programmer's
1551 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1552 this, it may be able to override the default implementation of
1553 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1554
1555 Most implementations of :meth:`dst` will probably look like one of these two::
1556
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001557 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001558 # a fixed-offset class: doesn't account for DST
1559 return timedelta(0)
1560
1561 or ::
1562
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001563 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001564 # Code to set dston and dstoff to the time zone's DST
1565 # transition times based on the input dt.year, and expressed
1566 # in standard local time. Then
1567
1568 if dston <= dt.replace(tzinfo=None) < dstoff:
1569 return timedelta(hours=1)
1570 else:
1571 return timedelta(0)
1572
1573 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1574
1575
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001576.. method:: tzinfo.tzname(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001577
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001578 Return the time zone name corresponding to the :class:`.datetime` object *dt*, as
Georg Brandl116aa622007-08-15 14:28:22 +00001579 a string. Nothing about string names is defined by the :mod:`datetime` module,
1580 and there's no requirement that it mean anything in particular. For example,
1581 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1582 valid replies. Return ``None`` if a string name isn't known. Note that this is
1583 a method rather than a fixed string primarily because some :class:`tzinfo`
1584 subclasses will wish to return different names depending on the specific value
1585 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1586 daylight time.
1587
1588 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1589
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001590
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001591These methods are called by a :class:`.datetime` or :class:`.time` object, in
1592response to their methods of the same names. A :class:`.datetime` object passes
1593itself as the argument, and a :class:`.time` object passes ``None`` as the
Georg Brandl116aa622007-08-15 14:28:22 +00001594argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001595accept a *dt* argument of ``None``, or of class :class:`.datetime`.
Georg Brandl116aa622007-08-15 14:28:22 +00001596
1597When ``None`` is passed, it's up to the class designer to decide the best
1598response. For example, returning ``None`` is appropriate if the class wishes to
1599say that time objects don't participate in the :class:`tzinfo` protocols. It
1600may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1601there is no other convention for discovering the standard offset.
1602
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001603When a :class:`.datetime` object is passed in response to a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +00001604method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1605rely on this, unless user code calls :class:`tzinfo` methods directly. The
1606intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1607time, and not need worry about objects in other timezones.
1608
1609There is one more :class:`tzinfo` method that a subclass may wish to override:
1610
1611
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001612.. method:: tzinfo.fromutc(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001613
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001614 This is called from the default :class:`datetime.astimezone()`
1615 implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s
1616 date and time data are to be viewed as expressing a UTC time. The purpose
1617 of :meth:`fromutc` is to adjust the date and time data, returning an
Senthil Kumarana6bac952011-07-04 11:28:30 -07001618 equivalent datetime in *self*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00001619
1620 Most :class:`tzinfo` subclasses should be able to inherit the default
1621 :meth:`fromutc` implementation without problems. It's strong enough to handle
1622 fixed-offset time zones, and time zones accounting for both standard and
1623 daylight time, and the latter even if the DST transition times differ in
1624 different years. An example of a time zone the default :meth:`fromutc`
1625 implementation may not handle correctly in all cases is one where the standard
1626 offset (from UTC) depends on the specific date and time passed, which can happen
1627 for political reasons. The default implementations of :meth:`astimezone` and
1628 :meth:`fromutc` may not produce the result you want if the result is one of the
1629 hours straddling the moment the standard offset changes.
1630
1631 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1632 like::
1633
1634 def fromutc(self, dt):
1635 # raise ValueError error if dt.tzinfo is not self
1636 dtoff = dt.utcoffset()
1637 dtdst = dt.dst()
1638 # raise ValueError if dtoff is None or dtdst is None
1639 delta = dtoff - dtdst # this is self's standard offset
1640 if delta:
1641 dt += delta # convert to standard local time
1642 dtdst = dt.dst()
1643 # raise ValueError if dtdst is None
1644 if dtdst:
1645 return dt + dtdst
1646 else:
1647 return dt
1648
1649Example :class:`tzinfo` classes:
1650
1651.. literalinclude:: ../includes/tzinfo-examples.py
1652
Georg Brandl116aa622007-08-15 14:28:22 +00001653Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1654subclass accounting for both standard and daylight time, at the DST transition
1655points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00001656minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
16571:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001658
1659 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1660 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1661 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1662
1663 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1664
1665 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1666
1667When DST starts (the "start" line), the local wall clock leaps from 1:59 to
16683:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1669``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1670begins. In order for :meth:`astimezone` to make this guarantee, the
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001671:meth:`tzinfo.dst` method must consider times in the "missing hour" (2:MM for
Georg Brandl116aa622007-08-15 14:28:22 +00001672Eastern) to be in daylight time.
1673
1674When DST ends (the "end" line), there's a potentially worse problem: there's an
1675hour that can't be spelled unambiguously in local wall time: the last hour of
1676daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1677daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1678to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1679:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1680hours into the same local hour then. In the Eastern example, UTC times of the
1681form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1682:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1683consider times in the "repeated hour" to be in standard time. This is easily
1684arranged, as in the example, by expressing DST switch times in the time zone's
1685standard local time.
1686
1687Applications that can't bear such ambiguities should avoid using hybrid
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001688:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`,
1689or any other fixed-offset :class:`tzinfo` subclass (such as a class representing
1690only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
1691
Sandro Tosid11d0d62012-04-24 19:46:06 +02001692.. seealso::
1693
Georg Brandle73778c2014-10-29 08:36:35 +01001694 `pytz <https://pypi.python.org/pypi/pytz/>`_
Benjamin Peterson9b29acd2014-06-22 16:26:39 -07001695 The standard library has :class:`timezone` class for handling arbitrary
1696 fixed offsets from UTC and :attr:`timezone.utc` as UTC timezone instance.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001697
Benjamin Peterson9b29acd2014-06-22 16:26:39 -07001698 *pytz* library brings the *IANA timezone database* (also known as the
1699 Olson database) to Python and its usage is recommended.
Sandro Tosi100b8892012-04-28 11:19:37 +02001700
1701 `IANA timezone database <http://www.iana.org/time-zones>`_
1702 The Time Zone Database (often called tz or zoneinfo) contains code and
1703 data that represent the history of local time for many representative
1704 locations around the globe. It is updated periodically to reflect changes
1705 made by political bodies to time zone boundaries, UTC offsets, and
1706 daylight-saving rules.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001707
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001708
1709.. _datetime-timezone:
1710
1711:class:`timezone` Objects
1712--------------------------
1713
Alexander Belopolsky6d3c9a62011-05-04 10:28:26 -04001714The :class:`timezone` class is a subclass of :class:`tzinfo`, each
1715instance of which represents a timezone defined by a fixed offset from
1716UTC. Note that objects of this class cannot be used to represent
1717timezone information in the locations where different offsets are used
1718in different days of the year or where historical changes have been
1719made to civil time.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001720
1721
1722.. class:: timezone(offset[, name])
1723
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001724 The *offset* argument must be specified as a :class:`timedelta`
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001725 object representing the difference between the local time and UTC. It must
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001726 be strictly between ``-timedelta(hours=24)`` and
1727 ``timedelta(hours=24)`` and represent a whole number of minutes,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001728 otherwise :exc:`ValueError` is raised.
1729
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001730 The *name* argument is optional. If specified it must be a string that
1731 is used as the value returned by the ``tzname(dt)`` method. Otherwise,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001732 ``tzname(dt)`` returns a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001733 *offset*, HH and MM are two digits of ``offset.hours`` and
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001734 ``offset.minutes`` respectively.
1735
Benjamin Peterson9b29acd2014-06-22 16:26:39 -07001736 .. versionadded:: 3.2
1737
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001738.. method:: timezone.utcoffset(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001739
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001740 Return the fixed value specified when the :class:`timezone` instance is
1741 constructed. The *dt* argument is ignored. The return value is a
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001742 :class:`timedelta` instance equal to the difference between the
1743 local time and UTC.
1744
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001745.. method:: timezone.tzname(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001746
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001747 Return the fixed value specified when the :class:`timezone` instance is
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001748 constructed or a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001749 *offset*, HH and MM are two digits of ``offset.hours`` and
1750 ``offset.minutes`` respectively.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001751
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001752.. method:: timezone.dst(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001753
1754 Always returns ``None``.
1755
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001756.. method:: timezone.fromutc(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001757
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001758 Return ``dt + offset``. The *dt* argument must be an aware
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001759 :class:`.datetime` instance, with ``tzinfo`` set to ``self``.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001760
1761Class attributes:
1762
1763.. attribute:: timezone.utc
1764
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001765 The UTC timezone, ``timezone(timedelta(0))``.
Georg Brandl48310cd2009-01-03 21:18:54 +00001766
Georg Brandl116aa622007-08-15 14:28:22 +00001767
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001768.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00001769
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001770:meth:`strftime` and :meth:`strptime` Behavior
1771----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001772
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001773:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
Georg Brandl116aa622007-08-15 14:28:22 +00001774``strftime(format)`` method, to create a string representing the time under the
1775control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1776acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1777although not all objects support a :meth:`timetuple` method.
1778
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001779Conversely, the :meth:`datetime.strptime` class method creates a
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001780:class:`.datetime` object from a string representing a date and time and a
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001781corresponding format string. ``datetime.strptime(date_string, format)`` is
1782equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1783
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001784For :class:`.time` objects, the format codes for year, month, and day should not
Georg Brandl116aa622007-08-15 14:28:22 +00001785be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001786is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00001787
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001788For :class:`date` objects, the format codes for hours, minutes, seconds, and
1789microseconds should not be used, as :class:`date` objects have no such
1790values. If they're used anyway, ``0`` is substituted for them.
1791
Georg Brandl116aa622007-08-15 14:28:22 +00001792The full set of format codes supported varies across platforms, because Python
1793calls the platform C library's :func:`strftime` function, and platform
Georg Brandlb7117af2013-10-13 18:28:25 +02001794variations are common. To see the full set of format codes supported on your
1795platform, consult the :manpage:`strftime(3)` documentation.
Christian Heimes895627f2007-12-08 17:28:33 +00001796
1797The following is a list of all the format codes that the C standard (1989
1798version) requires, and these work on all platforms with a standard C
1799implementation. Note that the 1999 version of the C standard added additional
1800format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001801
David Wolever569a5fa2013-08-12 16:56:02 -04001802+-----------+--------------------------------+------------------------+-------+
1803| Directive | Meaning | Example | Notes |
1804+===========+================================+========================+=======+
1805| ``%a`` | Weekday as locale's || Sun, Mon, ..., Sat | \(1) |
1806| | abbreviated name. | (en_US); | |
1807| | || So, Mo, ..., Sa | |
1808| | | (de_DE) | |
1809+-----------+--------------------------------+------------------------+-------+
1810| ``%A`` | Weekday as locale's full name. || Sunday, Monday, ..., | \(1) |
1811| | | Saturday (en_US); | |
1812| | || Sonntag, Montag, ..., | |
1813| | | Samstag (de_DE) | |
1814+-----------+--------------------------------+------------------------+-------+
1815| ``%w`` | Weekday as a decimal number, | 0, 1, ..., 6 | |
1816| | where 0 is Sunday and 6 is | | |
1817| | Saturday. | | |
1818+-----------+--------------------------------+------------------------+-------+
1819| ``%d`` | Day of the month as a | 01, 02, ..., 31 | |
1820| | zero-padded decimal number. | | |
1821+-----------+--------------------------------+------------------------+-------+
1822| ``%b`` | Month as locale's abbreviated || Jan, Feb, ..., Dec | \(1) |
1823| | name. | (en_US); | |
1824| | || Jan, Feb, ..., Dez | |
1825| | | (de_DE) | |
1826+-----------+--------------------------------+------------------------+-------+
1827| ``%B`` | Month as locale's full name. || January, February, | \(1) |
1828| | | ..., December (en_US);| |
1829| | || Januar, Februar, ..., | |
1830| | | Dezember (de_DE) | |
1831+-----------+--------------------------------+------------------------+-------+
1832| ``%m`` | Month as a zero-padded | 01, 02, ..., 12 | |
1833| | decimal number. | | |
1834+-----------+--------------------------------+------------------------+-------+
1835| ``%y`` | Year without century as a | 00, 01, ..., 99 | |
1836| | zero-padded decimal number. | | |
1837+-----------+--------------------------------+------------------------+-------+
1838| ``%Y`` | Year with century as a decimal | 0001, 0002, ..., 2013, | \(2) |
David Wolever5d07e702013-08-14 14:41:48 -04001839| | number. | 2014, ..., 9998, 9999 | |
David Wolever569a5fa2013-08-12 16:56:02 -04001840+-----------+--------------------------------+------------------------+-------+
1841| ``%H`` | Hour (24-hour clock) as a | 00, 01, ..., 23 | |
1842| | zero-padded decimal number. | | |
1843+-----------+--------------------------------+------------------------+-------+
1844| ``%I`` | Hour (12-hour clock) as a | 01, 02, ..., 12 | |
1845| | zero-padded decimal number. | | |
1846+-----------+--------------------------------+------------------------+-------+
1847| ``%p`` | Locale's equivalent of either || AM, PM (en_US); | \(1), |
1848| | AM or PM. || am, pm (de_DE) | \(3) |
1849+-----------+--------------------------------+------------------------+-------+
1850| ``%M`` | Minute as a zero-padded | 00, 01, ..., 59 | |
1851| | decimal number. | | |
1852+-----------+--------------------------------+------------------------+-------+
1853| ``%S`` | Second as a zero-padded | 00, 01, ..., 59 | \(4) |
1854| | decimal number. | | |
1855+-----------+--------------------------------+------------------------+-------+
1856| ``%f`` | Microsecond as a decimal | 000000, 000001, ..., | \(5) |
1857| | number, zero-padded on the | 999999 | |
1858| | left. | | |
1859+-----------+--------------------------------+------------------------+-------+
1860| ``%z`` | UTC offset in the form +HHMM | (empty), +0000, -0400, | \(6) |
1861| | or -HHMM (empty string if the | +1030 | |
1862| | the object is naive). | | |
1863+-----------+--------------------------------+------------------------+-------+
1864| ``%Z`` | Time zone name (empty string | (empty), UTC, EST, CST | |
1865| | if the object is naive). | | |
1866+-----------+--------------------------------+------------------------+-------+
1867| ``%j`` | Day of the year as a | 001, 002, ..., 366 | |
1868| | zero-padded decimal number. | | |
1869+-----------+--------------------------------+------------------------+-------+
1870| ``%U`` | Week number of the year | 00, 01, ..., 53 | \(7) |
1871| | (Sunday as the first day of | | |
1872| | the week) as a zero padded | | |
1873| | decimal number. All days in a | | |
1874| | new year preceding the first | | |
1875| | Sunday are considered to be in | | |
1876| | week 0. | | |
1877+-----------+--------------------------------+------------------------+-------+
1878| ``%W`` | Week number of the year | 00, 01, ..., 53 | \(7) |
1879| | (Monday as the first day of | | |
1880| | the week) as a decimal number. | | |
1881| | All days in a new year | | |
1882| | preceding the first Monday | | |
1883| | are considered to be in | | |
1884| | week 0. | | |
1885+-----------+--------------------------------+------------------------+-------+
1886| ``%c`` | Locale's appropriate date and || Tue Aug 16 21:30:00 | \(1) |
1887| | time representation. | 1988 (en_US); | |
1888| | || Di 16 Aug 21:30:00 | |
1889| | | 1988 (de_DE) | |
1890+-----------+--------------------------------+------------------------+-------+
1891| ``%x`` | Locale's appropriate date || 08/16/88 (None); | \(1) |
1892| | representation. || 08/16/1988 (en_US); | |
1893| | || 16.08.1988 (de_DE) | |
1894+-----------+--------------------------------+------------------------+-------+
1895| ``%X`` | Locale's appropriate time || 21:30:00 (en_US); | \(1) |
1896| | representation. || 21:30:00 (de_DE) | |
1897+-----------+--------------------------------+------------------------+-------+
1898| ``%%`` | A literal ``'%'`` character. | % | |
1899+-----------+--------------------------------+------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001900
Christian Heimes895627f2007-12-08 17:28:33 +00001901Notes:
1902
1903(1)
David Wolever569a5fa2013-08-12 16:56:02 -04001904 Because the format depends on the current locale, care should be taken when
1905 making assumptions about the output value. Field orderings will vary (for
1906 example, "month/day/year" versus "day/month/year"), and the output may
1907 contain Unicode characters encoded using the locale's default encoding (for
Georg Brandlad321532013-10-29 08:05:10 +01001908 example, if the current locale is ``ja_JP``, the default encoding could be
David Wolever569a5fa2013-08-12 16:56:02 -04001909 any one of ``eucJP``, ``SJIS``, or ``utf-8``; use :meth:`locale.getlocale`
1910 to determine the current locale's encoding).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001911
1912(2)
David Wolever569a5fa2013-08-12 16:56:02 -04001913 The :meth:`strptime` method can parse years in the full [1, 9999] range, but
1914 years < 1000 must be zero-filled to 4-digit width.
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001915
1916 .. versionchanged:: 3.2
1917 In previous versions, :meth:`strftime` method was restricted to
1918 years >= 1900.
1919
Alexander Belopolsky5611a1c2011-05-02 14:14:48 -04001920 .. versionchanged:: 3.3
1921 In version 3.2, :meth:`strftime` method was restricted to
1922 years >= 1000.
1923
David Wolever569a5fa2013-08-12 16:56:02 -04001924(3)
1925 When used with the :meth:`strptime` method, the ``%p`` directive only affects
1926 the output hour field if the ``%I`` directive is used to parse the hour.
Alexander Belopolskyca94f552010-06-17 18:30:34 +00001927
David Wolever569a5fa2013-08-12 16:56:02 -04001928(4)
1929 Unlike the :mod:`time` module, the :mod:`datetime` module does not support
1930 leap seconds.
1931
1932(5)
1933 When used with the :meth:`strptime` method, the ``%f`` directive
1934 accepts from one to six digits and zero pads on the right. ``%f`` is
1935 an extension to the set of format characters in the C standard (but
1936 implemented separately in datetime objects, and therefore always
1937 available).
1938
1939(6)
1940 For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1941 strings.
1942
1943 For an aware object:
1944
1945 ``%z``
1946 :meth:`utcoffset` is transformed into a 5-character string of the form
1947 +HHMM or -HHMM, where HH is a 2-digit string giving the number of UTC
1948 offset hours, and MM is a 2-digit string giving the number of UTC offset
1949 minutes. For example, if :meth:`utcoffset` returns
1950 ``timedelta(hours=-3, minutes=-30)``, ``%z`` is replaced with the string
1951 ``'-0330'``.
1952
1953 ``%Z``
1954 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty
1955 string. Otherwise ``%Z`` is replaced by the returned value, which must
1956 be a string.
1957
1958 .. versionchanged:: 3.2
1959 When the ``%z`` directive is provided to the :meth:`strptime` method, an
1960 aware :class:`.datetime` object will be produced. The ``tzinfo`` of the
1961 result will be set to a :class:`timezone` instance.
1962
1963(7)
1964 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used
1965 in calculations when the day of the week and the year are specified.
R David Murray9075d8b2012-05-14 22:14:46 -04001966
1967.. rubric:: Footnotes
1968
1969.. [#] If, that is, we ignore the effects of Relativity