blob: e4f1eb23017759c7079fefa06245f58691019b36 [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
Christian Heimes5b5e81c2007-12-31 16:14:33 +000010.. XXX what order should the types be discussed in?
Georg Brandl116aa622007-08-15 14:28:22 +000011
Georg Brandl116aa622007-08-15 14:28:22 +000012The :mod:`datetime` module supplies classes for manipulating dates and times in
13both simple and complex ways. While date and time arithmetic is supported, the
Senthil Kumarana6bac952011-07-04 11:28:30 -070014focus of the implementation is on efficient attribute extraction for output
R David Murray539f2392012-05-14 22:17:23 -040015formatting and manipulation. For related functionality, see also the
16:mod:`time` and :mod:`calendar` modules.
Georg Brandl116aa622007-08-15 14:28:22 +000017
R David Murray9075d8b2012-05-14 22:14:46 -040018There are two kinds of date and time objects: "naive" and "aware".
Georg Brandl116aa622007-08-15 14:28:22 +000019
R David Murray9075d8b2012-05-14 22:14:46 -040020An aware object has sufficient knowledge of applicable algorithmic and
21political time adjustments, such as time zone and daylight saving time
22information, to locate itself relative to other aware objects. An aware object
23is used to represent a specific moment in time that is not open to
24interpretation [#]_.
25
26A naive object does not contain enough information to unambiguously locate
27itself relative to other date/time objects. Whether a naive object represents
R David Murray539f2392012-05-14 22:17:23 -040028Coordinated Universal Time (UTC), local time, or time in some other timezone is
29purely up to the program, just like it is up to the program whether a
30particular number represents metres, miles, or mass. Naive objects are easy to
31understand and to work with, at the cost of ignoring some aspects of reality.
Georg Brandl116aa622007-08-15 14:28:22 +000032
R David Murray539f2392012-05-14 22:17:23 -040033For applications requiring aware objects, :class:`.datetime` and :class:`.time`
34objects have an optional time zone information attribute, :attr:`tzinfo`, that
35can be set to an instance of a subclass of the abstract :class:`tzinfo` class.
36These :class:`tzinfo` objects capture information about the offset from UTC
37time, the time zone name, and whether Daylight Saving Time is in effect. Note
38that only one concrete :class:`tzinfo` class, the :class:`timezone` class, is
39supplied by the :mod:`datetime` module. The :class:`timezone` class can
40represent simple timezones with fixed offset from UTC, such as UTC itself or
41North American EST and EDT timezones. Supporting timezones at deeper levels of
42detail is up to the application. The rules for time adjustment across the
Alexander Belopolsky4e749a12010-06-14 14:15:50 +000043world are more political than rational, change frequently, and there is no
44standard suitable for every application aside from UTC.
Georg Brandl116aa622007-08-15 14:28:22 +000045
46The :mod:`datetime` module exports the following constants:
47
Georg Brandl116aa622007-08-15 14:28:22 +000048.. data:: MINYEAR
49
Ezio Melotti35ec7f72011-10-02 12:44:50 +030050 The smallest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl116aa622007-08-15 14:28:22 +000051 :const:`MINYEAR` is ``1``.
52
53
54.. data:: MAXYEAR
55
Ezio Melotti35ec7f72011-10-02 12:44:50 +030056 The largest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl116aa622007-08-15 14:28:22 +000057 :const:`MAXYEAR` is ``9999``.
58
59
60.. seealso::
61
62 Module :mod:`calendar`
63 General calendar related functions.
64
65 Module :mod:`time`
66 Time access and conversions.
67
68
69Available Types
70---------------
71
Georg Brandl116aa622007-08-15 14:28:22 +000072.. class:: date
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000073 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000074
75 An idealized naive date, assuming the current Gregorian calendar always was, and
76 always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and
77 :attr:`day`.
78
79
80.. class:: time
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000081 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000082
83 An idealized time, independent of any particular day, assuming that every day
84 has exactly 24\*60\*60 seconds (there is no notion of "leap seconds" here).
85 Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
86 and :attr:`tzinfo`.
87
88
89.. class:: datetime
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000090 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000091
92 A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`,
93 :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
94 and :attr:`tzinfo`.
95
96
97.. class:: timedelta
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000098 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000099
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300100 A duration expressing the difference between two :class:`date`, :class:`.time`,
101 or :class:`.datetime` instances to microsecond resolution.
Georg Brandl116aa622007-08-15 14:28:22 +0000102
103
104.. class:: tzinfo
105
106 An abstract base class for time zone information objects. These are used by the
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300107 :class:`.datetime` and :class:`.time` classes to provide a customizable notion of
Georg Brandl116aa622007-08-15 14:28:22 +0000108 time adjustment (for example, to account for time zone and/or daylight saving
109 time).
110
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000111.. class:: timezone
112
113 A class that implements the :class:`tzinfo` abstract base class as a
114 fixed offset from the UTC.
115
116 .. versionadded:: 3.2
117
118
Georg Brandl116aa622007-08-15 14:28:22 +0000119Objects of these types are immutable.
120
121Objects of the :class:`date` type are always naive.
122
R David Murray9075d8b2012-05-14 22:14:46 -0400123An object of type :class:`.time` or :class:`.datetime` may be naive or aware.
124A :class:`.datetime` object *d* is aware if ``d.tzinfo`` is not ``None`` and
125``d.tzinfo.utcoffset(d)`` does not return ``None``. If ``d.tzinfo`` is
126``None``, or if ``d.tzinfo`` is not ``None`` but ``d.tzinfo.utcoffset(d)``
127returns ``None``, *d* is naive. A :class:`.time` object *t* is aware
128if ``t.tzinfo`` is not ``None`` and ``t.tzinfo.utcoffset(None)`` does not return
129``None``. Otherwise, *t* is naive.
Georg Brandl116aa622007-08-15 14:28:22 +0000130
131The distinction between naive and aware doesn't apply to :class:`timedelta`
132objects.
133
134Subclass relationships::
135
136 object
137 timedelta
138 tzinfo
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000139 timezone
Georg Brandl116aa622007-08-15 14:28:22 +0000140 time
141 date
142 datetime
143
144
145.. _datetime-timedelta:
146
147:class:`timedelta` Objects
148--------------------------
149
150A :class:`timedelta` object represents a duration, the difference between two
151dates or times.
152
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000153.. class:: timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000154
Georg Brandl5c106642007-11-29 17:41:05 +0000155 All arguments are optional and default to ``0``. Arguments may be integers
Georg Brandl116aa622007-08-15 14:28:22 +0000156 or floats, and may be positive or negative.
157
158 Only *days*, *seconds* and *microseconds* are stored internally. Arguments are
159 converted to those units:
160
161 * A millisecond is converted to 1000 microseconds.
162 * A minute is converted to 60 seconds.
163 * An hour is converted to 3600 seconds.
164 * A week is converted to 7 days.
165
166 and days, seconds and microseconds are then normalized so that the
167 representation is unique, with
168
169 * ``0 <= microseconds < 1000000``
170 * ``0 <= seconds < 3600*24`` (the number of seconds in one day)
171 * ``-999999999 <= days <= 999999999``
172
Alexander Belopolsky790d2692013-08-04 14:51:35 -0400173 If any argument is a float and there are fractional microseconds,
174 the fractional microseconds left over from all arguments are
175 combined and their sum is rounded to the nearest microsecond using
176 round-half-to-even tiebreaker. If no argument is a float, the
177 conversion and normalization processes are exact (no information is
178 lost).
Georg Brandl116aa622007-08-15 14:28:22 +0000179
180 If the normalized value of days lies outside the indicated range,
181 :exc:`OverflowError` is raised.
182
183 Note that normalization of negative values may be surprising at first. For
Christian Heimesfe337bf2008-03-23 21:54:12 +0000184 example,
Georg Brandl116aa622007-08-15 14:28:22 +0000185
Christian Heimes895627f2007-12-08 17:28:33 +0000186 >>> from datetime import timedelta
Georg Brandl116aa622007-08-15 14:28:22 +0000187 >>> d = timedelta(microseconds=-1)
188 >>> (d.days, d.seconds, d.microseconds)
189 (-1, 86399, 999999)
190
Georg Brandl116aa622007-08-15 14:28:22 +0000191
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000192Class attributes are:
Georg Brandl116aa622007-08-15 14:28:22 +0000193
194.. attribute:: timedelta.min
195
196 The most negative :class:`timedelta` object, ``timedelta(-999999999)``.
197
198
199.. attribute:: timedelta.max
200
201 The most positive :class:`timedelta` object, ``timedelta(days=999999999,
202 hours=23, minutes=59, seconds=59, microseconds=999999)``.
203
204
205.. attribute:: timedelta.resolution
206
207 The smallest possible difference between non-equal :class:`timedelta` objects,
208 ``timedelta(microseconds=1)``.
209
210Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``.
211``-timedelta.max`` is not representable as a :class:`timedelta` object.
212
213Instance attributes (read-only):
214
215+------------------+--------------------------------------------+
216| Attribute | Value |
217+==================+============================================+
218| ``days`` | Between -999999999 and 999999999 inclusive |
219+------------------+--------------------------------------------+
220| ``seconds`` | Between 0 and 86399 inclusive |
221+------------------+--------------------------------------------+
222| ``microseconds`` | Between 0 and 999999 inclusive |
223+------------------+--------------------------------------------+
224
225Supported operations:
226
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000227.. XXX this table is too wide!
Georg Brandl116aa622007-08-15 14:28:22 +0000228
229+--------------------------------+-----------------------------------------------+
230| Operation | Result |
231+================================+===============================================+
232| ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == |
233| | *t3* and *t1*-*t3* == *t2* are true. (1) |
234+--------------------------------+-----------------------------------------------+
235| ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* |
236| | == *t2* - *t3* and *t2* == *t1* + *t3* are |
237| | true. (1) |
238+--------------------------------+-----------------------------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000239| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer. |
Georg Brandl116aa622007-08-15 14:28:22 +0000240| | Afterwards *t1* // i == *t2* is true, |
241| | provided ``i != 0``. |
242+--------------------------------+-----------------------------------------------+
243| | In general, *t1* \* i == *t1* \* (i-1) + *t1* |
244| | is true. (1) |
245+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000246| ``t1 = t2 * f or t1 = f * t2`` | Delta multiplied by a float. The result is |
247| | rounded to the nearest multiple of |
248| | timedelta.resolution using round-half-to-even.|
249+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000250| ``f = t2 / t3`` | Division (3) of *t2* by *t3*. Returns a |
251| | :class:`float` object. |
252+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000253| ``t1 = t2 / f or t1 = t2 / i`` | Delta divided by a float or an int. The result|
254| | is rounded to the nearest multiple of |
255| | timedelta.resolution using round-half-to-even.|
256+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000257| ``t1 = t2 // i`` or | The floor is computed and the remainder (if |
258| ``t1 = t2 // t3`` | any) is thrown away. In the second case, an |
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000259| | integer is returned. (3) |
Mark Dickinson7c186e22010-04-20 22:32:49 +0000260+--------------------------------+-----------------------------------------------+
261| ``t1 = t2 % t3`` | The remainder is computed as a |
262| | :class:`timedelta` object. (3) |
263+--------------------------------+-----------------------------------------------+
264| ``q, r = divmod(t1, t2)`` | Computes the quotient and the remainder: |
265| | ``q = t1 // t2`` (3) and ``r = t1 % t2``. |
266| | q is an integer and r is a :class:`timedelta` |
267| | object. |
Georg Brandl116aa622007-08-15 14:28:22 +0000268+--------------------------------+-----------------------------------------------+
269| ``+t1`` | Returns a :class:`timedelta` object with the |
270| | same value. (2) |
271+--------------------------------+-----------------------------------------------+
272| ``-t1`` | equivalent to :class:`timedelta`\ |
273| | (-*t1.days*, -*t1.seconds*, |
274| | -*t1.microseconds*), and to *t1*\* -1. (1)(4) |
275+--------------------------------+-----------------------------------------------+
Georg Brandl495f7b52009-10-27 15:28:25 +0000276| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, and|
Georg Brandl116aa622007-08-15 14:28:22 +0000277| | to -*t* when ``t.days < 0``. (2) |
278+--------------------------------+-----------------------------------------------+
Georg Brandlf55c3152010-07-31 11:40:07 +0000279| ``str(t)`` | Returns a string in the form |
280| | ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D |
281| | is negative for negative ``t``. (5) |
282+--------------------------------+-----------------------------------------------+
283| ``repr(t)`` | Returns a string in the form |
284| | ``datetime.timedelta(D[, S[, U]])``, where D |
285| | is negative for negative ``t``. (5) |
286+--------------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000287
288Notes:
289
290(1)
291 This is exact, but may overflow.
292
293(2)
294 This is exact, and cannot overflow.
295
296(3)
297 Division by 0 raises :exc:`ZeroDivisionError`.
298
299(4)
300 -*timedelta.max* is not representable as a :class:`timedelta` object.
301
Georg Brandlf55c3152010-07-31 11:40:07 +0000302(5)
303 String representations of :class:`timedelta` objects are normalized
304 similarly to their internal representation. This leads to somewhat
305 unusual results for negative timedeltas. For example:
306
307 >>> timedelta(hours=-5)
308 datetime.timedelta(-1, 68400)
309 >>> print(_)
310 -1 day, 19:00:00
311
Georg Brandl116aa622007-08-15 14:28:22 +0000312In addition to the operations listed above :class:`timedelta` objects support
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300313certain additions and subtractions with :class:`date` and :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +0000314objects (see below).
315
Georg Brandl67b21b72010-08-17 15:07:14 +0000316.. versionchanged:: 3.2
317 Floor division and true division of a :class:`timedelta` object by another
318 :class:`timedelta` object are now supported, as are remainder operations and
319 the :func:`divmod` function. True division and multiplication of a
320 :class:`timedelta` object by a :class:`float` object are now supported.
Mark Dickinson7c186e22010-04-20 22:32:49 +0000321
322
Georg Brandl116aa622007-08-15 14:28:22 +0000323Comparisons of :class:`timedelta` objects are supported with the
324:class:`timedelta` object representing the smaller duration considered to be the
325smaller timedelta. In order to stop mixed-type comparisons from falling back to
326the default comparison by object address, when a :class:`timedelta` object is
327compared to an object of a different type, :exc:`TypeError` is raised unless the
328comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
329:const:`True`, respectively.
330
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000331:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl116aa622007-08-15 14:28:22 +0000332efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
333considered to be true if and only if it isn't equal to ``timedelta(0)``.
334
Antoine Pitroube6859d2009-11-25 23:02:32 +0000335Instance methods:
336
337.. method:: timedelta.total_seconds()
338
339 Return the total number of seconds contained in the duration. Equivalent to
Mark Dickinson0381e3f2010-05-08 14:35:02 +0000340 ``td / timedelta(seconds=1)``.
341
342 Note that for very large time intervals (greater than 270 years on
343 most platforms) this method will lose microsecond accuracy.
Antoine Pitroube6859d2009-11-25 23:02:32 +0000344
345 .. versionadded:: 3.2
346
347
Christian Heimesfe337bf2008-03-23 21:54:12 +0000348Example usage:
Georg Brandl48310cd2009-01-03 21:18:54 +0000349
Christian Heimes895627f2007-12-08 17:28:33 +0000350 >>> from datetime import timedelta
351 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000352 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Christian Heimes895627f2007-12-08 17:28:33 +0000353 ... minutes=50, seconds=600) # adds up to 365 days
Antoine Pitroube6859d2009-11-25 23:02:32 +0000354 >>> year.total_seconds()
355 31536000.0
Christian Heimes895627f2007-12-08 17:28:33 +0000356 >>> year == another_year
357 True
358 >>> ten_years = 10 * year
359 >>> ten_years, ten_years.days // 365
360 (datetime.timedelta(3650), 10)
361 >>> nine_years = ten_years - year
362 >>> nine_years, nine_years.days // 365
363 (datetime.timedelta(3285), 9)
364 >>> three_years = nine_years // 3;
365 >>> three_years, three_years.days // 365
366 (datetime.timedelta(1095), 3)
367 >>> abs(three_years - ten_years) == 2 * three_years + year
368 True
369
Georg Brandl116aa622007-08-15 14:28:22 +0000370
371.. _datetime-date:
372
373:class:`date` Objects
374---------------------
375
376A :class:`date` object represents a date (year, month and day) in an idealized
377calendar, the current Gregorian calendar indefinitely extended in both
378directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
379called day number 2, and so on. This matches the definition of the "proleptic
380Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
381where it's the base calendar for all computations. See the book for algorithms
382for converting between proleptic Gregorian ordinals and many other calendar
383systems.
384
385
386.. class:: date(year, month, day)
387
Georg Brandl5c106642007-11-29 17:41:05 +0000388 All arguments are required. Arguments may be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000389 ranges:
390
391 * ``MINYEAR <= year <= MAXYEAR``
392 * ``1 <= month <= 12``
393 * ``1 <= day <= number of days in the given month and year``
394
395 If an argument outside those ranges is given, :exc:`ValueError` is raised.
396
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000397
Georg Brandl116aa622007-08-15 14:28:22 +0000398Other constructors, all class methods:
399
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000400.. classmethod:: date.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000401
402 Return the current local date. This is equivalent to
403 ``date.fromtimestamp(time.time())``.
404
405
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000406.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000407
408 Return the local date corresponding to the POSIX timestamp, such as is returned
Victor Stinner5d272cc2012-03-13 13:35:55 +0100409 by :func:`time.time`. This may raise :exc:`OverflowError`, if the timestamp is out
Victor Stinnerecc6e662012-03-14 00:39:29 +0100410 of the range of values supported by the platform C :c:func:`localtime` function,
411 and :exc:`OSError` on :c:func:`localtime` failure.
Georg Brandl116aa622007-08-15 14:28:22 +0000412 It's common for this to be restricted to years from 1970 through 2038. Note
413 that on non-POSIX systems that include leap seconds in their notion of a
414 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
415
Victor Stinner5d272cc2012-03-13 13:35:55 +0100416 .. versionchanged:: 3.3
417 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
418 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100419 :c:func:`localtime` function. Raise :exc:`OSError` instead of
420 :exc:`ValueError` on :c:func:`localtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100421
Georg Brandl116aa622007-08-15 14:28:22 +0000422
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000423.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000424
425 Return the date corresponding to the proleptic Gregorian ordinal, where January
426 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
427 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
428 d``.
429
Georg Brandl116aa622007-08-15 14:28:22 +0000430
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000431Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000432
433.. attribute:: date.min
434
435 The earliest representable date, ``date(MINYEAR, 1, 1)``.
436
437
438.. attribute:: date.max
439
440 The latest representable date, ``date(MAXYEAR, 12, 31)``.
441
442
443.. attribute:: date.resolution
444
445 The smallest possible difference between non-equal date objects,
446 ``timedelta(days=1)``.
447
Georg Brandl116aa622007-08-15 14:28:22 +0000448
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000449Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000450
451.. attribute:: date.year
452
453 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
454
455
456.. attribute:: date.month
457
458 Between 1 and 12 inclusive.
459
460
461.. attribute:: date.day
462
463 Between 1 and the number of days in the given month of the given year.
464
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000465
Georg Brandl116aa622007-08-15 14:28:22 +0000466Supported operations:
467
468+-------------------------------+----------------------------------------------+
469| Operation | Result |
470+===============================+==============================================+
471| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
472| | from *date1*. (1) |
473+-------------------------------+----------------------------------------------+
474| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
475| | timedelta == date1``. (2) |
476+-------------------------------+----------------------------------------------+
477| ``timedelta = date1 - date2`` | \(3) |
478+-------------------------------+----------------------------------------------+
479| ``date1 < date2`` | *date1* is considered less than *date2* when |
480| | *date1* precedes *date2* in time. (4) |
481+-------------------------------+----------------------------------------------+
482
483Notes:
484
485(1)
486 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
487 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
488 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
489 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
490 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
491
492(2)
493 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
494 isolation can overflow in cases where date1 - timedelta does not.
495 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
496
497(3)
498 This is exact, and cannot overflow. timedelta.seconds and
499 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
500
501(4)
502 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
503 date2.toordinal()``. In order to stop comparison from falling back to the
504 default scheme of comparing object addresses, date comparison normally raises
505 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
506 However, ``NotImplemented`` is returned instead if the other comparand has a
507 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
508 chance at implementing mixed-type comparison. If not, when a :class:`date`
509 object is compared to an object of a different type, :exc:`TypeError` is raised
510 unless the comparison is ``==`` or ``!=``. The latter cases return
511 :const:`False` or :const:`True`, respectively.
512
513Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
514objects are considered to be true.
515
516Instance methods:
517
Georg Brandl116aa622007-08-15 14:28:22 +0000518.. method:: date.replace(year, month, day)
519
Senthil Kumarana6bac952011-07-04 11:28:30 -0700520 Return a date with the same value, except for those parameters given new
521 values by whichever keyword arguments are specified. For example, if ``d ==
522 date(2002, 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000523
524
525.. method:: date.timetuple()
526
527 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
528 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
529 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000530 d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1,
531 1).toordinal() + 1`` is the day number within the current year starting with
532 ``1`` for January 1st.
Georg Brandl116aa622007-08-15 14:28:22 +0000533
534
535.. method:: date.toordinal()
536
537 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
538 has ordinal 1. For any :class:`date` object *d*,
539 ``date.fromordinal(d.toordinal()) == d``.
540
541
542.. method:: date.weekday()
543
544 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
545 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
546 :meth:`isoweekday`.
547
548
549.. method:: date.isoweekday()
550
551 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
552 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
553 :meth:`weekday`, :meth:`isocalendar`.
554
555
556.. method:: date.isocalendar()
557
558 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
559
560 The ISO calendar is a widely used variant of the Gregorian calendar. See
Mark Dickinsonf964ac22009-11-03 16:29:10 +0000561 http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
562 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000563
564 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
565 Monday and ends on a Sunday. The first week of an ISO year is the first
566 (Gregorian) calendar week of a year containing a Thursday. This is called week
567 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
568
569 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
570 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
571 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
572 4).isocalendar() == (2004, 1, 7)``.
573
574
575.. method:: date.isoformat()
576
577 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
578 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
579
580
581.. method:: date.__str__()
582
583 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
584
585
586.. method:: date.ctime()
587
588 Return a string representing the date, for example ``date(2002, 12,
589 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
590 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
Georg Brandl60203b42010-10-06 10:11:56 +0000591 :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +0000592 :meth:`date.ctime` does not invoke) conforms to the C standard.
593
594
595.. method:: date.strftime(format)
596
597 Return a string representing the date, controlled by an explicit format string.
David Wolever569a5fa2013-08-12 16:56:02 -0400598 Format codes referring to hours, minutes or seconds will see 0 values. For a
599 complete list of formatting directives, see
600 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000601
Georg Brandl116aa622007-08-15 14:28:22 +0000602
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300603.. method:: date.__format__(format)
604
605 Same as :meth:`.date.strftime`. This makes it possible to specify format
David Wolever569a5fa2013-08-12 16:56:02 -0400606 string for a :class:`.date` object when using :meth:`str.format`. For a
607 complete list of formatting directives, see
608 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300609
610
Christian Heimes895627f2007-12-08 17:28:33 +0000611Example of counting days to an event::
612
613 >>> import time
614 >>> from datetime import date
615 >>> today = date.today()
616 >>> today
617 datetime.date(2007, 12, 5)
618 >>> today == date.fromtimestamp(time.time())
619 True
620 >>> my_birthday = date(today.year, 6, 24)
621 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000622 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000623 >>> my_birthday
624 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000625 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000626 >>> time_to_birthday.days
627 202
628
Christian Heimesfe337bf2008-03-23 21:54:12 +0000629Example of working with :class:`date`:
630
631.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000632
633 >>> from datetime import date
634 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
635 >>> d
636 datetime.date(2002, 3, 11)
637 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000638 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000639 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000640 2002 # year
641 3 # month
642 11 # day
643 0
644 0
645 0
646 0 # weekday (0 = Monday)
647 70 # 70th day in the year
648 -1
649 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000650 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000651 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000652 2002 # ISO year
653 11 # ISO week number
654 1 # ISO day number ( 1 = Monday )
655 >>> d.isoformat()
656 '2002-03-11'
657 >>> d.strftime("%d/%m/%y")
658 '11/03/02'
659 >>> d.strftime("%A %d. %B %Y")
660 'Monday 11. March 2002'
Ezio Melotti09f0dde2013-04-04 09:16:15 +0300661 >>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")
662 'The day is 11, the month is March.'
Christian Heimes895627f2007-12-08 17:28:33 +0000663
Georg Brandl116aa622007-08-15 14:28:22 +0000664
665.. _datetime-datetime:
666
667:class:`datetime` Objects
668-------------------------
669
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300670A :class:`.datetime` object is a single object containing all the information
671from a :class:`date` object and a :class:`.time` object. Like a :class:`date`
672object, :class:`.datetime` assumes the current Gregorian calendar extended in
673both directions; like a time object, :class:`.datetime` assumes there are exactly
Georg Brandl116aa622007-08-15 14:28:22 +00006743600\*24 seconds in every day.
675
676Constructor:
677
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000678.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000679
680 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000681 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
682 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000683
684 * ``MINYEAR <= year <= MAXYEAR``
685 * ``1 <= month <= 12``
686 * ``1 <= day <= number of days in the given month and year``
687 * ``0 <= hour < 24``
688 * ``0 <= minute < 60``
689 * ``0 <= second < 60``
690 * ``0 <= microsecond < 1000000``
691
692 If an argument outside those ranges is given, :exc:`ValueError` is raised.
693
694Other constructors, all class methods:
695
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000696.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000697
698 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
699 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
700 :meth:`fromtimestamp`.
701
702
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000703.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000704
705 Return the current local date and time. If optional argument *tz* is ``None``
706 or not specified, this is like :meth:`today`, but, if possible, supplies more
707 precision than can be gotten from going through a :func:`time.time` timestamp
708 (for example, this may be possible on platforms supplying the C
Georg Brandl60203b42010-10-06 10:11:56 +0000709 :c:func:`gettimeofday` function).
Georg Brandl116aa622007-08-15 14:28:22 +0000710
711 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
712 current date and time are converted to *tz*'s time zone. In this case the
713 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
714 See also :meth:`today`, :meth:`utcnow`.
715
716
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000717.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000718
719 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
720 :meth:`now`, but returns the current UTC date and time, as a naive
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300721 :class:`.datetime` object. An aware current UTC datetime can be obtained by
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000722 calling ``datetime.now(timezone.utc)``. See also :meth:`now`.
Georg Brandl116aa622007-08-15 14:28:22 +0000723
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000724.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000725
726 Return the local date and time corresponding to the POSIX timestamp, such as is
727 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
728 specified, the timestamp is converted to the platform's local date and time, and
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300729 the returned :class:`.datetime` object is naive.
Georg Brandl116aa622007-08-15 14:28:22 +0000730
731 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
732 timestamp is converted to *tz*'s time zone. In this case the result is
733 equivalent to
734 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
735
Victor Stinnerecc6e662012-03-14 00:39:29 +0100736 :meth:`fromtimestamp` may raise :exc:`OverflowError`, if the timestamp is out of
Georg Brandl60203b42010-10-06 10:11:56 +0000737 the range of values supported by the platform C :c:func:`localtime` or
Victor Stinnerecc6e662012-03-14 00:39:29 +0100738 :c:func:`gmtime` functions, and :exc:`OSError` on :c:func:`localtime` or
739 :c:func:`gmtime` failure.
740 It's common for this to be restricted to years in
Georg Brandl116aa622007-08-15 14:28:22 +0000741 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
742 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
743 and then it's possible to have two timestamps differing by a second that yield
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300744 identical :class:`.datetime` objects. See also :meth:`utcfromtimestamp`.
Georg Brandl116aa622007-08-15 14:28:22 +0000745
Victor Stinner5d272cc2012-03-13 13:35:55 +0100746 .. versionchanged:: 3.3
747 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
748 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100749 :c:func:`localtime` or :c:func:`gmtime` functions. Raise :exc:`OSError`
750 instead of :exc:`ValueError` on :c:func:`localtime` or :c:func:`gmtime`
751 failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100752
Georg Brandl116aa622007-08-15 14:28:22 +0000753
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000754.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000755
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300756 Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with
Victor Stinnerecc6e662012-03-14 00:39:29 +0100757 :attr:`tzinfo` ``None``. This may raise :exc:`OverflowError`, if the timestamp is
758 out of the range of values supported by the platform C :c:func:`gmtime` function,
759 and :exc:`OSError` on :c:func:`gmtime` failure.
Georg Brandl116aa622007-08-15 14:28:22 +0000760 It's common for this to be restricted to years in 1970 through 2038. See also
761 :meth:`fromtimestamp`.
762
Alexander Belopolsky54afa552011-04-25 13:00:40 -0400763 On the POSIX compliant platforms, ``utcfromtimestamp(timestamp)``
764 is equivalent to the following expression::
765
766 datetime(1970, 1, 1) + timedelta(seconds=timestamp)
767
Victor Stinner5d272cc2012-03-13 13:35:55 +0100768 .. versionchanged:: 3.3
769 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
770 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100771 :c:func:`gmtime` function. Raise :exc:`OSError` instead of
772 :exc:`ValueError` on :c:func:`gmtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100773
Georg Brandl116aa622007-08-15 14:28:22 +0000774
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000775.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000776
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300777 Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal,
Georg Brandl116aa622007-08-15 14:28:22 +0000778 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
779 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
780 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
781
782
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000783.. classmethod:: datetime.combine(date, time)
Georg Brandl116aa622007-08-15 14:28:22 +0000784
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300785 Return a new :class:`.datetime` object whose date components are equal to the
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800786 given :class:`date` object's, and whose time components and :attr:`tzinfo`
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300787 attributes are equal to the given :class:`.time` object's. For any
788 :class:`.datetime` object *d*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800789 ``d == datetime.combine(d.date(), d.timetz())``. If date is a
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300790 :class:`.datetime` object, its time components and :attr:`tzinfo` attributes
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800791 are ignored.
Georg Brandl116aa622007-08-15 14:28:22 +0000792
793
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000794.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000795
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300796 Return a :class:`.datetime` corresponding to *date_string*, parsed according to
Georg Brandl116aa622007-08-15 14:28:22 +0000797 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
798 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
799 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 -0400800 time tuple. For a complete list of formatting directives, see
801 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000802
Georg Brandl116aa622007-08-15 14:28:22 +0000803
Georg Brandl116aa622007-08-15 14:28:22 +0000804
805Class attributes:
806
Georg Brandl116aa622007-08-15 14:28:22 +0000807.. attribute:: datetime.min
808
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300809 The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1,
Georg Brandl116aa622007-08-15 14:28:22 +0000810 tzinfo=None)``.
811
812
813.. attribute:: datetime.max
814
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300815 The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
Georg Brandl116aa622007-08-15 14:28:22 +0000816 59, 999999, tzinfo=None)``.
817
818
819.. attribute:: datetime.resolution
820
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300821 The smallest possible difference between non-equal :class:`.datetime` objects,
Georg Brandl116aa622007-08-15 14:28:22 +0000822 ``timedelta(microseconds=1)``.
823
Georg Brandl116aa622007-08-15 14:28:22 +0000824
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000825Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000826
827.. attribute:: datetime.year
828
829 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
830
831
832.. attribute:: datetime.month
833
834 Between 1 and 12 inclusive.
835
836
837.. attribute:: datetime.day
838
839 Between 1 and the number of days in the given month of the given year.
840
841
842.. attribute:: datetime.hour
843
844 In ``range(24)``.
845
846
847.. attribute:: datetime.minute
848
849 In ``range(60)``.
850
851
852.. attribute:: datetime.second
853
854 In ``range(60)``.
855
856
857.. attribute:: datetime.microsecond
858
859 In ``range(1000000)``.
860
861
862.. attribute:: datetime.tzinfo
863
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300864 The object passed as the *tzinfo* argument to the :class:`.datetime` constructor,
Georg Brandl116aa622007-08-15 14:28:22 +0000865 or ``None`` if none was passed.
866
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000867
Georg Brandl116aa622007-08-15 14:28:22 +0000868Supported operations:
869
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300870+---------------------------------------+--------------------------------+
871| Operation | Result |
872+=======================================+================================+
873| ``datetime2 = datetime1 + timedelta`` | \(1) |
874+---------------------------------------+--------------------------------+
875| ``datetime2 = datetime1 - timedelta`` | \(2) |
876+---------------------------------------+--------------------------------+
877| ``timedelta = datetime1 - datetime2`` | \(3) |
878+---------------------------------------+--------------------------------+
879| ``datetime1 < datetime2`` | Compares :class:`.datetime` to |
880| | :class:`.datetime`. (4) |
881+---------------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000882
883(1)
884 datetime2 is a duration of timedelta removed from datetime1, moving forward in
885 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
Senthil Kumarana6bac952011-07-04 11:28:30 -0700886 result has the same :attr:`tzinfo` attribute as the input datetime, and
887 datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
888 datetime2.year would be smaller than :const:`MINYEAR` or larger than
889 :const:`MAXYEAR`. Note that no time zone adjustments are done even if the
890 input is an aware object.
Georg Brandl116aa622007-08-15 14:28:22 +0000891
892(2)
893 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
Senthil Kumarana6bac952011-07-04 11:28:30 -0700894 addition, the result has the same :attr:`tzinfo` attribute as the input
895 datetime, and no time zone adjustments are done even if the input is aware.
896 This isn't quite equivalent to datetime1 + (-timedelta), because -timedelta
897 in isolation can overflow in cases where datetime1 - timedelta does not.
Georg Brandl116aa622007-08-15 14:28:22 +0000898
899(3)
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300900 Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if
Georg Brandl116aa622007-08-15 14:28:22 +0000901 both operands are naive, or if both are aware. If one is aware and the other is
902 naive, :exc:`TypeError` is raised.
903
Senthil Kumarana6bac952011-07-04 11:28:30 -0700904 If both are naive, or both are aware and have the same :attr:`tzinfo` attribute,
905 the :attr:`tzinfo` attributes are ignored, and the result is a :class:`timedelta`
Georg Brandl116aa622007-08-15 14:28:22 +0000906 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
907 are done in this case.
908
Senthil Kumarana6bac952011-07-04 11:28:30 -0700909 If both are aware and have different :attr:`tzinfo` attributes, ``a-b`` acts
910 as if *a* and *b* were first converted to naive UTC datetimes first. The
911 result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
912 - b.utcoffset())`` except that the implementation never overflows.
Georg Brandl116aa622007-08-15 14:28:22 +0000913
914(4)
915 *datetime1* is considered less than *datetime2* when *datetime1* precedes
916 *datetime2* in time.
917
Alexander Belopolsky08313822012-06-15 20:19:47 -0400918 If one comparand is naive and the other is aware, :exc:`TypeError`
919 is raised if an order comparison is attempted. For equality
920 comparisons, naive instances are never equal to aware instances.
921
Senthil Kumarana6bac952011-07-04 11:28:30 -0700922 If both comparands are aware, and have the same :attr:`tzinfo` attribute, the
923 common :attr:`tzinfo` attribute is ignored and the base datetimes are
924 compared. If both comparands are aware and have different :attr:`tzinfo`
925 attributes, the comparands are first adjusted by subtracting their UTC
926 offsets (obtained from ``self.utcoffset()``).
Georg Brandl116aa622007-08-15 14:28:22 +0000927
Alexander Belopolsky08313822012-06-15 20:19:47 -0400928 .. versionchanged:: 3.3
Éric Araujob0f08952012-06-24 16:22:09 -0400929 Equality comparisons between naive and aware :class:`datetime`
930 instances don't raise :exc:`TypeError`.
Alexander Belopolsky08313822012-06-15 20:19:47 -0400931
Georg Brandl116aa622007-08-15 14:28:22 +0000932 .. note::
933
934 In order to stop comparison from falling back to the default scheme of comparing
935 object addresses, datetime comparison normally raises :exc:`TypeError` if the
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300936 other comparand isn't also a :class:`.datetime` object. However,
Georg Brandl116aa622007-08-15 14:28:22 +0000937 ``NotImplemented`` is returned instead if the other comparand has a
938 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300939 chance at implementing mixed-type comparison. If not, when a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +0000940 object is compared to an object of a different type, :exc:`TypeError` is raised
941 unless the comparison is ``==`` or ``!=``. The latter cases return
942 :const:`False` or :const:`True`, respectively.
943
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300944:class:`.datetime` objects can be used as dictionary keys. In Boolean contexts,
945all :class:`.datetime` objects are considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +0000946
947Instance methods:
948
Georg Brandl116aa622007-08-15 14:28:22 +0000949.. method:: datetime.date()
950
951 Return :class:`date` object with same year, month and day.
952
953
954.. method:: datetime.time()
955
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300956 Return :class:`.time` object with same hour, minute, second and microsecond.
Georg Brandl116aa622007-08-15 14:28:22 +0000957 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
958
959
960.. method:: datetime.timetz()
961
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300962 Return :class:`.time` object with same hour, minute, second, microsecond, and
Senthil Kumarana6bac952011-07-04 11:28:30 -0700963 tzinfo attributes. See also method :meth:`time`.
Georg Brandl116aa622007-08-15 14:28:22 +0000964
965
966.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
967
Senthil Kumarana6bac952011-07-04 11:28:30 -0700968 Return a datetime with the same attributes, except for those attributes given
969 new values by whichever keyword arguments are specified. Note that
970 ``tzinfo=None`` can be specified to create a naive datetime from an aware
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800971 datetime with no conversion of date and time data.
Georg Brandl116aa622007-08-15 14:28:22 +0000972
973
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -0400974.. method:: datetime.astimezone(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000975
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -0400976 Return a :class:`datetime` object with new :attr:`tzinfo` attribute *tz*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800977 adjusting the date and time data so the result is the same UTC time as
Senthil Kumarana6bac952011-07-04 11:28:30 -0700978 *self*, but in *tz*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +0000979
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -0400980 If provided, *tz* must be an instance of a :class:`tzinfo` subclass, and its
Georg Brandl116aa622007-08-15 14:28:22 +0000981 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
982 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
983 not return ``None``).
984
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -0400985 If called without arguments (or with ``tz=None``) the system local
986 timezone is assumed. The ``tzinfo`` attribute of the converted
987 datetime instance will be set to an instance of :class:`timezone`
988 with the zone name and offset obtained from the OS.
989
Georg Brandl116aa622007-08-15 14:28:22 +0000990 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800991 adjustment of date or time data is performed. Else the result is local
Senthil Kumarana6bac952011-07-04 11:28:30 -0700992 time in time zone *tz*, representing the same UTC time as *self*: after
993 ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800994 the same date and time data as ``dt - dt.utcoffset()``. The discussion
Senthil Kumarana6bac952011-07-04 11:28:30 -0700995 of class :class:`tzinfo` explains the cases at Daylight Saving Time transition
996 boundaries where this cannot be achieved (an issue only if *tz* models both
997 standard and daylight time).
Georg Brandl116aa622007-08-15 14:28:22 +0000998
999 If you merely want to attach a time zone object *tz* to a datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001000 adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you
Georg Brandl116aa622007-08-15 14:28:22 +00001001 merely want to remove the time zone object from an aware datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001002 conversion of date and time data, use ``dt.replace(tzinfo=None)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001003
1004 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
1005 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
1006 Ignoring error cases, :meth:`astimezone` acts like::
1007
1008 def astimezone(self, tz):
1009 if self.tzinfo is tz:
1010 return self
1011 # Convert self to UTC, and attach the new time zone object.
1012 utc = (self - self.utcoffset()).replace(tzinfo=tz)
1013 # Convert from UTC to tz's local time.
1014 return tz.fromutc(utc)
1015
Georg Brandlee0be402012-06-26 09:14:40 +02001016 .. versionchanged:: 3.3
1017 *tz* now can be omitted.
1018
Georg Brandl116aa622007-08-15 14:28:22 +00001019
1020.. method:: datetime.utcoffset()
1021
1022 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1023 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
1024 return ``None``, or a :class:`timedelta` object representing a whole number of
1025 minutes with magnitude less than one day.
1026
1027
1028.. method:: datetime.dst()
1029
1030 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1031 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
1032 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1033 with magnitude less than one day.
1034
1035
1036.. method:: datetime.tzname()
1037
1038 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1039 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
1040 ``None`` or a string object,
1041
1042
1043.. method:: datetime.timetuple()
1044
1045 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
1046 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
Alexander Belopolsky64912482010-06-08 18:59:20 +00001047 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
1048 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
1049 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
1050 of the result is set according to the :meth:`dst` method: :attr:`tzinfo` is
Georg Brandl682d7e02010-10-06 10:26:05 +00001051 ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
Alexander Belopolsky64912482010-06-08 18:59:20 +00001052 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
Alexander Belopolskyda62f2f2010-06-09 17:11:01 +00001053 else :attr:`tm_isdst` is set to ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +00001054
1055
1056.. method:: datetime.utctimetuple()
1057
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001058 If :class:`.datetime` instance *d* is naive, this is the same as
Georg Brandl116aa622007-08-15 14:28:22 +00001059 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
1060 ``d.dst()`` returns. DST is never in effect for a UTC time.
1061
1062 If *d* is aware, *d* is normalized to UTC time, by subtracting
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00001063 ``d.utcoffset()``, and a :class:`time.struct_time` for the
1064 normalized time is returned. :attr:`tm_isdst` is forced to 0. Note
1065 that an :exc:`OverflowError` may be raised if *d*.year was
1066 ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
Georg Brandl116aa622007-08-15 14:28:22 +00001067 boundary.
1068
1069
1070.. method:: datetime.toordinal()
1071
1072 Return the proleptic Gregorian ordinal of the date. The same as
1073 ``self.date().toordinal()``.
1074
Alexander Belopolskya4415142012-06-08 12:33:09 -04001075.. method:: datetime.timestamp()
1076
1077 Return POSIX timestamp corresponding to the :class:`datetime`
1078 instance. The return value is a :class:`float` similar to that
1079 returned by :func:`time.time`.
1080
1081 Naive :class:`datetime` instances are assumed to represent local
1082 time and this method relies on the platform C :c:func:`mktime`
1083 function to perform the conversion. Since :class:`datetime`
1084 supports wider range of values than :c:func:`mktime` on many
1085 platforms, this method may raise :exc:`OverflowError` for times far
1086 in the past or far in the future.
1087
1088 For aware :class:`datetime` instances, the return value is computed
1089 as::
1090
1091 (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
1092
1093 .. versionadded:: 3.3
1094
1095 .. note::
1096
1097 There is no method to obtain the POSIX timestamp directly from a
1098 naive :class:`datetime` instance representing UTC time. If your
1099 application uses this convention and your system timezone is not
1100 set to UTC, you can obtain the POSIX timestamp by supplying
1101 ``tzinfo=timezone.utc``::
1102
1103 timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
1104
1105 or by calculating the timestamp directly::
1106
1107 timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001108
1109.. method:: datetime.weekday()
1110
1111 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
1112 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
1113
1114
1115.. method:: datetime.isoweekday()
1116
1117 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
1118 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
1119 :meth:`isocalendar`.
1120
1121
1122.. method:: datetime.isocalendar()
1123
1124 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
1125 ``self.date().isocalendar()``.
1126
1127
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001128.. method:: datetime.isoformat(sep='T')
Georg Brandl116aa622007-08-15 14:28:22 +00001129
1130 Return a string representing the date and time in ISO 8601 format,
1131 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
1132 YYYY-MM-DDTHH:MM:SS
1133
1134 If :meth:`utcoffset` does not return ``None``, a 6-character string is
1135 appended, giving the UTC offset in (signed) hours and minutes:
1136 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
1137 YYYY-MM-DDTHH:MM:SS+HH:MM
1138
1139 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +00001140 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +00001141
1142 >>> from datetime import tzinfo, timedelta, datetime
1143 >>> class TZ(tzinfo):
1144 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1145 ...
1146 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1147 '2002-12-25 00:00:00-06:39'
1148
1149
1150.. method:: datetime.__str__()
1151
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001152 For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to
Georg Brandl116aa622007-08-15 14:28:22 +00001153 ``d.isoformat(' ')``.
1154
1155
1156.. method:: datetime.ctime()
1157
1158 Return a string representing the date and time, for example ``datetime(2002, 12,
1159 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1160 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
Georg Brandl60203b42010-10-06 10:11:56 +00001161 native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +00001162 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1163
1164
1165.. method:: datetime.strftime(format)
1166
1167 Return a string representing the date and time, controlled by an explicit format
David Wolever569a5fa2013-08-12 16:56:02 -04001168 string. For a complete list of formatting directives, see
1169 :ref:`strftime-strptime-behavior`.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001170
Georg Brandl116aa622007-08-15 14:28:22 +00001171
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001172.. method:: datetime.__format__(format)
1173
1174 Same as :meth:`.datetime.strftime`. This makes it possible to specify format
David Wolever569a5fa2013-08-12 16:56:02 -04001175 string for a :class:`.datetime` object when using :meth:`str.format`. For a
1176 complete list of formatting directives, see
1177 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001178
1179
Christian Heimesfe337bf2008-03-23 21:54:12 +00001180Examples of working with datetime objects:
1181
1182.. doctest::
1183
Christian Heimes895627f2007-12-08 17:28:33 +00001184 >>> from datetime import datetime, date, time
1185 >>> # Using datetime.combine()
1186 >>> d = date(2005, 7, 14)
1187 >>> t = time(12, 30)
1188 >>> datetime.combine(d, t)
1189 datetime.datetime(2005, 7, 14, 12, 30)
1190 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001191 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001192 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001193 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001194 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1195 >>> # Using datetime.strptime()
1196 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1197 >>> dt
1198 datetime.datetime(2006, 11, 21, 16, 30)
1199 >>> # Using datetime.timetuple() to get tuple of all attributes
1200 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001201 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001202 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001203 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001204 2006 # year
1205 11 # month
1206 21 # day
1207 16 # hour
1208 30 # minute
1209 0 # second
1210 1 # weekday (0 = Monday)
1211 325 # number of days since 1st January
1212 -1 # dst - method tzinfo.dst() returned None
1213 >>> # Date in ISO format
1214 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001215 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001216 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001217 ...
1218 2006 # ISO year
1219 47 # ISO week
1220 2 # ISO weekday
1221 >>> # Formatting datetime
1222 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1223 'Tuesday, 21. November 2006 04:30PM'
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001224 >>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
1225 'The day is 21, the month is November, the time is 04:30PM.'
Christian Heimes895627f2007-12-08 17:28:33 +00001226
Christian Heimesfe337bf2008-03-23 21:54:12 +00001227Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001228
1229 >>> from datetime import timedelta, datetime, tzinfo
1230 >>> class GMT1(tzinfo):
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001231 ... def utcoffset(self, dt):
1232 ... return timedelta(hours=1) + self.dst(dt)
1233 ... def dst(self, dt):
1234 ... # DST starts last Sunday in March
Christian Heimes895627f2007-12-08 17:28:33 +00001235 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1236 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001237 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001238 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001239 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1240 ... return timedelta(hours=1)
1241 ... else:
1242 ... return timedelta(0)
1243 ... def tzname(self,dt):
1244 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001245 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001246 >>> class GMT2(tzinfo):
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001247 ... def utcoffset(self, dt):
1248 ... return timedelta(hours=2) + self.dst(dt)
1249 ... def dst(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001250 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001251 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001252 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001253 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001254 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001255 ... return timedelta(hours=1)
Christian Heimes895627f2007-12-08 17:28:33 +00001256 ... else:
1257 ... return timedelta(0)
1258 ... def tzname(self,dt):
1259 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001260 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001261 >>> gmt1 = GMT1()
1262 >>> # Daylight Saving Time
1263 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1264 >>> dt1.dst()
1265 datetime.timedelta(0)
1266 >>> dt1.utcoffset()
1267 datetime.timedelta(0, 3600)
1268 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1269 >>> dt2.dst()
1270 datetime.timedelta(0, 3600)
1271 >>> dt2.utcoffset()
1272 datetime.timedelta(0, 7200)
1273 >>> # Convert datetime to another time zone
1274 >>> dt3 = dt2.astimezone(GMT2())
1275 >>> dt3 # doctest: +ELLIPSIS
1276 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1277 >>> dt2 # doctest: +ELLIPSIS
1278 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1279 >>> dt2.utctimetuple() == dt3.utctimetuple()
1280 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001281
Christian Heimes895627f2007-12-08 17:28:33 +00001282
Georg Brandl116aa622007-08-15 14:28:22 +00001283
1284.. _datetime-time:
1285
1286:class:`time` Objects
1287---------------------
1288
1289A time object represents a (local) time of day, independent of any particular
1290day, and subject to adjustment via a :class:`tzinfo` object.
1291
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001292.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001293
1294 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001295 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001296 following ranges:
1297
1298 * ``0 <= hour < 24``
1299 * ``0 <= minute < 60``
1300 * ``0 <= second < 60``
1301 * ``0 <= microsecond < 1000000``.
1302
1303 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1304 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1305
1306Class attributes:
1307
1308
1309.. attribute:: time.min
1310
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001311 The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001312
1313
1314.. attribute:: time.max
1315
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001316 The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001317
1318
1319.. attribute:: time.resolution
1320
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001321 The smallest possible difference between non-equal :class:`.time` objects,
1322 ``timedelta(microseconds=1)``, although note that arithmetic on
1323 :class:`.time` objects is not supported.
Georg Brandl116aa622007-08-15 14:28:22 +00001324
Georg Brandl116aa622007-08-15 14:28:22 +00001325
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001326Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001327
1328.. attribute:: time.hour
1329
1330 In ``range(24)``.
1331
1332
1333.. attribute:: time.minute
1334
1335 In ``range(60)``.
1336
1337
1338.. attribute:: time.second
1339
1340 In ``range(60)``.
1341
1342
1343.. attribute:: time.microsecond
1344
1345 In ``range(1000000)``.
1346
1347
1348.. attribute:: time.tzinfo
1349
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001350 The object passed as the tzinfo argument to the :class:`.time` constructor, or
Georg Brandl116aa622007-08-15 14:28:22 +00001351 ``None`` if none was passed.
1352
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001353
Georg Brandl116aa622007-08-15 14:28:22 +00001354Supported operations:
1355
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001356* comparison of :class:`.time` to :class:`.time`, where *a* is considered less
Georg Brandl116aa622007-08-15 14:28:22 +00001357 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
Alexander Belopolsky08313822012-06-15 20:19:47 -04001358 is aware, :exc:`TypeError` is raised if an order comparison is attempted. For equality
1359 comparisons, naive instances are never equal to aware instances.
1360
1361 If both comparands are aware, and have
Senthil Kumarana6bac952011-07-04 11:28:30 -07001362 the same :attr:`tzinfo` attribute, the common :attr:`tzinfo` attribute is
1363 ignored and the base times are compared. If both comparands are aware and
1364 have different :attr:`tzinfo` attributes, the comparands are first adjusted by
1365 subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
1366 to stop mixed-type comparisons from falling back to the default comparison by
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001367 object address, when a :class:`.time` object is compared to an object of a
Senthil Kumaran3aac1792011-07-04 11:43:51 -07001368 different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
Senthil Kumarana6bac952011-07-04 11:28:30 -07001369 ``!=``. The latter cases return :const:`False` or :const:`True`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +00001370
Alexander Belopolsky08313822012-06-15 20:19:47 -04001371 .. versionchanged:: 3.3
Éric Araujob0f08952012-06-24 16:22:09 -04001372 Equality comparisons between naive and aware :class:`time` instances
1373 don't raise :exc:`TypeError`.
Alexander Belopolsky08313822012-06-15 20:19:47 -04001374
Georg Brandl116aa622007-08-15 14:28:22 +00001375* hash, use as dict key
1376
1377* efficient pickling
1378
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001379* in Boolean contexts, a :class:`.time` object is considered to be true if and
Georg Brandl116aa622007-08-15 14:28:22 +00001380 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1381 ``0`` if that's ``None``), the result is non-zero.
1382
Georg Brandl116aa622007-08-15 14:28:22 +00001383
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001384Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001385
1386.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1387
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001388 Return a :class:`.time` with the same value, except for those attributes given
Senthil Kumarana6bac952011-07-04 11:28:30 -07001389 new values by whichever keyword arguments are specified. Note that
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001390 ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
1391 aware :class:`.time`, without conversion of the time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001392
1393
1394.. method:: time.isoformat()
1395
1396 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1397 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1398 6-character string is appended, giving the UTC offset in (signed) hours and
1399 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1400
1401
1402.. method:: time.__str__()
1403
1404 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1405
1406
1407.. method:: time.strftime(format)
1408
David Wolever569a5fa2013-08-12 16:56:02 -04001409 Return a string representing the time, controlled by an explicit format
1410 string. For a complete list of formatting directives, see
David Woleverbbf4a462013-08-12 17:15:36 -04001411 :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001412
1413
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001414.. method:: time.__format__(format)
1415
1416 Same as :meth:`.time.strftime`. This makes it possible to specify format string
David Wolever569a5fa2013-08-12 16:56:02 -04001417 for a :class:`.time` object when using :meth:`str.format`. For a
1418 complete list of formatting directives, see
1419 :ref:`strftime-strptime-behavior`.
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001420
1421
Georg Brandl116aa622007-08-15 14:28:22 +00001422.. method:: time.utcoffset()
1423
1424 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1425 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1426 return ``None`` or a :class:`timedelta` object representing a whole number of
1427 minutes with magnitude less than one day.
1428
1429
1430.. method:: time.dst()
1431
1432 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1433 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1434 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1435 with magnitude less than one day.
1436
1437
1438.. method:: time.tzname()
1439
1440 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1441 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1442 return ``None`` or a string object.
1443
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001444
Christian Heimesfe337bf2008-03-23 21:54:12 +00001445Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001446
Christian Heimes895627f2007-12-08 17:28:33 +00001447 >>> from datetime import time, tzinfo
1448 >>> class GMT1(tzinfo):
1449 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001450 ... return timedelta(hours=1)
1451 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001452 ... return timedelta(0)
1453 ... def tzname(self,dt):
1454 ... return "Europe/Prague"
1455 ...
1456 >>> t = time(12, 10, 30, tzinfo=GMT1())
1457 >>> t # doctest: +ELLIPSIS
1458 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1459 >>> gmt = GMT1()
1460 >>> t.isoformat()
1461 '12:10:30+01:00'
1462 >>> t.dst()
1463 datetime.timedelta(0)
1464 >>> t.tzname()
1465 'Europe/Prague'
1466 >>> t.strftime("%H:%M:%S %Z")
1467 '12:10:30 Europe/Prague'
Ezio Melotti09f0dde2013-04-04 09:16:15 +03001468 >>> 'The {} is {:%H:%M}.'.format("time", t)
1469 'The time is 12:10.'
Christian Heimes895627f2007-12-08 17:28:33 +00001470
Georg Brandl116aa622007-08-15 14:28:22 +00001471
1472.. _datetime-tzinfo:
1473
1474:class:`tzinfo` Objects
1475-----------------------
1476
Brett Cannone1327f72009-01-29 04:10:21 +00001477:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001478instantiated directly. You need to derive a concrete subclass, and (at least)
1479supply implementations of the standard :class:`tzinfo` methods needed by the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001480:class:`.datetime` methods you use. The :mod:`datetime` module supplies
Andrew Svetlovdfe109e2012-12-17 13:42:04 +02001481a simple concrete subclass of :class:`tzinfo` :class:`timezone` which can represent
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001482timezones with fixed offset from UTC such as UTC itself or North American EST and
1483EDT.
Georg Brandl116aa622007-08-15 14:28:22 +00001484
1485An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001486constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
Senthil Kumarana6bac952011-07-04 11:28:30 -07001487view their attributes as being in local time, and the :class:`tzinfo` object
Georg Brandl116aa622007-08-15 14:28:22 +00001488supports methods revealing offset of local time from UTC, the name of the time
1489zone, and DST offset, all relative to a date or time object passed to them.
1490
1491Special requirement for pickling: A :class:`tzinfo` subclass must have an
1492:meth:`__init__` method that can be called with no arguments, else it can be
1493pickled but possibly not unpickled again. This is a technical requirement that
1494may be relaxed in the future.
1495
1496A concrete subclass of :class:`tzinfo` may need to implement the following
1497methods. Exactly which methods are needed depends on the uses made of aware
1498:mod:`datetime` objects. If in doubt, simply implement all of them.
1499
1500
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001501.. method:: tzinfo.utcoffset(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001502
1503 Return offset of local time from UTC, in minutes east of UTC. If local time is
1504 west of UTC, this should be negative. Note that this is intended to be the
1505 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1506 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1507 the UTC offset isn't known, return ``None``. Else the value returned must be a
1508 :class:`timedelta` object specifying a whole number of minutes in the range
1509 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1510 than one day). Most implementations of :meth:`utcoffset` will probably look
1511 like one of these two::
1512
1513 return CONSTANT # fixed-offset class
1514 return CONSTANT + self.dst(dt) # daylight-aware class
1515
1516 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1517 ``None`` either.
1518
1519 The default implementation of :meth:`utcoffset` raises
1520 :exc:`NotImplementedError`.
1521
1522
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001523.. method:: tzinfo.dst(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001524
1525 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1526 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1527 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1528 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1529 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1530 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1531 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -07001532 attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
1533 should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
1534 DST changes when crossing time zones.
Georg Brandl116aa622007-08-15 14:28:22 +00001535
1536 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1537 daylight times must be consistent in this sense:
1538
1539 ``tz.utcoffset(dt) - tz.dst(dt)``
1540
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001541 must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo ==
Georg Brandl116aa622007-08-15 14:28:22 +00001542 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1543 zone's "standard offset", which should not depend on the date or the time, but
1544 only on geographic location. The implementation of :meth:`datetime.astimezone`
1545 relies on this, but cannot detect violations; it's the programmer's
1546 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1547 this, it may be able to override the default implementation of
1548 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1549
1550 Most implementations of :meth:`dst` will probably look like one of these two::
1551
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001552 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001553 # a fixed-offset class: doesn't account for DST
1554 return timedelta(0)
1555
1556 or ::
1557
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001558 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001559 # Code to set dston and dstoff to the time zone's DST
1560 # transition times based on the input dt.year, and expressed
1561 # in standard local time. Then
1562
1563 if dston <= dt.replace(tzinfo=None) < dstoff:
1564 return timedelta(hours=1)
1565 else:
1566 return timedelta(0)
1567
1568 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1569
1570
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001571.. method:: tzinfo.tzname(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001572
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001573 Return the time zone name corresponding to the :class:`.datetime` object *dt*, as
Georg Brandl116aa622007-08-15 14:28:22 +00001574 a string. Nothing about string names is defined by the :mod:`datetime` module,
1575 and there's no requirement that it mean anything in particular. For example,
1576 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1577 valid replies. Return ``None`` if a string name isn't known. Note that this is
1578 a method rather than a fixed string primarily because some :class:`tzinfo`
1579 subclasses will wish to return different names depending on the specific value
1580 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1581 daylight time.
1582
1583 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1584
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001585
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001586These methods are called by a :class:`.datetime` or :class:`.time` object, in
1587response to their methods of the same names. A :class:`.datetime` object passes
1588itself as the argument, and a :class:`.time` object passes ``None`` as the
Georg Brandl116aa622007-08-15 14:28:22 +00001589argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001590accept a *dt* argument of ``None``, or of class :class:`.datetime`.
Georg Brandl116aa622007-08-15 14:28:22 +00001591
1592When ``None`` is passed, it's up to the class designer to decide the best
1593response. For example, returning ``None`` is appropriate if the class wishes to
1594say that time objects don't participate in the :class:`tzinfo` protocols. It
1595may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1596there is no other convention for discovering the standard offset.
1597
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001598When a :class:`.datetime` object is passed in response to a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +00001599method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1600rely on this, unless user code calls :class:`tzinfo` methods directly. The
1601intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1602time, and not need worry about objects in other timezones.
1603
1604There is one more :class:`tzinfo` method that a subclass may wish to override:
1605
1606
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001607.. method:: tzinfo.fromutc(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001608
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001609 This is called from the default :class:`datetime.astimezone()`
1610 implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s
1611 date and time data are to be viewed as expressing a UTC time. The purpose
1612 of :meth:`fromutc` is to adjust the date and time data, returning an
Senthil Kumarana6bac952011-07-04 11:28:30 -07001613 equivalent datetime in *self*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00001614
1615 Most :class:`tzinfo` subclasses should be able to inherit the default
1616 :meth:`fromutc` implementation without problems. It's strong enough to handle
1617 fixed-offset time zones, and time zones accounting for both standard and
1618 daylight time, and the latter even if the DST transition times differ in
1619 different years. An example of a time zone the default :meth:`fromutc`
1620 implementation may not handle correctly in all cases is one where the standard
1621 offset (from UTC) depends on the specific date and time passed, which can happen
1622 for political reasons. The default implementations of :meth:`astimezone` and
1623 :meth:`fromutc` may not produce the result you want if the result is one of the
1624 hours straddling the moment the standard offset changes.
1625
1626 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1627 like::
1628
1629 def fromutc(self, dt):
1630 # raise ValueError error if dt.tzinfo is not self
1631 dtoff = dt.utcoffset()
1632 dtdst = dt.dst()
1633 # raise ValueError if dtoff is None or dtdst is None
1634 delta = dtoff - dtdst # this is self's standard offset
1635 if delta:
1636 dt += delta # convert to standard local time
1637 dtdst = dt.dst()
1638 # raise ValueError if dtdst is None
1639 if dtdst:
1640 return dt + dtdst
1641 else:
1642 return dt
1643
1644Example :class:`tzinfo` classes:
1645
1646.. literalinclude:: ../includes/tzinfo-examples.py
1647
Georg Brandl116aa622007-08-15 14:28:22 +00001648Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1649subclass accounting for both standard and daylight time, at the DST transition
1650points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00001651minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
16521:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001653
1654 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1655 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1656 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1657
1658 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1659
1660 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1661
1662When DST starts (the "start" line), the local wall clock leaps from 1:59 to
16633:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1664``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1665begins. In order for :meth:`astimezone` to make this guarantee, the
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001666:meth:`tzinfo.dst` method must consider times in the "missing hour" (2:MM for
Georg Brandl116aa622007-08-15 14:28:22 +00001667Eastern) to be in daylight time.
1668
1669When DST ends (the "end" line), there's a potentially worse problem: there's an
1670hour that can't be spelled unambiguously in local wall time: the last hour of
1671daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1672daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1673to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1674:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1675hours into the same local hour then. In the Eastern example, UTC times of the
1676form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1677:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1678consider times in the "repeated hour" to be in standard time. This is easily
1679arranged, as in the example, by expressing DST switch times in the time zone's
1680standard local time.
1681
1682Applications that can't bear such ambiguities should avoid using hybrid
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001683:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`,
1684or any other fixed-offset :class:`tzinfo` subclass (such as a class representing
1685only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
1686
Sandro Tosid11d0d62012-04-24 19:46:06 +02001687.. seealso::
1688
1689 `pytz <http://pypi.python.org/pypi/pytz/>`_
Sandro Tosi100b8892012-04-28 11:19:37 +02001690 The standard library has no :class:`tzinfo` instances except for UTC, but
1691 there exists a third-party library which brings the *IANA timezone
1692 database* (also known as the Olson database) to Python: *pytz*.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001693
Sandro Tosi100b8892012-04-28 11:19:37 +02001694 *pytz* contains up-to-date information and its usage is recommended.
1695
1696 `IANA timezone database <http://www.iana.org/time-zones>`_
1697 The Time Zone Database (often called tz or zoneinfo) contains code and
1698 data that represent the history of local time for many representative
1699 locations around the globe. It is updated periodically to reflect changes
1700 made by political bodies to time zone boundaries, UTC offsets, and
1701 daylight-saving rules.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001702
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001703
1704.. _datetime-timezone:
1705
1706:class:`timezone` Objects
1707--------------------------
1708
Alexander Belopolsky6d3c9a62011-05-04 10:28:26 -04001709The :class:`timezone` class is a subclass of :class:`tzinfo`, each
1710instance of which represents a timezone defined by a fixed offset from
1711UTC. Note that objects of this class cannot be used to represent
1712timezone information in the locations where different offsets are used
1713in different days of the year or where historical changes have been
1714made to civil time.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001715
1716
1717.. class:: timezone(offset[, name])
1718
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001719 The *offset* argument must be specified as a :class:`timedelta`
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001720 object representing the difference between the local time and UTC. It must
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001721 be strictly between ``-timedelta(hours=24)`` and
1722 ``timedelta(hours=24)`` and represent a whole number of minutes,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001723 otherwise :exc:`ValueError` is raised.
1724
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001725 The *name* argument is optional. If specified it must be a string that
1726 is used as the value returned by the ``tzname(dt)`` method. Otherwise,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001727 ``tzname(dt)`` returns a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001728 *offset*, HH and MM are two digits of ``offset.hours`` and
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001729 ``offset.minutes`` respectively.
1730
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001731.. method:: timezone.utcoffset(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001732
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001733 Return the fixed value specified when the :class:`timezone` instance is
1734 constructed. The *dt* argument is ignored. The return value is a
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001735 :class:`timedelta` instance equal to the difference between the
1736 local time and UTC.
1737
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001738.. method:: timezone.tzname(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
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001741 constructed or a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001742 *offset*, HH and MM are two digits of ``offset.hours`` and
1743 ``offset.minutes`` respectively.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001744
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001745.. method:: timezone.dst(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001746
1747 Always returns ``None``.
1748
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001749.. method:: timezone.fromutc(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001750
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001751 Return ``dt + offset``. The *dt* argument must be an aware
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001752 :class:`.datetime` instance, with ``tzinfo`` set to ``self``.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001753
1754Class attributes:
1755
1756.. attribute:: timezone.utc
1757
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001758 The UTC timezone, ``timezone(timedelta(0))``.
Georg Brandl48310cd2009-01-03 21:18:54 +00001759
Georg Brandl116aa622007-08-15 14:28:22 +00001760
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001761.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00001762
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001763:meth:`strftime` and :meth:`strptime` Behavior
1764----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001765
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001766:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
Georg Brandl116aa622007-08-15 14:28:22 +00001767``strftime(format)`` method, to create a string representing the time under the
1768control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1769acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1770although not all objects support a :meth:`timetuple` method.
1771
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001772Conversely, the :meth:`datetime.strptime` class method creates a
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001773:class:`.datetime` object from a string representing a date and time and a
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001774corresponding format string. ``datetime.strptime(date_string, format)`` is
1775equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1776
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001777For :class:`.time` objects, the format codes for year, month, and day should not
Georg Brandl116aa622007-08-15 14:28:22 +00001778be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001779is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00001780
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001781For :class:`date` objects, the format codes for hours, minutes, seconds, and
1782microseconds should not be used, as :class:`date` objects have no such
1783values. If they're used anyway, ``0`` is substituted for them.
1784
Georg Brandl116aa622007-08-15 14:28:22 +00001785The full set of format codes supported varies across platforms, because Python
1786calls the platform C library's :func:`strftime` function, and platform
Georg Brandlb7117af2013-10-13 18:28:25 +02001787variations are common. To see the full set of format codes supported on your
1788platform, consult the :manpage:`strftime(3)` documentation.
Christian Heimes895627f2007-12-08 17:28:33 +00001789
1790The following is a list of all the format codes that the C standard (1989
1791version) requires, and these work on all platforms with a standard C
1792implementation. Note that the 1999 version of the C standard added additional
1793format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001794
David Wolever569a5fa2013-08-12 16:56:02 -04001795+-----------+--------------------------------+------------------------+-------+
1796| Directive | Meaning | Example | Notes |
1797+===========+================================+========================+=======+
1798| ``%a`` | Weekday as locale's || Sun, Mon, ..., Sat | \(1) |
1799| | abbreviated name. | (en_US); | |
1800| | || So, Mo, ..., Sa | |
1801| | | (de_DE) | |
1802+-----------+--------------------------------+------------------------+-------+
1803| ``%A`` | Weekday as locale's full name. || Sunday, Monday, ..., | \(1) |
1804| | | Saturday (en_US); | |
1805| | || Sonntag, Montag, ..., | |
1806| | | Samstag (de_DE) | |
1807+-----------+--------------------------------+------------------------+-------+
1808| ``%w`` | Weekday as a decimal number, | 0, 1, ..., 6 | |
1809| | where 0 is Sunday and 6 is | | |
1810| | Saturday. | | |
1811+-----------+--------------------------------+------------------------+-------+
1812| ``%d`` | Day of the month as a | 01, 02, ..., 31 | |
1813| | zero-padded decimal number. | | |
1814+-----------+--------------------------------+------------------------+-------+
1815| ``%b`` | Month as locale's abbreviated || Jan, Feb, ..., Dec | \(1) |
1816| | name. | (en_US); | |
1817| | || Jan, Feb, ..., Dez | |
1818| | | (de_DE) | |
1819+-----------+--------------------------------+------------------------+-------+
1820| ``%B`` | Month as locale's full name. || January, February, | \(1) |
1821| | | ..., December (en_US);| |
1822| | || Januar, Februar, ..., | |
1823| | | Dezember (de_DE) | |
1824+-----------+--------------------------------+------------------------+-------+
1825| ``%m`` | Month as a zero-padded | 01, 02, ..., 12 | |
1826| | decimal number. | | |
1827+-----------+--------------------------------+------------------------+-------+
1828| ``%y`` | Year without century as a | 00, 01, ..., 99 | |
1829| | zero-padded decimal number. | | |
1830+-----------+--------------------------------+------------------------+-------+
1831| ``%Y`` | Year with century as a decimal | 0001, 0002, ..., 2013, | \(2) |
David Wolever5d07e702013-08-14 14:41:48 -04001832| | number. | 2014, ..., 9998, 9999 | |
David Wolever569a5fa2013-08-12 16:56:02 -04001833+-----------+--------------------------------+------------------------+-------+
1834| ``%H`` | Hour (24-hour clock) as a | 00, 01, ..., 23 | |
1835| | zero-padded decimal number. | | |
1836+-----------+--------------------------------+------------------------+-------+
1837| ``%I`` | Hour (12-hour clock) as a | 01, 02, ..., 12 | |
1838| | zero-padded decimal number. | | |
1839+-----------+--------------------------------+------------------------+-------+
1840| ``%p`` | Locale's equivalent of either || AM, PM (en_US); | \(1), |
1841| | AM or PM. || am, pm (de_DE) | \(3) |
1842+-----------+--------------------------------+------------------------+-------+
1843| ``%M`` | Minute as a zero-padded | 00, 01, ..., 59 | |
1844| | decimal number. | | |
1845+-----------+--------------------------------+------------------------+-------+
1846| ``%S`` | Second as a zero-padded | 00, 01, ..., 59 | \(4) |
1847| | decimal number. | | |
1848+-----------+--------------------------------+------------------------+-------+
1849| ``%f`` | Microsecond as a decimal | 000000, 000001, ..., | \(5) |
1850| | number, zero-padded on the | 999999 | |
1851| | left. | | |
1852+-----------+--------------------------------+------------------------+-------+
1853| ``%z`` | UTC offset in the form +HHMM | (empty), +0000, -0400, | \(6) |
1854| | or -HHMM (empty string if the | +1030 | |
1855| | the object is naive). | | |
1856+-----------+--------------------------------+------------------------+-------+
1857| ``%Z`` | Time zone name (empty string | (empty), UTC, EST, CST | |
1858| | if the object is naive). | | |
1859+-----------+--------------------------------+------------------------+-------+
1860| ``%j`` | Day of the year as a | 001, 002, ..., 366 | |
1861| | zero-padded decimal number. | | |
1862+-----------+--------------------------------+------------------------+-------+
1863| ``%U`` | Week number of the year | 00, 01, ..., 53 | \(7) |
1864| | (Sunday as the first day of | | |
1865| | the week) as a zero padded | | |
1866| | decimal number. All days in a | | |
1867| | new year preceding the first | | |
1868| | Sunday are considered to be in | | |
1869| | week 0. | | |
1870+-----------+--------------------------------+------------------------+-------+
1871| ``%W`` | Week number of the year | 00, 01, ..., 53 | \(7) |
1872| | (Monday as the first day of | | |
1873| | the week) as a decimal number. | | |
1874| | All days in a new year | | |
1875| | preceding the first Monday | | |
1876| | are considered to be in | | |
1877| | week 0. | | |
1878+-----------+--------------------------------+------------------------+-------+
1879| ``%c`` | Locale's appropriate date and || Tue Aug 16 21:30:00 | \(1) |
1880| | time representation. | 1988 (en_US); | |
1881| | || Di 16 Aug 21:30:00 | |
1882| | | 1988 (de_DE) | |
1883+-----------+--------------------------------+------------------------+-------+
1884| ``%x`` | Locale's appropriate date || 08/16/88 (None); | \(1) |
1885| | representation. || 08/16/1988 (en_US); | |
1886| | || 16.08.1988 (de_DE) | |
1887+-----------+--------------------------------+------------------------+-------+
1888| ``%X`` | Locale's appropriate time || 21:30:00 (en_US); | \(1) |
1889| | representation. || 21:30:00 (de_DE) | |
1890+-----------+--------------------------------+------------------------+-------+
1891| ``%%`` | A literal ``'%'`` character. | % | |
1892+-----------+--------------------------------+------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001893
Christian Heimes895627f2007-12-08 17:28:33 +00001894Notes:
1895
1896(1)
David Wolever569a5fa2013-08-12 16:56:02 -04001897 Because the format depends on the current locale, care should be taken when
1898 making assumptions about the output value. Field orderings will vary (for
1899 example, "month/day/year" versus "day/month/year"), and the output may
1900 contain Unicode characters encoded using the locale's default encoding (for
Georg Brandlad321532013-10-29 08:05:10 +01001901 example, if the current locale is ``ja_JP``, the default encoding could be
David Wolever569a5fa2013-08-12 16:56:02 -04001902 any one of ``eucJP``, ``SJIS``, or ``utf-8``; use :meth:`locale.getlocale`
1903 to determine the current locale's encoding).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001904
1905(2)
David Wolever569a5fa2013-08-12 16:56:02 -04001906 The :meth:`strptime` method can parse years in the full [1, 9999] range, but
1907 years < 1000 must be zero-filled to 4-digit width.
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001908
1909 .. versionchanged:: 3.2
1910 In previous versions, :meth:`strftime` method was restricted to
1911 years >= 1900.
1912
Alexander Belopolsky5611a1c2011-05-02 14:14:48 -04001913 .. versionchanged:: 3.3
1914 In version 3.2, :meth:`strftime` method was restricted to
1915 years >= 1000.
1916
David Wolever569a5fa2013-08-12 16:56:02 -04001917(3)
1918 When used with the :meth:`strptime` method, the ``%p`` directive only affects
1919 the output hour field if the ``%I`` directive is used to parse the hour.
Alexander Belopolskyca94f552010-06-17 18:30:34 +00001920
David Wolever569a5fa2013-08-12 16:56:02 -04001921(4)
1922 Unlike the :mod:`time` module, the :mod:`datetime` module does not support
1923 leap seconds.
1924
1925(5)
1926 When used with the :meth:`strptime` method, the ``%f`` directive
1927 accepts from one to six digits and zero pads on the right. ``%f`` is
1928 an extension to the set of format characters in the C standard (but
1929 implemented separately in datetime objects, and therefore always
1930 available).
1931
1932(6)
1933 For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1934 strings.
1935
1936 For an aware object:
1937
1938 ``%z``
1939 :meth:`utcoffset` is transformed into a 5-character string of the form
1940 +HHMM or -HHMM, where HH is a 2-digit string giving the number of UTC
1941 offset hours, and MM is a 2-digit string giving the number of UTC offset
1942 minutes. For example, if :meth:`utcoffset` returns
1943 ``timedelta(hours=-3, minutes=-30)``, ``%z`` is replaced with the string
1944 ``'-0330'``.
1945
1946 ``%Z``
1947 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty
1948 string. Otherwise ``%Z`` is replaced by the returned value, which must
1949 be a string.
1950
1951 .. versionchanged:: 3.2
1952 When the ``%z`` directive is provided to the :meth:`strptime` method, an
1953 aware :class:`.datetime` object will be produced. The ``tzinfo`` of the
1954 result will be set to a :class:`timezone` instance.
1955
1956(7)
1957 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used
1958 in calculations when the day of the week and the year are specified.
R David Murray9075d8b2012-05-14 22:14:46 -04001959
1960.. rubric:: Footnotes
1961
1962.. [#] If, that is, we ignore the effects of Relativity