blob: 669236aaed103b40e33d41735f23753e1c7d5b4b [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
173 If any argument is a float and there are fractional microseconds, the fractional
174 microseconds left over from all arguments are combined and their sum is rounded
175 to the nearest microsecond. If no argument is a float, the conversion and
176 normalization processes are exact (no information is lost).
177
178 If the normalized value of days lies outside the indicated range,
179 :exc:`OverflowError` is raised.
180
181 Note that normalization of negative values may be surprising at first. For
Christian Heimesfe337bf2008-03-23 21:54:12 +0000182 example,
Georg Brandl116aa622007-08-15 14:28:22 +0000183
Christian Heimes895627f2007-12-08 17:28:33 +0000184 >>> from datetime import timedelta
Georg Brandl116aa622007-08-15 14:28:22 +0000185 >>> d = timedelta(microseconds=-1)
186 >>> (d.days, d.seconds, d.microseconds)
187 (-1, 86399, 999999)
188
Georg Brandl116aa622007-08-15 14:28:22 +0000189
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000190Class attributes are:
Georg Brandl116aa622007-08-15 14:28:22 +0000191
192.. attribute:: timedelta.min
193
194 The most negative :class:`timedelta` object, ``timedelta(-999999999)``.
195
196
197.. attribute:: timedelta.max
198
199 The most positive :class:`timedelta` object, ``timedelta(days=999999999,
200 hours=23, minutes=59, seconds=59, microseconds=999999)``.
201
202
203.. attribute:: timedelta.resolution
204
205 The smallest possible difference between non-equal :class:`timedelta` objects,
206 ``timedelta(microseconds=1)``.
207
208Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``.
209``-timedelta.max`` is not representable as a :class:`timedelta` object.
210
211Instance attributes (read-only):
212
213+------------------+--------------------------------------------+
214| Attribute | Value |
215+==================+============================================+
216| ``days`` | Between -999999999 and 999999999 inclusive |
217+------------------+--------------------------------------------+
218| ``seconds`` | Between 0 and 86399 inclusive |
219+------------------+--------------------------------------------+
220| ``microseconds`` | Between 0 and 999999 inclusive |
221+------------------+--------------------------------------------+
222
223Supported operations:
224
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000225.. XXX this table is too wide!
Georg Brandl116aa622007-08-15 14:28:22 +0000226
227+--------------------------------+-----------------------------------------------+
228| Operation | Result |
229+================================+===============================================+
230| ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == |
231| | *t3* and *t1*-*t3* == *t2* are true. (1) |
232+--------------------------------+-----------------------------------------------+
233| ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* |
234| | == *t2* - *t3* and *t2* == *t1* + *t3* are |
235| | true. (1) |
236+--------------------------------+-----------------------------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000237| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer. |
Georg Brandl116aa622007-08-15 14:28:22 +0000238| | Afterwards *t1* // i == *t2* is true, |
239| | provided ``i != 0``. |
240+--------------------------------+-----------------------------------------------+
241| | In general, *t1* \* i == *t1* \* (i-1) + *t1* |
242| | is true. (1) |
243+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000244| ``t1 = t2 * f or t1 = f * t2`` | Delta multiplied by a float. The result is |
245| | rounded to the nearest multiple of |
246| | timedelta.resolution using round-half-to-even.|
247+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000248| ``f = t2 / t3`` | Division (3) of *t2* by *t3*. Returns a |
249| | :class:`float` object. |
250+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000251| ``t1 = t2 / f or t1 = t2 / i`` | Delta divided by a float or an int. The result|
252| | is rounded to the nearest multiple of |
253| | timedelta.resolution using round-half-to-even.|
254+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000255| ``t1 = t2 // i`` or | The floor is computed and the remainder (if |
256| ``t1 = t2 // t3`` | any) is thrown away. In the second case, an |
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000257| | integer is returned. (3) |
Mark Dickinson7c186e22010-04-20 22:32:49 +0000258+--------------------------------+-----------------------------------------------+
259| ``t1 = t2 % t3`` | The remainder is computed as a |
260| | :class:`timedelta` object. (3) |
261+--------------------------------+-----------------------------------------------+
262| ``q, r = divmod(t1, t2)`` | Computes the quotient and the remainder: |
263| | ``q = t1 // t2`` (3) and ``r = t1 % t2``. |
264| | q is an integer and r is a :class:`timedelta` |
265| | object. |
Georg Brandl116aa622007-08-15 14:28:22 +0000266+--------------------------------+-----------------------------------------------+
267| ``+t1`` | Returns a :class:`timedelta` object with the |
268| | same value. (2) |
269+--------------------------------+-----------------------------------------------+
270| ``-t1`` | equivalent to :class:`timedelta`\ |
271| | (-*t1.days*, -*t1.seconds*, |
272| | -*t1.microseconds*), and to *t1*\* -1. (1)(4) |
273+--------------------------------+-----------------------------------------------+
Georg Brandl495f7b52009-10-27 15:28:25 +0000274| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, and|
Georg Brandl116aa622007-08-15 14:28:22 +0000275| | to -*t* when ``t.days < 0``. (2) |
276+--------------------------------+-----------------------------------------------+
Georg Brandlf55c3152010-07-31 11:40:07 +0000277| ``str(t)`` | Returns a string in the form |
278| | ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D |
279| | is negative for negative ``t``. (5) |
280+--------------------------------+-----------------------------------------------+
281| ``repr(t)`` | Returns a string in the form |
282| | ``datetime.timedelta(D[, S[, U]])``, where D |
283| | is negative for negative ``t``. (5) |
284+--------------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000285
286Notes:
287
288(1)
289 This is exact, but may overflow.
290
291(2)
292 This is exact, and cannot overflow.
293
294(3)
295 Division by 0 raises :exc:`ZeroDivisionError`.
296
297(4)
298 -*timedelta.max* is not representable as a :class:`timedelta` object.
299
Georg Brandlf55c3152010-07-31 11:40:07 +0000300(5)
301 String representations of :class:`timedelta` objects are normalized
302 similarly to their internal representation. This leads to somewhat
303 unusual results for negative timedeltas. For example:
304
305 >>> timedelta(hours=-5)
306 datetime.timedelta(-1, 68400)
307 >>> print(_)
308 -1 day, 19:00:00
309
Georg Brandl116aa622007-08-15 14:28:22 +0000310In addition to the operations listed above :class:`timedelta` objects support
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300311certain additions and subtractions with :class:`date` and :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +0000312objects (see below).
313
Georg Brandl67b21b72010-08-17 15:07:14 +0000314.. versionchanged:: 3.2
315 Floor division and true division of a :class:`timedelta` object by another
316 :class:`timedelta` object are now supported, as are remainder operations and
317 the :func:`divmod` function. True division and multiplication of a
318 :class:`timedelta` object by a :class:`float` object are now supported.
Mark Dickinson7c186e22010-04-20 22:32:49 +0000319
320
Georg Brandl116aa622007-08-15 14:28:22 +0000321Comparisons of :class:`timedelta` objects are supported with the
322:class:`timedelta` object representing the smaller duration considered to be the
323smaller timedelta. In order to stop mixed-type comparisons from falling back to
324the default comparison by object address, when a :class:`timedelta` object is
325compared to an object of a different type, :exc:`TypeError` is raised unless the
326comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
327:const:`True`, respectively.
328
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000329:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl116aa622007-08-15 14:28:22 +0000330efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
331considered to be true if and only if it isn't equal to ``timedelta(0)``.
332
Antoine Pitroube6859d2009-11-25 23:02:32 +0000333Instance methods:
334
335.. method:: timedelta.total_seconds()
336
337 Return the total number of seconds contained in the duration. Equivalent to
Mark Dickinson0381e3f2010-05-08 14:35:02 +0000338 ``td / timedelta(seconds=1)``.
339
340 Note that for very large time intervals (greater than 270 years on
341 most platforms) this method will lose microsecond accuracy.
Antoine Pitroube6859d2009-11-25 23:02:32 +0000342
343 .. versionadded:: 3.2
344
345
Christian Heimesfe337bf2008-03-23 21:54:12 +0000346Example usage:
Georg Brandl48310cd2009-01-03 21:18:54 +0000347
Christian Heimes895627f2007-12-08 17:28:33 +0000348 >>> from datetime import timedelta
349 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000350 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Christian Heimes895627f2007-12-08 17:28:33 +0000351 ... minutes=50, seconds=600) # adds up to 365 days
Antoine Pitroube6859d2009-11-25 23:02:32 +0000352 >>> year.total_seconds()
353 31536000.0
Christian Heimes895627f2007-12-08 17:28:33 +0000354 >>> year == another_year
355 True
356 >>> ten_years = 10 * year
357 >>> ten_years, ten_years.days // 365
358 (datetime.timedelta(3650), 10)
359 >>> nine_years = ten_years - year
360 >>> nine_years, nine_years.days // 365
361 (datetime.timedelta(3285), 9)
362 >>> three_years = nine_years // 3;
363 >>> three_years, three_years.days // 365
364 (datetime.timedelta(1095), 3)
365 >>> abs(three_years - ten_years) == 2 * three_years + year
366 True
367
Georg Brandl116aa622007-08-15 14:28:22 +0000368
369.. _datetime-date:
370
371:class:`date` Objects
372---------------------
373
374A :class:`date` object represents a date (year, month and day) in an idealized
375calendar, the current Gregorian calendar indefinitely extended in both
376directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
377called day number 2, and so on. This matches the definition of the "proleptic
378Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
379where it's the base calendar for all computations. See the book for algorithms
380for converting between proleptic Gregorian ordinals and many other calendar
381systems.
382
383
384.. class:: date(year, month, day)
385
Georg Brandl5c106642007-11-29 17:41:05 +0000386 All arguments are required. Arguments may be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000387 ranges:
388
389 * ``MINYEAR <= year <= MAXYEAR``
390 * ``1 <= month <= 12``
391 * ``1 <= day <= number of days in the given month and year``
392
393 If an argument outside those ranges is given, :exc:`ValueError` is raised.
394
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000395
Georg Brandl116aa622007-08-15 14:28:22 +0000396Other constructors, all class methods:
397
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000398.. classmethod:: date.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000399
400 Return the current local date. This is equivalent to
401 ``date.fromtimestamp(time.time())``.
402
403
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000404.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000405
406 Return the local date corresponding to the POSIX timestamp, such as is returned
Victor Stinner5d272cc2012-03-13 13:35:55 +0100407 by :func:`time.time`. This may raise :exc:`OverflowError`, if the timestamp is out
Victor Stinnerecc6e662012-03-14 00:39:29 +0100408 of the range of values supported by the platform C :c:func:`localtime` function,
409 and :exc:`OSError` on :c:func:`localtime` failure.
Georg Brandl116aa622007-08-15 14:28:22 +0000410 It's common for this to be restricted to years from 1970 through 2038. Note
411 that on non-POSIX systems that include leap seconds in their notion of a
412 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
413
Victor Stinner5d272cc2012-03-13 13:35:55 +0100414 .. versionchanged:: 3.3
415 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
416 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100417 :c:func:`localtime` function. Raise :exc:`OSError` instead of
418 :exc:`ValueError` on :c:func:`localtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100419
Georg Brandl116aa622007-08-15 14:28:22 +0000420
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000421.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000422
423 Return the date corresponding to the proleptic Gregorian ordinal, where January
424 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
425 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
426 d``.
427
Georg Brandl116aa622007-08-15 14:28:22 +0000428
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000429Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000430
431.. attribute:: date.min
432
433 The earliest representable date, ``date(MINYEAR, 1, 1)``.
434
435
436.. attribute:: date.max
437
438 The latest representable date, ``date(MAXYEAR, 12, 31)``.
439
440
441.. attribute:: date.resolution
442
443 The smallest possible difference between non-equal date objects,
444 ``timedelta(days=1)``.
445
Georg Brandl116aa622007-08-15 14:28:22 +0000446
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000447Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000448
449.. attribute:: date.year
450
451 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
452
453
454.. attribute:: date.month
455
456 Between 1 and 12 inclusive.
457
458
459.. attribute:: date.day
460
461 Between 1 and the number of days in the given month of the given year.
462
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000463
Georg Brandl116aa622007-08-15 14:28:22 +0000464Supported operations:
465
466+-------------------------------+----------------------------------------------+
467| Operation | Result |
468+===============================+==============================================+
469| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
470| | from *date1*. (1) |
471+-------------------------------+----------------------------------------------+
472| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
473| | timedelta == date1``. (2) |
474+-------------------------------+----------------------------------------------+
475| ``timedelta = date1 - date2`` | \(3) |
476+-------------------------------+----------------------------------------------+
477| ``date1 < date2`` | *date1* is considered less than *date2* when |
478| | *date1* precedes *date2* in time. (4) |
479+-------------------------------+----------------------------------------------+
480
481Notes:
482
483(1)
484 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
485 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
486 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
487 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
488 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
489
490(2)
491 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
492 isolation can overflow in cases where date1 - timedelta does not.
493 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
494
495(3)
496 This is exact, and cannot overflow. timedelta.seconds and
497 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
498
499(4)
500 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
501 date2.toordinal()``. In order to stop comparison from falling back to the
502 default scheme of comparing object addresses, date comparison normally raises
503 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
504 However, ``NotImplemented`` is returned instead if the other comparand has a
505 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
506 chance at implementing mixed-type comparison. If not, when a :class:`date`
507 object is compared to an object of a different type, :exc:`TypeError` is raised
508 unless the comparison is ``==`` or ``!=``. The latter cases return
509 :const:`False` or :const:`True`, respectively.
510
511Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
512objects are considered to be true.
513
514Instance methods:
515
Georg Brandl116aa622007-08-15 14:28:22 +0000516.. method:: date.replace(year, month, day)
517
Senthil Kumarana6bac952011-07-04 11:28:30 -0700518 Return a date with the same value, except for those parameters given new
519 values by whichever keyword arguments are specified. For example, if ``d ==
520 date(2002, 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000521
522
523.. method:: date.timetuple()
524
525 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
526 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
527 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000528 d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1,
529 1).toordinal() + 1`` is the day number within the current year starting with
530 ``1`` for January 1st.
Georg Brandl116aa622007-08-15 14:28:22 +0000531
532
533.. method:: date.toordinal()
534
535 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
536 has ordinal 1. For any :class:`date` object *d*,
537 ``date.fromordinal(d.toordinal()) == d``.
538
539
540.. method:: date.weekday()
541
542 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
543 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
544 :meth:`isoweekday`.
545
546
547.. method:: date.isoweekday()
548
549 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
550 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
551 :meth:`weekday`, :meth:`isocalendar`.
552
553
554.. method:: date.isocalendar()
555
556 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
557
558 The ISO calendar is a widely used variant of the Gregorian calendar. See
Mark Dickinsonf964ac22009-11-03 16:29:10 +0000559 http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
560 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000561
562 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
563 Monday and ends on a Sunday. The first week of an ISO year is the first
564 (Gregorian) calendar week of a year containing a Thursday. This is called week
565 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
566
567 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
568 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
569 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
570 4).isocalendar() == (2004, 1, 7)``.
571
572
573.. method:: date.isoformat()
574
575 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
576 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
577
578
579.. method:: date.__str__()
580
581 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
582
583
584.. method:: date.ctime()
585
586 Return a string representing the date, for example ``date(2002, 12,
587 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
588 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
Georg Brandl60203b42010-10-06 10:11:56 +0000589 :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +0000590 :meth:`date.ctime` does not invoke) conforms to the C standard.
591
592
593.. method:: date.strftime(format)
594
595 Return a string representing the date, controlled by an explicit format string.
596 Format codes referring to hours, minutes or seconds will see 0 values. See
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000597 section :ref:`strftime-strptime-behavior`.
598
Georg Brandl116aa622007-08-15 14:28:22 +0000599
Christian Heimes895627f2007-12-08 17:28:33 +0000600Example of counting days to an event::
601
602 >>> import time
603 >>> from datetime import date
604 >>> today = date.today()
605 >>> today
606 datetime.date(2007, 12, 5)
607 >>> today == date.fromtimestamp(time.time())
608 True
609 >>> my_birthday = date(today.year, 6, 24)
610 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000611 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000612 >>> my_birthday
613 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000614 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000615 >>> time_to_birthday.days
616 202
617
Christian Heimesfe337bf2008-03-23 21:54:12 +0000618Example of working with :class:`date`:
619
620.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000621
622 >>> from datetime import date
623 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
624 >>> d
625 datetime.date(2002, 3, 11)
626 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000627 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000628 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000629 2002 # year
630 3 # month
631 11 # day
632 0
633 0
634 0
635 0 # weekday (0 = Monday)
636 70 # 70th day in the year
637 -1
638 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000639 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000640 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000641 2002 # ISO year
642 11 # ISO week number
643 1 # ISO day number ( 1 = Monday )
644 >>> d.isoformat()
645 '2002-03-11'
646 >>> d.strftime("%d/%m/%y")
647 '11/03/02'
648 >>> d.strftime("%A %d. %B %Y")
649 'Monday 11. March 2002'
650
Georg Brandl116aa622007-08-15 14:28:22 +0000651
652.. _datetime-datetime:
653
654:class:`datetime` Objects
655-------------------------
656
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300657A :class:`.datetime` object is a single object containing all the information
658from a :class:`date` object and a :class:`.time` object. Like a :class:`date`
659object, :class:`.datetime` assumes the current Gregorian calendar extended in
660both directions; like a time object, :class:`.datetime` assumes there are exactly
Georg Brandl116aa622007-08-15 14:28:22 +00006613600\*24 seconds in every day.
662
663Constructor:
664
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000665.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000666
667 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000668 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
669 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000670
671 * ``MINYEAR <= year <= MAXYEAR``
672 * ``1 <= month <= 12``
673 * ``1 <= day <= number of days in the given month and year``
674 * ``0 <= hour < 24``
675 * ``0 <= minute < 60``
676 * ``0 <= second < 60``
677 * ``0 <= microsecond < 1000000``
678
679 If an argument outside those ranges is given, :exc:`ValueError` is raised.
680
681Other constructors, all class methods:
682
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000683.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000684
685 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
686 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
687 :meth:`fromtimestamp`.
688
689
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000690.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000691
692 Return the current local date and time. If optional argument *tz* is ``None``
693 or not specified, this is like :meth:`today`, but, if possible, supplies more
694 precision than can be gotten from going through a :func:`time.time` timestamp
695 (for example, this may be possible on platforms supplying the C
Georg Brandl60203b42010-10-06 10:11:56 +0000696 :c:func:`gettimeofday` function).
Georg Brandl116aa622007-08-15 14:28:22 +0000697
698 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
699 current date and time are converted to *tz*'s time zone. In this case the
700 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
701 See also :meth:`today`, :meth:`utcnow`.
702
703
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000704.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000705
706 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
707 :meth:`now`, but returns the current UTC date and time, as a naive
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300708 :class:`.datetime` object. An aware current UTC datetime can be obtained by
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000709 calling ``datetime.now(timezone.utc)``. See also :meth:`now`.
Georg Brandl116aa622007-08-15 14:28:22 +0000710
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000711.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000712
713 Return the local date and time corresponding to the POSIX timestamp, such as is
714 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
715 specified, the timestamp is converted to the platform's local date and time, and
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300716 the returned :class:`.datetime` object is naive.
Georg Brandl116aa622007-08-15 14:28:22 +0000717
718 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
719 timestamp is converted to *tz*'s time zone. In this case the result is
720 equivalent to
721 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
722
Victor Stinnerecc6e662012-03-14 00:39:29 +0100723 :meth:`fromtimestamp` may raise :exc:`OverflowError`, if the timestamp is out of
Georg Brandl60203b42010-10-06 10:11:56 +0000724 the range of values supported by the platform C :c:func:`localtime` or
Victor Stinnerecc6e662012-03-14 00:39:29 +0100725 :c:func:`gmtime` functions, and :exc:`OSError` on :c:func:`localtime` or
726 :c:func:`gmtime` failure.
727 It's common for this to be restricted to years in
Georg Brandl116aa622007-08-15 14:28:22 +0000728 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
729 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
730 and then it's possible to have two timestamps differing by a second that yield
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300731 identical :class:`.datetime` objects. See also :meth:`utcfromtimestamp`.
Georg Brandl116aa622007-08-15 14:28:22 +0000732
Victor Stinner5d272cc2012-03-13 13:35:55 +0100733 .. versionchanged:: 3.3
734 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
735 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100736 :c:func:`localtime` or :c:func:`gmtime` functions. Raise :exc:`OSError`
737 instead of :exc:`ValueError` on :c:func:`localtime` or :c:func:`gmtime`
738 failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100739
Georg Brandl116aa622007-08-15 14:28:22 +0000740
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000741.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000742
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300743 Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with
Victor Stinnerecc6e662012-03-14 00:39:29 +0100744 :attr:`tzinfo` ``None``. This may raise :exc:`OverflowError`, if the timestamp is
745 out of the range of values supported by the platform C :c:func:`gmtime` function,
746 and :exc:`OSError` on :c:func:`gmtime` failure.
Georg Brandl116aa622007-08-15 14:28:22 +0000747 It's common for this to be restricted to years in 1970 through 2038. See also
748 :meth:`fromtimestamp`.
749
Alexander Belopolsky54afa552011-04-25 13:00:40 -0400750 On the POSIX compliant platforms, ``utcfromtimestamp(timestamp)``
751 is equivalent to the following expression::
752
753 datetime(1970, 1, 1) + timedelta(seconds=timestamp)
754
755 There is no method to obtain the timestamp from a :class:`datetime`
756 instance, but POSIX timestamp corresponding to a :class:`datetime`
757 instance ``dt`` can be easily calculated as follows. For a naive
758 ``dt``::
759
760 timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
761
762 And for an aware ``dt``::
763
764 timestamp = (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)) / timedelta(seconds=1)
765
Victor Stinner5d272cc2012-03-13 13:35:55 +0100766 .. versionchanged:: 3.3
767 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
768 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100769 :c:func:`gmtime` function. Raise :exc:`OSError` instead of
770 :exc:`ValueError` on :c:func:`gmtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100771
Georg Brandl116aa622007-08-15 14:28:22 +0000772
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000773.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000774
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300775 Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal,
Georg Brandl116aa622007-08-15 14:28:22 +0000776 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
777 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
778 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
779
780
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000781.. classmethod:: datetime.combine(date, time)
Georg Brandl116aa622007-08-15 14:28:22 +0000782
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300783 Return a new :class:`.datetime` object whose date components are equal to the
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800784 given :class:`date` object's, and whose time components and :attr:`tzinfo`
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300785 attributes are equal to the given :class:`.time` object's. For any
786 :class:`.datetime` object *d*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800787 ``d == datetime.combine(d.date(), d.timetz())``. If date is a
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300788 :class:`.datetime` object, its time components and :attr:`tzinfo` attributes
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800789 are ignored.
Georg Brandl116aa622007-08-15 14:28:22 +0000790
791
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000792.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000793
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300794 Return a :class:`.datetime` corresponding to *date_string*, parsed according to
Georg Brandl116aa622007-08-15 14:28:22 +0000795 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
796 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
797 can't be parsed by :func:`time.strptime` or if it returns a value which isn't a
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000798 time tuple. See section :ref:`strftime-strptime-behavior`.
799
Georg Brandl116aa622007-08-15 14:28:22 +0000800
Georg Brandl116aa622007-08-15 14:28:22 +0000801
802Class attributes:
803
Georg Brandl116aa622007-08-15 14:28:22 +0000804.. attribute:: datetime.min
805
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300806 The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1,
Georg Brandl116aa622007-08-15 14:28:22 +0000807 tzinfo=None)``.
808
809
810.. attribute:: datetime.max
811
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300812 The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
Georg Brandl116aa622007-08-15 14:28:22 +0000813 59, 999999, tzinfo=None)``.
814
815
816.. attribute:: datetime.resolution
817
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300818 The smallest possible difference between non-equal :class:`.datetime` objects,
Georg Brandl116aa622007-08-15 14:28:22 +0000819 ``timedelta(microseconds=1)``.
820
Georg Brandl116aa622007-08-15 14:28:22 +0000821
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000822Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000823
824.. attribute:: datetime.year
825
826 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
827
828
829.. attribute:: datetime.month
830
831 Between 1 and 12 inclusive.
832
833
834.. attribute:: datetime.day
835
836 Between 1 and the number of days in the given month of the given year.
837
838
839.. attribute:: datetime.hour
840
841 In ``range(24)``.
842
843
844.. attribute:: datetime.minute
845
846 In ``range(60)``.
847
848
849.. attribute:: datetime.second
850
851 In ``range(60)``.
852
853
854.. attribute:: datetime.microsecond
855
856 In ``range(1000000)``.
857
858
859.. attribute:: datetime.tzinfo
860
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300861 The object passed as the *tzinfo* argument to the :class:`.datetime` constructor,
Georg Brandl116aa622007-08-15 14:28:22 +0000862 or ``None`` if none was passed.
863
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000864
Georg Brandl116aa622007-08-15 14:28:22 +0000865Supported operations:
866
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300867+---------------------------------------+--------------------------------+
868| Operation | Result |
869+=======================================+================================+
870| ``datetime2 = datetime1 + timedelta`` | \(1) |
871+---------------------------------------+--------------------------------+
872| ``datetime2 = datetime1 - timedelta`` | \(2) |
873+---------------------------------------+--------------------------------+
874| ``timedelta = datetime1 - datetime2`` | \(3) |
875+---------------------------------------+--------------------------------+
876| ``datetime1 < datetime2`` | Compares :class:`.datetime` to |
877| | :class:`.datetime`. (4) |
878+---------------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000879
880(1)
881 datetime2 is a duration of timedelta removed from datetime1, moving forward in
882 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
Senthil Kumarana6bac952011-07-04 11:28:30 -0700883 result has the same :attr:`tzinfo` attribute as the input datetime, and
884 datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
885 datetime2.year would be smaller than :const:`MINYEAR` or larger than
886 :const:`MAXYEAR`. Note that no time zone adjustments are done even if the
887 input is an aware object.
Georg Brandl116aa622007-08-15 14:28:22 +0000888
889(2)
890 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
Senthil Kumarana6bac952011-07-04 11:28:30 -0700891 addition, the result has the same :attr:`tzinfo` attribute as the input
892 datetime, and no time zone adjustments are done even if the input is aware.
893 This isn't quite equivalent to datetime1 + (-timedelta), because -timedelta
894 in isolation can overflow in cases where datetime1 - timedelta does not.
Georg Brandl116aa622007-08-15 14:28:22 +0000895
896(3)
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300897 Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if
Georg Brandl116aa622007-08-15 14:28:22 +0000898 both operands are naive, or if both are aware. If one is aware and the other is
899 naive, :exc:`TypeError` is raised.
900
Senthil Kumarana6bac952011-07-04 11:28:30 -0700901 If both are naive, or both are aware and have the same :attr:`tzinfo` attribute,
902 the :attr:`tzinfo` attributes are ignored, and the result is a :class:`timedelta`
Georg Brandl116aa622007-08-15 14:28:22 +0000903 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
904 are done in this case.
905
Senthil Kumarana6bac952011-07-04 11:28:30 -0700906 If both are aware and have different :attr:`tzinfo` attributes, ``a-b`` acts
907 as if *a* and *b* were first converted to naive UTC datetimes first. The
908 result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
909 - b.utcoffset())`` except that the implementation never overflows.
Georg Brandl116aa622007-08-15 14:28:22 +0000910
911(4)
912 *datetime1* is considered less than *datetime2* when *datetime1* precedes
913 *datetime2* in time.
914
915 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
Senthil Kumarana6bac952011-07-04 11:28:30 -0700916 If both comparands are aware, and have the same :attr:`tzinfo` attribute, the
917 common :attr:`tzinfo` attribute is ignored and the base datetimes are
918 compared. If both comparands are aware and have different :attr:`tzinfo`
919 attributes, the comparands are first adjusted by subtracting their UTC
920 offsets (obtained from ``self.utcoffset()``).
Georg Brandl116aa622007-08-15 14:28:22 +0000921
922 .. note::
923
924 In order to stop comparison from falling back to the default scheme of comparing
925 object addresses, datetime comparison normally raises :exc:`TypeError` if the
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300926 other comparand isn't also a :class:`.datetime` object. However,
Georg Brandl116aa622007-08-15 14:28:22 +0000927 ``NotImplemented`` is returned instead if the other comparand has a
928 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300929 chance at implementing mixed-type comparison. If not, when a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +0000930 object is compared to an object of a different type, :exc:`TypeError` is raised
931 unless the comparison is ``==`` or ``!=``. The latter cases return
932 :const:`False` or :const:`True`, respectively.
933
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300934:class:`.datetime` objects can be used as dictionary keys. In Boolean contexts,
935all :class:`.datetime` objects are considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +0000936
937Instance methods:
938
Georg Brandl116aa622007-08-15 14:28:22 +0000939.. method:: datetime.date()
940
941 Return :class:`date` object with same year, month and day.
942
943
944.. method:: datetime.time()
945
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300946 Return :class:`.time` object with same hour, minute, second and microsecond.
Georg Brandl116aa622007-08-15 14:28:22 +0000947 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
948
949
950.. method:: datetime.timetz()
951
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300952 Return :class:`.time` object with same hour, minute, second, microsecond, and
Senthil Kumarana6bac952011-07-04 11:28:30 -0700953 tzinfo attributes. See also method :meth:`time`.
Georg Brandl116aa622007-08-15 14:28:22 +0000954
955
956.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
957
Senthil Kumarana6bac952011-07-04 11:28:30 -0700958 Return a datetime with the same attributes, except for those attributes given
959 new values by whichever keyword arguments are specified. Note that
960 ``tzinfo=None`` can be specified to create a naive datetime from an aware
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800961 datetime with no conversion of date and time data.
Georg Brandl116aa622007-08-15 14:28:22 +0000962
963
964.. method:: datetime.astimezone(tz)
965
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300966 Return a :class:`.datetime` object with new :attr:`tzinfo` attribute *tz*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800967 adjusting the date and time data so the result is the same UTC time as
Senthil Kumarana6bac952011-07-04 11:28:30 -0700968 *self*, but in *tz*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +0000969
970 *tz* must be an instance of a :class:`tzinfo` subclass, and its
971 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
972 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
973 not return ``None``).
974
975 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800976 adjustment of date or time data is performed. Else the result is local
Senthil Kumarana6bac952011-07-04 11:28:30 -0700977 time in time zone *tz*, representing the same UTC time as *self*: after
978 ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800979 the same date and time data as ``dt - dt.utcoffset()``. The discussion
Senthil Kumarana6bac952011-07-04 11:28:30 -0700980 of class :class:`tzinfo` explains the cases at Daylight Saving Time transition
981 boundaries where this cannot be achieved (an issue only if *tz* models both
982 standard and daylight time).
Georg Brandl116aa622007-08-15 14:28:22 +0000983
984 If you merely want to attach a time zone object *tz* to a datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800985 adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you
Georg Brandl116aa622007-08-15 14:28:22 +0000986 merely want to remove the time zone object from an aware datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800987 conversion of date and time data, use ``dt.replace(tzinfo=None)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000988
989 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
990 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
991 Ignoring error cases, :meth:`astimezone` acts like::
992
993 def astimezone(self, tz):
994 if self.tzinfo is tz:
995 return self
996 # Convert self to UTC, and attach the new time zone object.
997 utc = (self - self.utcoffset()).replace(tzinfo=tz)
998 # Convert from UTC to tz's local time.
999 return tz.fromutc(utc)
1000
1001
1002.. method:: datetime.utcoffset()
1003
1004 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1005 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
1006 return ``None``, or a :class:`timedelta` object representing a whole number of
1007 minutes with magnitude less than one day.
1008
1009
1010.. method:: datetime.dst()
1011
1012 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1013 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
1014 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1015 with magnitude less than one day.
1016
1017
1018.. method:: datetime.tzname()
1019
1020 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1021 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
1022 ``None`` or a string object,
1023
1024
1025.. method:: datetime.timetuple()
1026
1027 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
1028 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
Alexander Belopolsky64912482010-06-08 18:59:20 +00001029 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
1030 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
1031 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
1032 of the result is set according to the :meth:`dst` method: :attr:`tzinfo` is
Georg Brandl682d7e02010-10-06 10:26:05 +00001033 ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
Alexander Belopolsky64912482010-06-08 18:59:20 +00001034 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
Alexander Belopolskyda62f2f2010-06-09 17:11:01 +00001035 else :attr:`tm_isdst` is set to ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +00001036
1037
1038.. method:: datetime.utctimetuple()
1039
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001040 If :class:`.datetime` instance *d* is naive, this is the same as
Georg Brandl116aa622007-08-15 14:28:22 +00001041 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
1042 ``d.dst()`` returns. DST is never in effect for a UTC time.
1043
1044 If *d* is aware, *d* is normalized to UTC time, by subtracting
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00001045 ``d.utcoffset()``, and a :class:`time.struct_time` for the
1046 normalized time is returned. :attr:`tm_isdst` is forced to 0. Note
1047 that an :exc:`OverflowError` may be raised if *d*.year was
1048 ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
Georg Brandl116aa622007-08-15 14:28:22 +00001049 boundary.
1050
1051
1052.. method:: datetime.toordinal()
1053
1054 Return the proleptic Gregorian ordinal of the date. The same as
1055 ``self.date().toordinal()``.
1056
1057
1058.. method:: datetime.weekday()
1059
1060 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
1061 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
1062
1063
1064.. method:: datetime.isoweekday()
1065
1066 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
1067 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
1068 :meth:`isocalendar`.
1069
1070
1071.. method:: datetime.isocalendar()
1072
1073 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
1074 ``self.date().isocalendar()``.
1075
1076
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001077.. method:: datetime.isoformat(sep='T')
Georg Brandl116aa622007-08-15 14:28:22 +00001078
1079 Return a string representing the date and time in ISO 8601 format,
1080 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
1081 YYYY-MM-DDTHH:MM:SS
1082
1083 If :meth:`utcoffset` does not return ``None``, a 6-character string is
1084 appended, giving the UTC offset in (signed) hours and minutes:
1085 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
1086 YYYY-MM-DDTHH:MM:SS+HH:MM
1087
1088 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +00001089 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +00001090
1091 >>> from datetime import tzinfo, timedelta, datetime
1092 >>> class TZ(tzinfo):
1093 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1094 ...
1095 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1096 '2002-12-25 00:00:00-06:39'
1097
1098
1099.. method:: datetime.__str__()
1100
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001101 For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to
Georg Brandl116aa622007-08-15 14:28:22 +00001102 ``d.isoformat(' ')``.
1103
1104
1105.. method:: datetime.ctime()
1106
1107 Return a string representing the date and time, for example ``datetime(2002, 12,
1108 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1109 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
Georg Brandl60203b42010-10-06 10:11:56 +00001110 native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +00001111 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1112
1113
1114.. method:: datetime.strftime(format)
1115
1116 Return a string representing the date and time, controlled by an explicit format
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001117 string. See section :ref:`strftime-strptime-behavior`.
1118
Georg Brandl116aa622007-08-15 14:28:22 +00001119
Christian Heimesfe337bf2008-03-23 21:54:12 +00001120Examples of working with datetime objects:
1121
1122.. doctest::
1123
Christian Heimes895627f2007-12-08 17:28:33 +00001124 >>> from datetime import datetime, date, time
1125 >>> # Using datetime.combine()
1126 >>> d = date(2005, 7, 14)
1127 >>> t = time(12, 30)
1128 >>> datetime.combine(d, t)
1129 datetime.datetime(2005, 7, 14, 12, 30)
1130 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001131 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001132 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001133 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001134 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1135 >>> # Using datetime.strptime()
1136 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1137 >>> dt
1138 datetime.datetime(2006, 11, 21, 16, 30)
1139 >>> # Using datetime.timetuple() to get tuple of all attributes
1140 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001141 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001142 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001143 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001144 2006 # year
1145 11 # month
1146 21 # day
1147 16 # hour
1148 30 # minute
1149 0 # second
1150 1 # weekday (0 = Monday)
1151 325 # number of days since 1st January
1152 -1 # dst - method tzinfo.dst() returned None
1153 >>> # Date in ISO format
1154 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001155 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001156 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001157 ...
1158 2006 # ISO year
1159 47 # ISO week
1160 2 # ISO weekday
1161 >>> # Formatting datetime
1162 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1163 'Tuesday, 21. November 2006 04:30PM'
1164
Christian Heimesfe337bf2008-03-23 21:54:12 +00001165Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001166
1167 >>> from datetime import timedelta, datetime, tzinfo
1168 >>> class GMT1(tzinfo):
1169 ... def __init__(self): # DST starts last Sunday in March
1170 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1171 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001172 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001173 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1174 ... def utcoffset(self, dt):
1175 ... return timedelta(hours=1) + self.dst(dt)
Georg Brandl48310cd2009-01-03 21:18:54 +00001176 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001177 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1178 ... return timedelta(hours=1)
1179 ... else:
1180 ... return timedelta(0)
1181 ... def tzname(self,dt):
1182 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001183 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001184 >>> class GMT2(tzinfo):
1185 ... def __init__(self):
Georg Brandl48310cd2009-01-03 21:18:54 +00001186 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001187 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001188 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001189 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1190 ... def utcoffset(self, dt):
1191 ... return timedelta(hours=1) + self.dst(dt)
1192 ... def dst(self, dt):
1193 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1194 ... return timedelta(hours=2)
1195 ... else:
1196 ... return timedelta(0)
1197 ... def tzname(self,dt):
1198 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001199 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001200 >>> gmt1 = GMT1()
1201 >>> # Daylight Saving Time
1202 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1203 >>> dt1.dst()
1204 datetime.timedelta(0)
1205 >>> dt1.utcoffset()
1206 datetime.timedelta(0, 3600)
1207 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1208 >>> dt2.dst()
1209 datetime.timedelta(0, 3600)
1210 >>> dt2.utcoffset()
1211 datetime.timedelta(0, 7200)
1212 >>> # Convert datetime to another time zone
1213 >>> dt3 = dt2.astimezone(GMT2())
1214 >>> dt3 # doctest: +ELLIPSIS
1215 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1216 >>> dt2 # doctest: +ELLIPSIS
1217 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1218 >>> dt2.utctimetuple() == dt3.utctimetuple()
1219 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001220
Christian Heimes895627f2007-12-08 17:28:33 +00001221
Georg Brandl116aa622007-08-15 14:28:22 +00001222
1223.. _datetime-time:
1224
1225:class:`time` Objects
1226---------------------
1227
1228A time object represents a (local) time of day, independent of any particular
1229day, and subject to adjustment via a :class:`tzinfo` object.
1230
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001231.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001232
1233 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001234 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001235 following ranges:
1236
1237 * ``0 <= hour < 24``
1238 * ``0 <= minute < 60``
1239 * ``0 <= second < 60``
1240 * ``0 <= microsecond < 1000000``.
1241
1242 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1243 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1244
1245Class attributes:
1246
1247
1248.. attribute:: time.min
1249
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001250 The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001251
1252
1253.. attribute:: time.max
1254
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001255 The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001256
1257
1258.. attribute:: time.resolution
1259
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001260 The smallest possible difference between non-equal :class:`.time` objects,
1261 ``timedelta(microseconds=1)``, although note that arithmetic on
1262 :class:`.time` objects is not supported.
Georg Brandl116aa622007-08-15 14:28:22 +00001263
Georg Brandl116aa622007-08-15 14:28:22 +00001264
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001265Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001266
1267.. attribute:: time.hour
1268
1269 In ``range(24)``.
1270
1271
1272.. attribute:: time.minute
1273
1274 In ``range(60)``.
1275
1276
1277.. attribute:: time.second
1278
1279 In ``range(60)``.
1280
1281
1282.. attribute:: time.microsecond
1283
1284 In ``range(1000000)``.
1285
1286
1287.. attribute:: time.tzinfo
1288
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001289 The object passed as the tzinfo argument to the :class:`.time` constructor, or
Georg Brandl116aa622007-08-15 14:28:22 +00001290 ``None`` if none was passed.
1291
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001292
Georg Brandl116aa622007-08-15 14:28:22 +00001293Supported operations:
1294
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001295* comparison of :class:`.time` to :class:`.time`, where *a* is considered less
Georg Brandl116aa622007-08-15 14:28:22 +00001296 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1297 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
Senthil Kumarana6bac952011-07-04 11:28:30 -07001298 the same :attr:`tzinfo` attribute, the common :attr:`tzinfo` attribute is
1299 ignored and the base times are compared. If both comparands are aware and
1300 have different :attr:`tzinfo` attributes, the comparands are first adjusted by
1301 subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
1302 to stop mixed-type comparisons from falling back to the default comparison by
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001303 object address, when a :class:`.time` object is compared to an object of a
Senthil Kumaran3aac1792011-07-04 11:43:51 -07001304 different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
Senthil Kumarana6bac952011-07-04 11:28:30 -07001305 ``!=``. The latter cases return :const:`False` or :const:`True`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +00001306
1307* hash, use as dict key
1308
1309* efficient pickling
1310
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001311* in Boolean contexts, a :class:`.time` object is considered to be true if and
Georg Brandl116aa622007-08-15 14:28:22 +00001312 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1313 ``0`` if that's ``None``), the result is non-zero.
1314
Georg Brandl116aa622007-08-15 14:28:22 +00001315
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001316Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001317
1318.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1319
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001320 Return a :class:`.time` with the same value, except for those attributes given
Senthil Kumarana6bac952011-07-04 11:28:30 -07001321 new values by whichever keyword arguments are specified. Note that
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001322 ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
1323 aware :class:`.time`, without conversion of the time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001324
1325
1326.. method:: time.isoformat()
1327
1328 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1329 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1330 6-character string is appended, giving the UTC offset in (signed) hours and
1331 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1332
1333
1334.. method:: time.__str__()
1335
1336 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1337
1338
1339.. method:: time.strftime(format)
1340
1341 Return a string representing the time, controlled by an explicit format string.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001342 See section :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001343
1344
1345.. method:: time.utcoffset()
1346
1347 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1348 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1349 return ``None`` or a :class:`timedelta` object representing a whole number of
1350 minutes with magnitude less than one day.
1351
1352
1353.. method:: time.dst()
1354
1355 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1356 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1357 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1358 with magnitude less than one day.
1359
1360
1361.. method:: time.tzname()
1362
1363 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1364 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1365 return ``None`` or a string object.
1366
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001367
Christian Heimesfe337bf2008-03-23 21:54:12 +00001368Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001369
Christian Heimes895627f2007-12-08 17:28:33 +00001370 >>> from datetime import time, tzinfo
1371 >>> class GMT1(tzinfo):
1372 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001373 ... return timedelta(hours=1)
1374 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001375 ... return timedelta(0)
1376 ... def tzname(self,dt):
1377 ... return "Europe/Prague"
1378 ...
1379 >>> t = time(12, 10, 30, tzinfo=GMT1())
1380 >>> t # doctest: +ELLIPSIS
1381 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1382 >>> gmt = GMT1()
1383 >>> t.isoformat()
1384 '12:10:30+01:00'
1385 >>> t.dst()
1386 datetime.timedelta(0)
1387 >>> t.tzname()
1388 'Europe/Prague'
1389 >>> t.strftime("%H:%M:%S %Z")
1390 '12:10:30 Europe/Prague'
1391
Georg Brandl116aa622007-08-15 14:28:22 +00001392
1393.. _datetime-tzinfo:
1394
1395:class:`tzinfo` Objects
1396-----------------------
1397
Brett Cannone1327f72009-01-29 04:10:21 +00001398:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001399instantiated directly. You need to derive a concrete subclass, and (at least)
1400supply implementations of the standard :class:`tzinfo` methods needed by the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001401:class:`.datetime` methods you use. The :mod:`datetime` module supplies
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001402a simple concrete subclass of :class:`tzinfo` :class:`timezone` which can reprsent
1403timezones with fixed offset from UTC such as UTC itself or North American EST and
1404EDT.
Georg Brandl116aa622007-08-15 14:28:22 +00001405
1406An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001407constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
Senthil Kumarana6bac952011-07-04 11:28:30 -07001408view their attributes as being in local time, and the :class:`tzinfo` object
Georg Brandl116aa622007-08-15 14:28:22 +00001409supports methods revealing offset of local time from UTC, the name of the time
1410zone, and DST offset, all relative to a date or time object passed to them.
1411
1412Special requirement for pickling: A :class:`tzinfo` subclass must have an
1413:meth:`__init__` method that can be called with no arguments, else it can be
1414pickled but possibly not unpickled again. This is a technical requirement that
1415may be relaxed in the future.
1416
1417A concrete subclass of :class:`tzinfo` may need to implement the following
1418methods. Exactly which methods are needed depends on the uses made of aware
1419:mod:`datetime` objects. If in doubt, simply implement all of them.
1420
1421
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001422.. method:: tzinfo.utcoffset(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001423
1424 Return offset of local time from UTC, in minutes east of UTC. If local time is
1425 west of UTC, this should be negative. Note that this is intended to be the
1426 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1427 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1428 the UTC offset isn't known, return ``None``. Else the value returned must be a
1429 :class:`timedelta` object specifying a whole number of minutes in the range
1430 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1431 than one day). Most implementations of :meth:`utcoffset` will probably look
1432 like one of these two::
1433
1434 return CONSTANT # fixed-offset class
1435 return CONSTANT + self.dst(dt) # daylight-aware class
1436
1437 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1438 ``None`` either.
1439
1440 The default implementation of :meth:`utcoffset` raises
1441 :exc:`NotImplementedError`.
1442
1443
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001444.. method:: tzinfo.dst(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001445
1446 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1447 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1448 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1449 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1450 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1451 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1452 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -07001453 attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
1454 should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
1455 DST changes when crossing time zones.
Georg Brandl116aa622007-08-15 14:28:22 +00001456
1457 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1458 daylight times must be consistent in this sense:
1459
1460 ``tz.utcoffset(dt) - tz.dst(dt)``
1461
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001462 must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo ==
Georg Brandl116aa622007-08-15 14:28:22 +00001463 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1464 zone's "standard offset", which should not depend on the date or the time, but
1465 only on geographic location. The implementation of :meth:`datetime.astimezone`
1466 relies on this, but cannot detect violations; it's the programmer's
1467 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1468 this, it may be able to override the default implementation of
1469 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1470
1471 Most implementations of :meth:`dst` will probably look like one of these two::
1472
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001473 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001474 # a fixed-offset class: doesn't account for DST
1475 return timedelta(0)
1476
1477 or ::
1478
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001479 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001480 # Code to set dston and dstoff to the time zone's DST
1481 # transition times based on the input dt.year, and expressed
1482 # in standard local time. Then
1483
1484 if dston <= dt.replace(tzinfo=None) < dstoff:
1485 return timedelta(hours=1)
1486 else:
1487 return timedelta(0)
1488
1489 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1490
1491
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001492.. method:: tzinfo.tzname(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001493
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001494 Return the time zone name corresponding to the :class:`.datetime` object *dt*, as
Georg Brandl116aa622007-08-15 14:28:22 +00001495 a string. Nothing about string names is defined by the :mod:`datetime` module,
1496 and there's no requirement that it mean anything in particular. For example,
1497 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1498 valid replies. Return ``None`` if a string name isn't known. Note that this is
1499 a method rather than a fixed string primarily because some :class:`tzinfo`
1500 subclasses will wish to return different names depending on the specific value
1501 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1502 daylight time.
1503
1504 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1505
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001506
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001507These methods are called by a :class:`.datetime` or :class:`.time` object, in
1508response to their methods of the same names. A :class:`.datetime` object passes
1509itself as the argument, and a :class:`.time` object passes ``None`` as the
Georg Brandl116aa622007-08-15 14:28:22 +00001510argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001511accept a *dt* argument of ``None``, or of class :class:`.datetime`.
Georg Brandl116aa622007-08-15 14:28:22 +00001512
1513When ``None`` is passed, it's up to the class designer to decide the best
1514response. For example, returning ``None`` is appropriate if the class wishes to
1515say that time objects don't participate in the :class:`tzinfo` protocols. It
1516may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1517there is no other convention for discovering the standard offset.
1518
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001519When a :class:`.datetime` object is passed in response to a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +00001520method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1521rely on this, unless user code calls :class:`tzinfo` methods directly. The
1522intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1523time, and not need worry about objects in other timezones.
1524
1525There is one more :class:`tzinfo` method that a subclass may wish to override:
1526
1527
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001528.. method:: tzinfo.fromutc(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001529
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001530 This is called from the default :class:`datetime.astimezone()`
1531 implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s
1532 date and time data are to be viewed as expressing a UTC time. The purpose
1533 of :meth:`fromutc` is to adjust the date and time data, returning an
Senthil Kumarana6bac952011-07-04 11:28:30 -07001534 equivalent datetime in *self*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00001535
1536 Most :class:`tzinfo` subclasses should be able to inherit the default
1537 :meth:`fromutc` implementation without problems. It's strong enough to handle
1538 fixed-offset time zones, and time zones accounting for both standard and
1539 daylight time, and the latter even if the DST transition times differ in
1540 different years. An example of a time zone the default :meth:`fromutc`
1541 implementation may not handle correctly in all cases is one where the standard
1542 offset (from UTC) depends on the specific date and time passed, which can happen
1543 for political reasons. The default implementations of :meth:`astimezone` and
1544 :meth:`fromutc` may not produce the result you want if the result is one of the
1545 hours straddling the moment the standard offset changes.
1546
1547 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1548 like::
1549
1550 def fromutc(self, dt):
1551 # raise ValueError error if dt.tzinfo is not self
1552 dtoff = dt.utcoffset()
1553 dtdst = dt.dst()
1554 # raise ValueError if dtoff is None or dtdst is None
1555 delta = dtoff - dtdst # this is self's standard offset
1556 if delta:
1557 dt += delta # convert to standard local time
1558 dtdst = dt.dst()
1559 # raise ValueError if dtdst is None
1560 if dtdst:
1561 return dt + dtdst
1562 else:
1563 return dt
1564
1565Example :class:`tzinfo` classes:
1566
1567.. literalinclude:: ../includes/tzinfo-examples.py
1568
Georg Brandl116aa622007-08-15 14:28:22 +00001569Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1570subclass accounting for both standard and daylight time, at the DST transition
1571points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00001572minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
15731:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001574
1575 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1576 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1577 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1578
1579 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1580
1581 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1582
1583When DST starts (the "start" line), the local wall clock leaps from 1:59 to
15843:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1585``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1586begins. In order for :meth:`astimezone` to make this guarantee, the
1587:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1588Eastern) to be in daylight time.
1589
1590When DST ends (the "end" line), there's a potentially worse problem: there's an
1591hour that can't be spelled unambiguously in local wall time: the last hour of
1592daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1593daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1594to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1595:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1596hours into the same local hour then. In the Eastern example, UTC times of the
1597form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1598:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1599consider times in the "repeated hour" to be in standard time. This is easily
1600arranged, as in the example, by expressing DST switch times in the time zone's
1601standard local time.
1602
1603Applications that can't bear such ambiguities should avoid using hybrid
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001604:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`,
1605or any other fixed-offset :class:`tzinfo` subclass (such as a class representing
1606only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
1607
Sandro Tosid11d0d62012-04-24 19:46:06 +02001608.. seealso::
1609
1610 `pytz <http://pypi.python.org/pypi/pytz/>`_
Sandro Tosi100b8892012-04-28 11:19:37 +02001611 The standard library has no :class:`tzinfo` instances except for UTC, but
1612 there exists a third-party library which brings the *IANA timezone
1613 database* (also known as the Olson database) to Python: *pytz*.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001614
Sandro Tosi100b8892012-04-28 11:19:37 +02001615 *pytz* contains up-to-date information and its usage is recommended.
1616
1617 `IANA timezone database <http://www.iana.org/time-zones>`_
1618 The Time Zone Database (often called tz or zoneinfo) contains code and
1619 data that represent the history of local time for many representative
1620 locations around the globe. It is updated periodically to reflect changes
1621 made by political bodies to time zone boundaries, UTC offsets, and
1622 daylight-saving rules.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001623
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001624
1625.. _datetime-timezone:
1626
1627:class:`timezone` Objects
1628--------------------------
1629
Alexander Belopolsky6d3c9a62011-05-04 10:28:26 -04001630The :class:`timezone` class is a subclass of :class:`tzinfo`, each
1631instance of which represents a timezone defined by a fixed offset from
1632UTC. Note that objects of this class cannot be used to represent
1633timezone information in the locations where different offsets are used
1634in different days of the year or where historical changes have been
1635made to civil time.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001636
1637
1638.. class:: timezone(offset[, name])
1639
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001640 The *offset* argument must be specified as a :class:`timedelta`
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001641 object representing the difference between the local time and UTC. It must
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001642 be strictly between ``-timedelta(hours=24)`` and
1643 ``timedelta(hours=24)`` and represent a whole number of minutes,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001644 otherwise :exc:`ValueError` is raised.
1645
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001646 The *name* argument is optional. If specified it must be a string that
1647 is used as the value returned by the ``tzname(dt)`` method. Otherwise,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001648 ``tzname(dt)`` returns a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001649 *offset*, HH and MM are two digits of ``offset.hours`` and
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001650 ``offset.minutes`` respectively.
1651
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001652.. method:: timezone.utcoffset(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001653
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001654 Return the fixed value specified when the :class:`timezone` instance is
1655 constructed. The *dt* argument is ignored. The return value is a
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001656 :class:`timedelta` instance equal to the difference between the
1657 local time and UTC.
1658
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001659.. method:: timezone.tzname(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001660
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001661 Return the fixed value specified when the :class:`timezone` instance is
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001662 constructed or a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001663 *offset*, HH and MM are two digits of ``offset.hours`` and
1664 ``offset.minutes`` respectively.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001665
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001666.. method:: timezone.dst(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001667
1668 Always returns ``None``.
1669
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001670.. method:: timezone.fromutc(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001671
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001672 Return ``dt + offset``. The *dt* argument must be an aware
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001673 :class:`.datetime` instance, with ``tzinfo`` set to ``self``.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001674
1675Class attributes:
1676
1677.. attribute:: timezone.utc
1678
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001679 The UTC timezone, ``timezone(timedelta(0))``.
Georg Brandl48310cd2009-01-03 21:18:54 +00001680
Georg Brandl116aa622007-08-15 14:28:22 +00001681
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001682.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00001683
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001684:meth:`strftime` and :meth:`strptime` Behavior
1685----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001686
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001687:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
Georg Brandl116aa622007-08-15 14:28:22 +00001688``strftime(format)`` method, to create a string representing the time under the
1689control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1690acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1691although not all objects support a :meth:`timetuple` method.
1692
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001693Conversely, the :meth:`datetime.strptime` class method creates a
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001694:class:`.datetime` object from a string representing a date and time and a
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001695corresponding format string. ``datetime.strptime(date_string, format)`` is
1696equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1697
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001698For :class:`.time` objects, the format codes for year, month, and day should not
Georg Brandl116aa622007-08-15 14:28:22 +00001699be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001700is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00001701
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001702For :class:`date` objects, the format codes for hours, minutes, seconds, and
1703microseconds should not be used, as :class:`date` objects have no such
1704values. If they're used anyway, ``0`` is substituted for them.
1705
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001706For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1707strings.
1708
1709For an aware object:
1710
1711``%z``
1712 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1713 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1714 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1715 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1716 replaced with the string ``'-0330'``.
1717
1718``%Z``
1719 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1720 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl116aa622007-08-15 14:28:22 +00001721
Georg Brandl116aa622007-08-15 14:28:22 +00001722The full set of format codes supported varies across platforms, because Python
1723calls the platform C library's :func:`strftime` function, and platform
Georg Brandl48310cd2009-01-03 21:18:54 +00001724variations are common.
Christian Heimes895627f2007-12-08 17:28:33 +00001725
1726The following is a list of all the format codes that the C standard (1989
1727version) requires, and these work on all platforms with a standard C
1728implementation. Note that the 1999 version of the C standard added additional
1729format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001730
Christian Heimes895627f2007-12-08 17:28:33 +00001731+-----------+--------------------------------+-------+
1732| Directive | Meaning | Notes |
1733+===========+================================+=======+
1734| ``%a`` | Locale's abbreviated weekday | |
1735| | name. | |
1736+-----------+--------------------------------+-------+
1737| ``%A`` | Locale's full weekday name. | |
1738+-----------+--------------------------------+-------+
1739| ``%b`` | Locale's abbreviated month | |
1740| | name. | |
1741+-----------+--------------------------------+-------+
1742| ``%B`` | Locale's full month name. | |
1743+-----------+--------------------------------+-------+
1744| ``%c`` | Locale's appropriate date and | |
1745| | time representation. | |
1746+-----------+--------------------------------+-------+
1747| ``%d`` | Day of the month as a decimal | |
1748| | number [01,31]. | |
1749+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001750| ``%f`` | Microsecond as a decimal | \(1) |
1751| | number [0,999999], zero-padded | |
1752| | on the left | |
1753+-----------+--------------------------------+-------+
Christian Heimes895627f2007-12-08 17:28:33 +00001754| ``%H`` | Hour (24-hour clock) as a | |
1755| | decimal number [00,23]. | |
1756+-----------+--------------------------------+-------+
1757| ``%I`` | Hour (12-hour clock) as a | |
1758| | decimal number [01,12]. | |
1759+-----------+--------------------------------+-------+
1760| ``%j`` | Day of the year as a decimal | |
1761| | number [001,366]. | |
1762+-----------+--------------------------------+-------+
1763| ``%m`` | Month as a decimal number | |
1764| | [01,12]. | |
1765+-----------+--------------------------------+-------+
1766| ``%M`` | Minute as a decimal number | |
1767| | [00,59]. | |
1768+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001769| ``%p`` | Locale's equivalent of either | \(2) |
Christian Heimes895627f2007-12-08 17:28:33 +00001770| | AM or PM. | |
1771+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001772| ``%S`` | Second as a decimal number | \(3) |
Alexander Belopolsky9971e002011-01-10 22:56:14 +00001773| | [00,59]. | |
Christian Heimes895627f2007-12-08 17:28:33 +00001774+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001775| ``%U`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001776| | (Sunday as the first day of | |
1777| | the week) as a decimal number | |
1778| | [00,53]. All days in a new | |
1779| | year preceding the first | |
1780| | Sunday are considered to be in | |
1781| | week 0. | |
1782+-----------+--------------------------------+-------+
1783| ``%w`` | Weekday as a decimal number | |
1784| | [0(Sunday),6]. | |
1785+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001786| ``%W`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001787| | (Monday as the first day of | |
1788| | the week) as a decimal number | |
1789| | [00,53]. All days in a new | |
1790| | year preceding the first | |
1791| | Monday are considered to be in | |
1792| | week 0. | |
1793+-----------+--------------------------------+-------+
1794| ``%x`` | Locale's appropriate date | |
1795| | representation. | |
1796+-----------+--------------------------------+-------+
1797| ``%X`` | Locale's appropriate time | |
1798| | representation. | |
1799+-----------+--------------------------------+-------+
1800| ``%y`` | Year without century as a | |
1801| | decimal number [00,99]. | |
1802+-----------+--------------------------------+-------+
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001803| ``%Y`` | Year with century as a decimal | \(5) |
Alexander Belopolsky89da3492011-05-02 13:14:24 -04001804| | number [0001,9999]. | |
Christian Heimes895627f2007-12-08 17:28:33 +00001805+-----------+--------------------------------+-------+
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001806| ``%z`` | UTC offset in the form +HHMM | \(6) |
Christian Heimes895627f2007-12-08 17:28:33 +00001807| | or -HHMM (empty string if the | |
1808| | the object is naive). | |
1809+-----------+--------------------------------+-------+
1810| ``%Z`` | Time zone name (empty string | |
1811| | if the object is naive). | |
1812+-----------+--------------------------------+-------+
1813| ``%%`` | A literal ``'%'`` character. | |
1814+-----------+--------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001815
Christian Heimes895627f2007-12-08 17:28:33 +00001816Notes:
1817
1818(1)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001819 When used with the :meth:`strptime` method, the ``%f`` directive
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001820 accepts from one to six digits and zero pads on the right. ``%f`` is
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001821 an extension to the set of format characters in the C standard (but
1822 implemented separately in datetime objects, and therefore always
1823 available).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001824
1825(2)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001826 When used with the :meth:`strptime` method, the ``%p`` directive only affects
Christian Heimes895627f2007-12-08 17:28:33 +00001827 the output hour field if the ``%I`` directive is used to parse the hour.
1828
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001829(3)
Alexander Belopolsky9971e002011-01-10 22:56:14 +00001830 Unlike :mod:`time` module, :mod:`datetime` module does not support
1831 leap seconds.
Christian Heimes895627f2007-12-08 17:28:33 +00001832
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001833(4)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001834 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in
Christian Heimes895627f2007-12-08 17:28:33 +00001835 calculations when the day of the week and the year are specified.
1836
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001837(5)
Alexander Belopolsky89da3492011-05-02 13:14:24 -04001838 The :meth:`strptime` method can
Alexander Belopolsky5fc850b2011-01-10 23:31:51 +00001839 parse years in the full [1, 9999] range, but years < 1000 must be
1840 zero-filled to 4-digit width.
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001841
1842 .. versionchanged:: 3.2
1843 In previous versions, :meth:`strftime` method was restricted to
1844 years >= 1900.
1845
Alexander Belopolsky5611a1c2011-05-02 14:14:48 -04001846 .. versionchanged:: 3.3
1847 In version 3.2, :meth:`strftime` method was restricted to
1848 years >= 1000.
1849
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001850(6)
Christian Heimes895627f2007-12-08 17:28:33 +00001851 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1852 ``%z`` is replaced with the string ``'-0330'``.
Alexander Belopolskyca94f552010-06-17 18:30:34 +00001853
Georg Brandl67b21b72010-08-17 15:07:14 +00001854.. versionchanged:: 3.2
1855 When the ``%z`` directive is provided to the :meth:`strptime` method, an
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001856 aware :class:`.datetime` object will be produced. The ``tzinfo`` of the
Georg Brandl67b21b72010-08-17 15:07:14 +00001857 result will be set to a :class:`timezone` instance.
R David Murray9075d8b2012-05-14 22:14:46 -04001858
1859.. rubric:: Footnotes
1860
1861.. [#] If, that is, we ignore the effects of Relativity