blob: f7e8762a7aa0c2eb9fd086f93e9d7f3223cb83a8 [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".
19
20An 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
407 by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out
Georg Brandl60203b42010-10-06 10:11:56 +0000408 of the range of values supported by the platform C :c:func:`localtime` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000409 It's common for this to be restricted to years from 1970 through 2038. Note
410 that on non-POSIX systems that include leap seconds in their notion of a
411 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
412
413
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000414.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000415
416 Return the date corresponding to the proleptic Gregorian ordinal, where January
417 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
418 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
419 d``.
420
Georg Brandl116aa622007-08-15 14:28:22 +0000421
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000422Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000423
424.. attribute:: date.min
425
426 The earliest representable date, ``date(MINYEAR, 1, 1)``.
427
428
429.. attribute:: date.max
430
431 The latest representable date, ``date(MAXYEAR, 12, 31)``.
432
433
434.. attribute:: date.resolution
435
436 The smallest possible difference between non-equal date objects,
437 ``timedelta(days=1)``.
438
Georg Brandl116aa622007-08-15 14:28:22 +0000439
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000440Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000441
442.. attribute:: date.year
443
444 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
445
446
447.. attribute:: date.month
448
449 Between 1 and 12 inclusive.
450
451
452.. attribute:: date.day
453
454 Between 1 and the number of days in the given month of the given year.
455
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000456
Georg Brandl116aa622007-08-15 14:28:22 +0000457Supported operations:
458
459+-------------------------------+----------------------------------------------+
460| Operation | Result |
461+===============================+==============================================+
462| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
463| | from *date1*. (1) |
464+-------------------------------+----------------------------------------------+
465| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
466| | timedelta == date1``. (2) |
467+-------------------------------+----------------------------------------------+
468| ``timedelta = date1 - date2`` | \(3) |
469+-------------------------------+----------------------------------------------+
470| ``date1 < date2`` | *date1* is considered less than *date2* when |
471| | *date1* precedes *date2* in time. (4) |
472+-------------------------------+----------------------------------------------+
473
474Notes:
475
476(1)
477 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
478 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
479 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
480 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
481 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
482
483(2)
484 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
485 isolation can overflow in cases where date1 - timedelta does not.
486 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
487
488(3)
489 This is exact, and cannot overflow. timedelta.seconds and
490 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
491
492(4)
493 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
494 date2.toordinal()``. In order to stop comparison from falling back to the
495 default scheme of comparing object addresses, date comparison normally raises
496 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
497 However, ``NotImplemented`` is returned instead if the other comparand has a
498 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
499 chance at implementing mixed-type comparison. If not, when a :class:`date`
500 object is compared to an object of a different type, :exc:`TypeError` is raised
501 unless the comparison is ``==`` or ``!=``. The latter cases return
502 :const:`False` or :const:`True`, respectively.
503
504Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
505objects are considered to be true.
506
507Instance methods:
508
Georg Brandl116aa622007-08-15 14:28:22 +0000509.. method:: date.replace(year, month, day)
510
Senthil Kumarana6bac952011-07-04 11:28:30 -0700511 Return a date with the same value, except for those parameters given new
512 values by whichever keyword arguments are specified. For example, if ``d ==
513 date(2002, 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000514
515
516.. method:: date.timetuple()
517
518 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
519 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
520 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000521 d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1,
522 1).toordinal() + 1`` is the day number within the current year starting with
523 ``1`` for January 1st.
Georg Brandl116aa622007-08-15 14:28:22 +0000524
525
526.. method:: date.toordinal()
527
528 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
529 has ordinal 1. For any :class:`date` object *d*,
530 ``date.fromordinal(d.toordinal()) == d``.
531
532
533.. method:: date.weekday()
534
535 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
536 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
537 :meth:`isoweekday`.
538
539
540.. method:: date.isoweekday()
541
542 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
543 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
544 :meth:`weekday`, :meth:`isocalendar`.
545
546
547.. method:: date.isocalendar()
548
549 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
550
551 The ISO calendar is a widely used variant of the Gregorian calendar. See
Mark Dickinsonf964ac22009-11-03 16:29:10 +0000552 http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
553 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000554
555 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
556 Monday and ends on a Sunday. The first week of an ISO year is the first
557 (Gregorian) calendar week of a year containing a Thursday. This is called week
558 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
559
560 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
561 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
562 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
563 4).isocalendar() == (2004, 1, 7)``.
564
565
566.. method:: date.isoformat()
567
568 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
569 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
570
571
572.. method:: date.__str__()
573
574 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
575
576
577.. method:: date.ctime()
578
579 Return a string representing the date, for example ``date(2002, 12,
580 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
581 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
Georg Brandl60203b42010-10-06 10:11:56 +0000582 :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +0000583 :meth:`date.ctime` does not invoke) conforms to the C standard.
584
585
586.. method:: date.strftime(format)
587
588 Return a string representing the date, controlled by an explicit format string.
589 Format codes referring to hours, minutes or seconds will see 0 values. See
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000590 section :ref:`strftime-strptime-behavior`.
591
Georg Brandl116aa622007-08-15 14:28:22 +0000592
Christian Heimes895627f2007-12-08 17:28:33 +0000593Example of counting days to an event::
594
595 >>> import time
596 >>> from datetime import date
597 >>> today = date.today()
598 >>> today
599 datetime.date(2007, 12, 5)
600 >>> today == date.fromtimestamp(time.time())
601 True
602 >>> my_birthday = date(today.year, 6, 24)
603 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000604 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000605 >>> my_birthday
606 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000607 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000608 >>> time_to_birthday.days
609 202
610
Christian Heimesfe337bf2008-03-23 21:54:12 +0000611Example of working with :class:`date`:
612
613.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000614
615 >>> from datetime import date
616 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
617 >>> d
618 datetime.date(2002, 3, 11)
619 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000620 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000621 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000622 2002 # year
623 3 # month
624 11 # day
625 0
626 0
627 0
628 0 # weekday (0 = Monday)
629 70 # 70th day in the year
630 -1
631 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000632 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000633 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000634 2002 # ISO year
635 11 # ISO week number
636 1 # ISO day number ( 1 = Monday )
637 >>> d.isoformat()
638 '2002-03-11'
639 >>> d.strftime("%d/%m/%y")
640 '11/03/02'
641 >>> d.strftime("%A %d. %B %Y")
642 'Monday 11. March 2002'
643
Georg Brandl116aa622007-08-15 14:28:22 +0000644
645.. _datetime-datetime:
646
647:class:`datetime` Objects
648-------------------------
649
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300650A :class:`.datetime` object is a single object containing all the information
651from a :class:`date` object and a :class:`.time` object. Like a :class:`date`
652object, :class:`.datetime` assumes the current Gregorian calendar extended in
653both directions; like a time object, :class:`.datetime` assumes there are exactly
Georg Brandl116aa622007-08-15 14:28:22 +00006543600\*24 seconds in every day.
655
656Constructor:
657
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000658.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000659
660 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000661 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
662 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000663
664 * ``MINYEAR <= year <= MAXYEAR``
665 * ``1 <= month <= 12``
666 * ``1 <= day <= number of days in the given month and year``
667 * ``0 <= hour < 24``
668 * ``0 <= minute < 60``
669 * ``0 <= second < 60``
670 * ``0 <= microsecond < 1000000``
671
672 If an argument outside those ranges is given, :exc:`ValueError` is raised.
673
674Other constructors, all class methods:
675
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000676.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000677
678 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
679 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
680 :meth:`fromtimestamp`.
681
682
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000683.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000684
685 Return the current local date and time. If optional argument *tz* is ``None``
686 or not specified, this is like :meth:`today`, but, if possible, supplies more
687 precision than can be gotten from going through a :func:`time.time` timestamp
688 (for example, this may be possible on platforms supplying the C
Georg Brandl60203b42010-10-06 10:11:56 +0000689 :c:func:`gettimeofday` function).
Georg Brandl116aa622007-08-15 14:28:22 +0000690
691 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
692 current date and time are converted to *tz*'s time zone. In this case the
693 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
694 See also :meth:`today`, :meth:`utcnow`.
695
696
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000697.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000698
699 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
700 :meth:`now`, but returns the current UTC date and time, as a naive
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300701 :class:`.datetime` object. An aware current UTC datetime can be obtained by
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000702 calling ``datetime.now(timezone.utc)``. See also :meth:`now`.
Georg Brandl116aa622007-08-15 14:28:22 +0000703
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000704.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000705
706 Return the local date and time corresponding to the POSIX timestamp, such as is
707 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
708 specified, the timestamp is converted to the platform's local date and time, and
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300709 the returned :class:`.datetime` object is naive.
Georg Brandl116aa622007-08-15 14:28:22 +0000710
711 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
712 timestamp is converted to *tz*'s time zone. In this case the result is
713 equivalent to
714 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
715
716 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
Georg Brandl60203b42010-10-06 10:11:56 +0000717 the range of values supported by the platform C :c:func:`localtime` or
718 :c:func:`gmtime` functions. It's common for this to be restricted to years in
Georg Brandl116aa622007-08-15 14:28:22 +0000719 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
720 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
721 and then it's possible to have two timestamps differing by a second that yield
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300722 identical :class:`.datetime` objects. See also :meth:`utcfromtimestamp`.
Georg Brandl116aa622007-08-15 14:28:22 +0000723
724
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000725.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000726
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300727 Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with
Georg Brandl116aa622007-08-15 14:28:22 +0000728 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
Georg Brandl60203b42010-10-06 10:11:56 +0000729 out of the range of values supported by the platform C :c:func:`gmtime` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000730 It's common for this to be restricted to years in 1970 through 2038. See also
731 :meth:`fromtimestamp`.
732
733
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000734.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000735
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300736 Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal,
Georg Brandl116aa622007-08-15 14:28:22 +0000737 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
738 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
739 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
740
741
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000742.. classmethod:: datetime.combine(date, time)
Georg Brandl116aa622007-08-15 14:28:22 +0000743
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300744 Return a new :class:`.datetime` object whose date components are equal to the
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800745 given :class:`date` object's, and whose time components and :attr:`tzinfo`
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300746 attributes are equal to the given :class:`.time` object's. For any
747 :class:`.datetime` object *d*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800748 ``d == datetime.combine(d.date(), d.timetz())``. If date is a
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300749 :class:`.datetime` object, its time components and :attr:`tzinfo` attributes
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800750 are ignored.
Georg Brandl116aa622007-08-15 14:28:22 +0000751
752
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000753.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000754
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300755 Return a :class:`.datetime` corresponding to *date_string*, parsed according to
Georg Brandl116aa622007-08-15 14:28:22 +0000756 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
757 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
758 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 +0000759 time tuple. See section :ref:`strftime-strptime-behavior`.
760
Georg Brandl116aa622007-08-15 14:28:22 +0000761
Georg Brandl116aa622007-08-15 14:28:22 +0000762
763Class attributes:
764
Georg Brandl116aa622007-08-15 14:28:22 +0000765.. attribute:: datetime.min
766
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300767 The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1,
Georg Brandl116aa622007-08-15 14:28:22 +0000768 tzinfo=None)``.
769
770
771.. attribute:: datetime.max
772
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300773 The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
Georg Brandl116aa622007-08-15 14:28:22 +0000774 59, 999999, tzinfo=None)``.
775
776
777.. attribute:: datetime.resolution
778
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300779 The smallest possible difference between non-equal :class:`.datetime` objects,
Georg Brandl116aa622007-08-15 14:28:22 +0000780 ``timedelta(microseconds=1)``.
781
Georg Brandl116aa622007-08-15 14:28:22 +0000782
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000783Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000784
785.. attribute:: datetime.year
786
787 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
788
789
790.. attribute:: datetime.month
791
792 Between 1 and 12 inclusive.
793
794
795.. attribute:: datetime.day
796
797 Between 1 and the number of days in the given month of the given year.
798
799
800.. attribute:: datetime.hour
801
802 In ``range(24)``.
803
804
805.. attribute:: datetime.minute
806
807 In ``range(60)``.
808
809
810.. attribute:: datetime.second
811
812 In ``range(60)``.
813
814
815.. attribute:: datetime.microsecond
816
817 In ``range(1000000)``.
818
819
820.. attribute:: datetime.tzinfo
821
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300822 The object passed as the *tzinfo* argument to the :class:`.datetime` constructor,
Georg Brandl116aa622007-08-15 14:28:22 +0000823 or ``None`` if none was passed.
824
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000825
Georg Brandl116aa622007-08-15 14:28:22 +0000826Supported operations:
827
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300828+---------------------------------------+--------------------------------+
829| Operation | Result |
830+=======================================+================================+
831| ``datetime2 = datetime1 + timedelta`` | \(1) |
832+---------------------------------------+--------------------------------+
833| ``datetime2 = datetime1 - timedelta`` | \(2) |
834+---------------------------------------+--------------------------------+
835| ``timedelta = datetime1 - datetime2`` | \(3) |
836+---------------------------------------+--------------------------------+
837| ``datetime1 < datetime2`` | Compares :class:`.datetime` to |
838| | :class:`.datetime`. (4) |
839+---------------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000840
841(1)
842 datetime2 is a duration of timedelta removed from datetime1, moving forward in
843 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
Senthil Kumarana6bac952011-07-04 11:28:30 -0700844 result has the same :attr:`tzinfo` attribute as the input datetime, and
845 datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
846 datetime2.year would be smaller than :const:`MINYEAR` or larger than
847 :const:`MAXYEAR`. Note that no time zone adjustments are done even if the
848 input is an aware object.
Georg Brandl116aa622007-08-15 14:28:22 +0000849
850(2)
851 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
Senthil Kumarana6bac952011-07-04 11:28:30 -0700852 addition, the result has the same :attr:`tzinfo` attribute as the input
853 datetime, and no time zone adjustments are done even if the input is aware.
854 This isn't quite equivalent to datetime1 + (-timedelta), because -timedelta
855 in isolation can overflow in cases where datetime1 - timedelta does not.
Georg Brandl116aa622007-08-15 14:28:22 +0000856
857(3)
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300858 Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if
Georg Brandl116aa622007-08-15 14:28:22 +0000859 both operands are naive, or if both are aware. If one is aware and the other is
860 naive, :exc:`TypeError` is raised.
861
Senthil Kumarana6bac952011-07-04 11:28:30 -0700862 If both are naive, or both are aware and have the same :attr:`tzinfo` attribute,
863 the :attr:`tzinfo` attributes are ignored, and the result is a :class:`timedelta`
Georg Brandl116aa622007-08-15 14:28:22 +0000864 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
865 are done in this case.
866
Senthil Kumarana6bac952011-07-04 11:28:30 -0700867 If both are aware and have different :attr:`tzinfo` attributes, ``a-b`` acts
868 as if *a* and *b* were first converted to naive UTC datetimes first. The
869 result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
870 - b.utcoffset())`` except that the implementation never overflows.
Georg Brandl116aa622007-08-15 14:28:22 +0000871
872(4)
873 *datetime1* is considered less than *datetime2* when *datetime1* precedes
874 *datetime2* in time.
875
876 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
Senthil Kumarana6bac952011-07-04 11:28:30 -0700877 If both comparands are aware, and have the same :attr:`tzinfo` attribute, the
878 common :attr:`tzinfo` attribute is ignored and the base datetimes are
879 compared. If both comparands are aware and have different :attr:`tzinfo`
880 attributes, the comparands are first adjusted by subtracting their UTC
881 offsets (obtained from ``self.utcoffset()``).
Georg Brandl116aa622007-08-15 14:28:22 +0000882
883 .. note::
884
885 In order to stop comparison from falling back to the default scheme of comparing
886 object addresses, datetime comparison normally raises :exc:`TypeError` if the
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300887 other comparand isn't also a :class:`.datetime` object. However,
Georg Brandl116aa622007-08-15 14:28:22 +0000888 ``NotImplemented`` is returned instead if the other comparand has a
889 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300890 chance at implementing mixed-type comparison. If not, when a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +0000891 object is compared to an object of a different type, :exc:`TypeError` is raised
892 unless the comparison is ``==`` or ``!=``. The latter cases return
893 :const:`False` or :const:`True`, respectively.
894
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300895:class:`.datetime` objects can be used as dictionary keys. In Boolean contexts,
896all :class:`.datetime` objects are considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +0000897
898Instance methods:
899
Georg Brandl116aa622007-08-15 14:28:22 +0000900.. method:: datetime.date()
901
902 Return :class:`date` object with same year, month and day.
903
904
905.. method:: datetime.time()
906
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300907 Return :class:`.time` object with same hour, minute, second and microsecond.
Georg Brandl116aa622007-08-15 14:28:22 +0000908 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
909
910
911.. method:: datetime.timetz()
912
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300913 Return :class:`.time` object with same hour, minute, second, microsecond, and
Senthil Kumarana6bac952011-07-04 11:28:30 -0700914 tzinfo attributes. See also method :meth:`time`.
Georg Brandl116aa622007-08-15 14:28:22 +0000915
916
917.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
918
Senthil Kumarana6bac952011-07-04 11:28:30 -0700919 Return a datetime with the same attributes, except for those attributes given
920 new values by whichever keyword arguments are specified. Note that
921 ``tzinfo=None`` can be specified to create a naive datetime from an aware
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800922 datetime with no conversion of date and time data.
Georg Brandl116aa622007-08-15 14:28:22 +0000923
924
925.. method:: datetime.astimezone(tz)
926
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300927 Return a :class:`.datetime` object with new :attr:`tzinfo` attribute *tz*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800928 adjusting the date and time data so the result is the same UTC time as
Senthil Kumarana6bac952011-07-04 11:28:30 -0700929 *self*, but in *tz*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +0000930
931 *tz* must be an instance of a :class:`tzinfo` subclass, and its
932 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
933 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
934 not return ``None``).
935
936 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800937 adjustment of date or time data is performed. Else the result is local
Senthil Kumarana6bac952011-07-04 11:28:30 -0700938 time in time zone *tz*, representing the same UTC time as *self*: after
939 ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800940 the same date and time data as ``dt - dt.utcoffset()``. The discussion
Senthil Kumarana6bac952011-07-04 11:28:30 -0700941 of class :class:`tzinfo` explains the cases at Daylight Saving Time transition
942 boundaries where this cannot be achieved (an issue only if *tz* models both
943 standard and daylight time).
Georg Brandl116aa622007-08-15 14:28:22 +0000944
945 If you merely want to attach a time zone object *tz* to a datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800946 adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you
Georg Brandl116aa622007-08-15 14:28:22 +0000947 merely want to remove the time zone object from an aware datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800948 conversion of date and time data, use ``dt.replace(tzinfo=None)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000949
950 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
951 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
952 Ignoring error cases, :meth:`astimezone` acts like::
953
954 def astimezone(self, tz):
955 if self.tzinfo is tz:
956 return self
957 # Convert self to UTC, and attach the new time zone object.
958 utc = (self - self.utcoffset()).replace(tzinfo=tz)
959 # Convert from UTC to tz's local time.
960 return tz.fromutc(utc)
961
962
963.. method:: datetime.utcoffset()
964
965 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
966 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
967 return ``None``, or a :class:`timedelta` object representing a whole number of
968 minutes with magnitude less than one day.
969
970
971.. method:: datetime.dst()
972
973 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
974 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
975 ``None``, or a :class:`timedelta` object representing a whole number of minutes
976 with magnitude less than one day.
977
978
979.. method:: datetime.tzname()
980
981 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
982 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
983 ``None`` or a string object,
984
985
986.. method:: datetime.timetuple()
987
988 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
989 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000990 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
991 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
992 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
993 of the result is set according to the :meth:`dst` method: :attr:`tzinfo` is
Georg Brandl682d7e02010-10-06 10:26:05 +0000994 ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
Alexander Belopolsky64912482010-06-08 18:59:20 +0000995 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
Alexander Belopolskyda62f2f2010-06-09 17:11:01 +0000996 else :attr:`tm_isdst` is set to ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +0000997
998
999.. method:: datetime.utctimetuple()
1000
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001001 If :class:`.datetime` instance *d* is naive, this is the same as
Georg Brandl116aa622007-08-15 14:28:22 +00001002 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
1003 ``d.dst()`` returns. DST is never in effect for a UTC time.
1004
1005 If *d* is aware, *d* is normalized to UTC time, by subtracting
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00001006 ``d.utcoffset()``, and a :class:`time.struct_time` for the
1007 normalized time is returned. :attr:`tm_isdst` is forced to 0. Note
1008 that an :exc:`OverflowError` may be raised if *d*.year was
1009 ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
Georg Brandl116aa622007-08-15 14:28:22 +00001010 boundary.
1011
1012
1013.. method:: datetime.toordinal()
1014
1015 Return the proleptic Gregorian ordinal of the date. The same as
1016 ``self.date().toordinal()``.
1017
1018
1019.. method:: datetime.weekday()
1020
1021 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
1022 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
1023
1024
1025.. method:: datetime.isoweekday()
1026
1027 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
1028 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
1029 :meth:`isocalendar`.
1030
1031
1032.. method:: datetime.isocalendar()
1033
1034 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
1035 ``self.date().isocalendar()``.
1036
1037
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001038.. method:: datetime.isoformat(sep='T')
Georg Brandl116aa622007-08-15 14:28:22 +00001039
1040 Return a string representing the date and time in ISO 8601 format,
1041 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
1042 YYYY-MM-DDTHH:MM:SS
1043
1044 If :meth:`utcoffset` does not return ``None``, a 6-character string is
1045 appended, giving the UTC offset in (signed) hours and minutes:
1046 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
1047 YYYY-MM-DDTHH:MM:SS+HH:MM
1048
1049 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +00001050 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +00001051
1052 >>> from datetime import tzinfo, timedelta, datetime
1053 >>> class TZ(tzinfo):
1054 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1055 ...
1056 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1057 '2002-12-25 00:00:00-06:39'
1058
1059
1060.. method:: datetime.__str__()
1061
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001062 For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to
Georg Brandl116aa622007-08-15 14:28:22 +00001063 ``d.isoformat(' ')``.
1064
1065
1066.. method:: datetime.ctime()
1067
1068 Return a string representing the date and time, for example ``datetime(2002, 12,
1069 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1070 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
Georg Brandl60203b42010-10-06 10:11:56 +00001071 native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +00001072 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1073
1074
1075.. method:: datetime.strftime(format)
1076
1077 Return a string representing the date and time, controlled by an explicit format
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001078 string. See section :ref:`strftime-strptime-behavior`.
1079
Georg Brandl116aa622007-08-15 14:28:22 +00001080
Christian Heimesfe337bf2008-03-23 21:54:12 +00001081Examples of working with datetime objects:
1082
1083.. doctest::
1084
Christian Heimes895627f2007-12-08 17:28:33 +00001085 >>> from datetime import datetime, date, time
1086 >>> # Using datetime.combine()
1087 >>> d = date(2005, 7, 14)
1088 >>> t = time(12, 30)
1089 >>> datetime.combine(d, t)
1090 datetime.datetime(2005, 7, 14, 12, 30)
1091 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001092 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001093 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001094 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001095 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1096 >>> # Using datetime.strptime()
1097 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1098 >>> dt
1099 datetime.datetime(2006, 11, 21, 16, 30)
1100 >>> # Using datetime.timetuple() to get tuple of all attributes
1101 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001102 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001103 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001104 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001105 2006 # year
1106 11 # month
1107 21 # day
1108 16 # hour
1109 30 # minute
1110 0 # second
1111 1 # weekday (0 = Monday)
1112 325 # number of days since 1st January
1113 -1 # dst - method tzinfo.dst() returned None
1114 >>> # Date in ISO format
1115 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001116 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001117 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001118 ...
1119 2006 # ISO year
1120 47 # ISO week
1121 2 # ISO weekday
1122 >>> # Formatting datetime
1123 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1124 'Tuesday, 21. November 2006 04:30PM'
1125
Christian Heimesfe337bf2008-03-23 21:54:12 +00001126Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001127
1128 >>> from datetime import timedelta, datetime, tzinfo
1129 >>> class GMT1(tzinfo):
1130 ... def __init__(self): # DST starts last Sunday in March
1131 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1132 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001133 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001134 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1135 ... def utcoffset(self, dt):
1136 ... return timedelta(hours=1) + self.dst(dt)
Georg Brandl48310cd2009-01-03 21:18:54 +00001137 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001138 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1139 ... return timedelta(hours=1)
1140 ... else:
1141 ... return timedelta(0)
1142 ... def tzname(self,dt):
1143 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001144 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001145 >>> class GMT2(tzinfo):
1146 ... def __init__(self):
Georg Brandl48310cd2009-01-03 21:18:54 +00001147 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001148 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001149 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001150 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1151 ... def utcoffset(self, dt):
1152 ... return timedelta(hours=1) + self.dst(dt)
1153 ... def dst(self, dt):
1154 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1155 ... return timedelta(hours=2)
1156 ... else:
1157 ... return timedelta(0)
1158 ... def tzname(self,dt):
1159 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001160 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001161 >>> gmt1 = GMT1()
1162 >>> # Daylight Saving Time
1163 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1164 >>> dt1.dst()
1165 datetime.timedelta(0)
1166 >>> dt1.utcoffset()
1167 datetime.timedelta(0, 3600)
1168 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1169 >>> dt2.dst()
1170 datetime.timedelta(0, 3600)
1171 >>> dt2.utcoffset()
1172 datetime.timedelta(0, 7200)
1173 >>> # Convert datetime to another time zone
1174 >>> dt3 = dt2.astimezone(GMT2())
1175 >>> dt3 # doctest: +ELLIPSIS
1176 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1177 >>> dt2 # doctest: +ELLIPSIS
1178 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1179 >>> dt2.utctimetuple() == dt3.utctimetuple()
1180 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001181
Christian Heimes895627f2007-12-08 17:28:33 +00001182
Georg Brandl116aa622007-08-15 14:28:22 +00001183
1184.. _datetime-time:
1185
1186:class:`time` Objects
1187---------------------
1188
1189A time object represents a (local) time of day, independent of any particular
1190day, and subject to adjustment via a :class:`tzinfo` object.
1191
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001192.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001193
1194 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001195 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001196 following ranges:
1197
1198 * ``0 <= hour < 24``
1199 * ``0 <= minute < 60``
1200 * ``0 <= second < 60``
1201 * ``0 <= microsecond < 1000000``.
1202
1203 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1204 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1205
1206Class attributes:
1207
1208
1209.. attribute:: time.min
1210
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001211 The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001212
1213
1214.. attribute:: time.max
1215
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001216 The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001217
1218
1219.. attribute:: time.resolution
1220
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001221 The smallest possible difference between non-equal :class:`.time` objects,
1222 ``timedelta(microseconds=1)``, although note that arithmetic on
1223 :class:`.time` objects is not supported.
Georg Brandl116aa622007-08-15 14:28:22 +00001224
Georg Brandl116aa622007-08-15 14:28:22 +00001225
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001226Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001227
1228.. attribute:: time.hour
1229
1230 In ``range(24)``.
1231
1232
1233.. attribute:: time.minute
1234
1235 In ``range(60)``.
1236
1237
1238.. attribute:: time.second
1239
1240 In ``range(60)``.
1241
1242
1243.. attribute:: time.microsecond
1244
1245 In ``range(1000000)``.
1246
1247
1248.. attribute:: time.tzinfo
1249
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001250 The object passed as the tzinfo argument to the :class:`.time` constructor, or
Georg Brandl116aa622007-08-15 14:28:22 +00001251 ``None`` if none was passed.
1252
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001253
Georg Brandl116aa622007-08-15 14:28:22 +00001254Supported operations:
1255
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001256* comparison of :class:`.time` to :class:`.time`, where *a* is considered less
Georg Brandl116aa622007-08-15 14:28:22 +00001257 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1258 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
Senthil Kumarana6bac952011-07-04 11:28:30 -07001259 the same :attr:`tzinfo` attribute, the common :attr:`tzinfo` attribute is
1260 ignored and the base times are compared. If both comparands are aware and
1261 have different :attr:`tzinfo` attributes, the comparands are first adjusted by
1262 subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
1263 to stop mixed-type comparisons from falling back to the default comparison by
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001264 object address, when a :class:`.time` object is compared to an object of a
Senthil Kumaran3aac1792011-07-04 11:43:51 -07001265 different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
Senthil Kumarana6bac952011-07-04 11:28:30 -07001266 ``!=``. The latter cases return :const:`False` or :const:`True`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +00001267
1268* hash, use as dict key
1269
1270* efficient pickling
1271
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001272* in Boolean contexts, a :class:`.time` object is considered to be true if and
Georg Brandl116aa622007-08-15 14:28:22 +00001273 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1274 ``0`` if that's ``None``), the result is non-zero.
1275
Georg Brandl116aa622007-08-15 14:28:22 +00001276
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001277Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001278
1279.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1280
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001281 Return a :class:`.time` with the same value, except for those attributes given
Senthil Kumarana6bac952011-07-04 11:28:30 -07001282 new values by whichever keyword arguments are specified. Note that
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001283 ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
1284 aware :class:`.time`, without conversion of the time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001285
1286
1287.. method:: time.isoformat()
1288
1289 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1290 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1291 6-character string is appended, giving the UTC offset in (signed) hours and
1292 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1293
1294
1295.. method:: time.__str__()
1296
1297 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1298
1299
1300.. method:: time.strftime(format)
1301
1302 Return a string representing the time, controlled by an explicit format string.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001303 See section :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001304
1305
1306.. method:: time.utcoffset()
1307
1308 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1309 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1310 return ``None`` or a :class:`timedelta` object representing a whole number of
1311 minutes with magnitude less than one day.
1312
1313
1314.. method:: time.dst()
1315
1316 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1317 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1318 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1319 with magnitude less than one day.
1320
1321
1322.. method:: time.tzname()
1323
1324 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1325 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1326 return ``None`` or a string object.
1327
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001328
Christian Heimesfe337bf2008-03-23 21:54:12 +00001329Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001330
Christian Heimes895627f2007-12-08 17:28:33 +00001331 >>> from datetime import time, tzinfo
1332 >>> class GMT1(tzinfo):
1333 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001334 ... return timedelta(hours=1)
1335 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001336 ... return timedelta(0)
1337 ... def tzname(self,dt):
1338 ... return "Europe/Prague"
1339 ...
1340 >>> t = time(12, 10, 30, tzinfo=GMT1())
1341 >>> t # doctest: +ELLIPSIS
1342 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1343 >>> gmt = GMT1()
1344 >>> t.isoformat()
1345 '12:10:30+01:00'
1346 >>> t.dst()
1347 datetime.timedelta(0)
1348 >>> t.tzname()
1349 'Europe/Prague'
1350 >>> t.strftime("%H:%M:%S %Z")
1351 '12:10:30 Europe/Prague'
1352
Georg Brandl116aa622007-08-15 14:28:22 +00001353
1354.. _datetime-tzinfo:
1355
1356:class:`tzinfo` Objects
1357-----------------------
1358
Brett Cannone1327f72009-01-29 04:10:21 +00001359:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001360instantiated directly. You need to derive a concrete subclass, and (at least)
1361supply implementations of the standard :class:`tzinfo` methods needed by the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001362:class:`.datetime` methods you use. The :mod:`datetime` module supplies
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001363a simple concrete subclass of :class:`tzinfo` :class:`timezone` which can reprsent
1364timezones with fixed offset from UTC such as UTC itself or North American EST and
1365EDT.
Georg Brandl116aa622007-08-15 14:28:22 +00001366
1367An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001368constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
Senthil Kumarana6bac952011-07-04 11:28:30 -07001369view their attributes as being in local time, and the :class:`tzinfo` object
Georg Brandl116aa622007-08-15 14:28:22 +00001370supports methods revealing offset of local time from UTC, the name of the time
1371zone, and DST offset, all relative to a date or time object passed to them.
1372
1373Special requirement for pickling: A :class:`tzinfo` subclass must have an
1374:meth:`__init__` method that can be called with no arguments, else it can be
1375pickled but possibly not unpickled again. This is a technical requirement that
1376may be relaxed in the future.
1377
1378A concrete subclass of :class:`tzinfo` may need to implement the following
1379methods. Exactly which methods are needed depends on the uses made of aware
1380:mod:`datetime` objects. If in doubt, simply implement all of them.
1381
1382
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001383.. method:: tzinfo.utcoffset(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001384
1385 Return offset of local time from UTC, in minutes east of UTC. If local time is
1386 west of UTC, this should be negative. Note that this is intended to be the
1387 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1388 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1389 the UTC offset isn't known, return ``None``. Else the value returned must be a
1390 :class:`timedelta` object specifying a whole number of minutes in the range
1391 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1392 than one day). Most implementations of :meth:`utcoffset` will probably look
1393 like one of these two::
1394
1395 return CONSTANT # fixed-offset class
1396 return CONSTANT + self.dst(dt) # daylight-aware class
1397
1398 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1399 ``None`` either.
1400
1401 The default implementation of :meth:`utcoffset` raises
1402 :exc:`NotImplementedError`.
1403
1404
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001405.. method:: tzinfo.dst(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001406
1407 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1408 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1409 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1410 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1411 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1412 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1413 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -07001414 attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
1415 should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
1416 DST changes when crossing time zones.
Georg Brandl116aa622007-08-15 14:28:22 +00001417
1418 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1419 daylight times must be consistent in this sense:
1420
1421 ``tz.utcoffset(dt) - tz.dst(dt)``
1422
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001423 must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo ==
Georg Brandl116aa622007-08-15 14:28:22 +00001424 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1425 zone's "standard offset", which should not depend on the date or the time, but
1426 only on geographic location. The implementation of :meth:`datetime.astimezone`
1427 relies on this, but cannot detect violations; it's the programmer's
1428 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1429 this, it may be able to override the default implementation of
1430 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1431
1432 Most implementations of :meth:`dst` will probably look like one of these two::
1433
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001434 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001435 # a fixed-offset class: doesn't account for DST
1436 return timedelta(0)
1437
1438 or ::
1439
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001440 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001441 # Code to set dston and dstoff to the time zone's DST
1442 # transition times based on the input dt.year, and expressed
1443 # in standard local time. Then
1444
1445 if dston <= dt.replace(tzinfo=None) < dstoff:
1446 return timedelta(hours=1)
1447 else:
1448 return timedelta(0)
1449
1450 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1451
1452
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001453.. method:: tzinfo.tzname(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001454
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001455 Return the time zone name corresponding to the :class:`.datetime` object *dt*, as
Georg Brandl116aa622007-08-15 14:28:22 +00001456 a string. Nothing about string names is defined by the :mod:`datetime` module,
1457 and there's no requirement that it mean anything in particular. For example,
1458 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1459 valid replies. Return ``None`` if a string name isn't known. Note that this is
1460 a method rather than a fixed string primarily because some :class:`tzinfo`
1461 subclasses will wish to return different names depending on the specific value
1462 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1463 daylight time.
1464
1465 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1466
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001467
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001468These methods are called by a :class:`.datetime` or :class:`.time` object, in
1469response to their methods of the same names. A :class:`.datetime` object passes
1470itself as the argument, and a :class:`.time` object passes ``None`` as the
Georg Brandl116aa622007-08-15 14:28:22 +00001471argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001472accept a *dt* argument of ``None``, or of class :class:`.datetime`.
Georg Brandl116aa622007-08-15 14:28:22 +00001473
1474When ``None`` is passed, it's up to the class designer to decide the best
1475response. For example, returning ``None`` is appropriate if the class wishes to
1476say that time objects don't participate in the :class:`tzinfo` protocols. It
1477may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1478there is no other convention for discovering the standard offset.
1479
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001480When a :class:`.datetime` object is passed in response to a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +00001481method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1482rely on this, unless user code calls :class:`tzinfo` methods directly. The
1483intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1484time, and not need worry about objects in other timezones.
1485
1486There is one more :class:`tzinfo` method that a subclass may wish to override:
1487
1488
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001489.. method:: tzinfo.fromutc(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001490
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001491 This is called from the default :class:`datetime.astimezone()`
1492 implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s
1493 date and time data are to be viewed as expressing a UTC time. The purpose
1494 of :meth:`fromutc` is to adjust the date and time data, returning an
Senthil Kumarana6bac952011-07-04 11:28:30 -07001495 equivalent datetime in *self*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00001496
1497 Most :class:`tzinfo` subclasses should be able to inherit the default
1498 :meth:`fromutc` implementation without problems. It's strong enough to handle
1499 fixed-offset time zones, and time zones accounting for both standard and
1500 daylight time, and the latter even if the DST transition times differ in
1501 different years. An example of a time zone the default :meth:`fromutc`
1502 implementation may not handle correctly in all cases is one where the standard
1503 offset (from UTC) depends on the specific date and time passed, which can happen
1504 for political reasons. The default implementations of :meth:`astimezone` and
1505 :meth:`fromutc` may not produce the result you want if the result is one of the
1506 hours straddling the moment the standard offset changes.
1507
1508 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1509 like::
1510
1511 def fromutc(self, dt):
1512 # raise ValueError error if dt.tzinfo is not self
1513 dtoff = dt.utcoffset()
1514 dtdst = dt.dst()
1515 # raise ValueError if dtoff is None or dtdst is None
1516 delta = dtoff - dtdst # this is self's standard offset
1517 if delta:
1518 dt += delta # convert to standard local time
1519 dtdst = dt.dst()
1520 # raise ValueError if dtdst is None
1521 if dtdst:
1522 return dt + dtdst
1523 else:
1524 return dt
1525
1526Example :class:`tzinfo` classes:
1527
1528.. literalinclude:: ../includes/tzinfo-examples.py
1529
Georg Brandl116aa622007-08-15 14:28:22 +00001530Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1531subclass accounting for both standard and daylight time, at the DST transition
1532points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00001533minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
15341:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001535
1536 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1537 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1538 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1539
1540 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1541
1542 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1543
1544When DST starts (the "start" line), the local wall clock leaps from 1:59 to
15453:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1546``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1547begins. In order for :meth:`astimezone` to make this guarantee, the
1548:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1549Eastern) to be in daylight time.
1550
1551When DST ends (the "end" line), there's a potentially worse problem: there's an
1552hour that can't be spelled unambiguously in local wall time: the last hour of
1553daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1554daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1555to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1556:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1557hours into the same local hour then. In the Eastern example, UTC times of the
1558form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1559:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1560consider times in the "repeated hour" to be in standard time. This is easily
1561arranged, as in the example, by expressing DST switch times in the time zone's
1562standard local time.
1563
1564Applications that can't bear such ambiguities should avoid using hybrid
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001565:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`,
1566or any other fixed-offset :class:`tzinfo` subclass (such as a class representing
1567only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
1568
Sandro Tosid11d0d62012-04-24 19:46:06 +02001569.. seealso::
1570
1571 `pytz <http://pypi.python.org/pypi/pytz/>`_
Sandro Tosi100b8892012-04-28 11:19:37 +02001572 The standard library has no :class:`tzinfo` instances except for UTC, but
1573 there exists a third-party library which brings the *IANA timezone
1574 database* (also known as the Olson database) to Python: *pytz*.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001575
Sandro Tosi100b8892012-04-28 11:19:37 +02001576 *pytz* contains up-to-date information and its usage is recommended.
1577
1578 `IANA timezone database <http://www.iana.org/time-zones>`_
1579 The Time Zone Database (often called tz or zoneinfo) contains code and
1580 data that represent the history of local time for many representative
1581 locations around the globe. It is updated periodically to reflect changes
1582 made by political bodies to time zone boundaries, UTC offsets, and
1583 daylight-saving rules.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001584
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001585
1586.. _datetime-timezone:
1587
1588:class:`timezone` Objects
1589--------------------------
1590
1591A :class:`timezone` object represents a timezone that is defined by a
1592fixed offset from UTC. Note that objects of this class cannot be used
1593to represent timezone information in the locations where different
1594offsets are used in different days of the year or where historical
1595changes have been made to civil time.
1596
1597
1598.. class:: timezone(offset[, name])
1599
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001600 The *offset* argument must be specified as a :class:`timedelta`
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001601 object representing the difference between the local time and UTC. It must
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001602 be strictly between ``-timedelta(hours=24)`` and
1603 ``timedelta(hours=24)`` and represent a whole number of minutes,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001604 otherwise :exc:`ValueError` is raised.
1605
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001606 The *name* argument is optional. If specified it must be a string that
1607 is used as the value returned by the ``tzname(dt)`` method. Otherwise,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001608 ``tzname(dt)`` returns a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001609 *offset*, HH and MM are two digits of ``offset.hours`` and
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001610 ``offset.minutes`` respectively.
1611
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001612.. method:: timezone.utcoffset(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001613
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001614 Return the fixed value specified when the :class:`timezone` instance is
1615 constructed. The *dt* argument is ignored. The return value is a
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001616 :class:`timedelta` instance equal to the difference between the
1617 local time and UTC.
1618
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001619.. method:: timezone.tzname(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001620
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001621 Return the fixed value specified when the :class:`timezone` instance is
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001622 constructed or a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001623 *offset*, HH and MM are two digits of ``offset.hours`` and
1624 ``offset.minutes`` respectively.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001625
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001626.. method:: timezone.dst(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001627
1628 Always returns ``None``.
1629
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001630.. method:: timezone.fromutc(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001631
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001632 Return ``dt + offset``. The *dt* argument must be an aware
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001633 :class:`.datetime` instance, with ``tzinfo`` set to ``self``.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001634
1635Class attributes:
1636
1637.. attribute:: timezone.utc
1638
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001639 The UTC timezone, ``timezone(timedelta(0))``.
Georg Brandl48310cd2009-01-03 21:18:54 +00001640
Georg Brandl116aa622007-08-15 14:28:22 +00001641
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001642.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00001643
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001644:meth:`strftime` and :meth:`strptime` Behavior
1645----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001646
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001647:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
Georg Brandl116aa622007-08-15 14:28:22 +00001648``strftime(format)`` method, to create a string representing the time under the
1649control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1650acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1651although not all objects support a :meth:`timetuple` method.
1652
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001653Conversely, the :meth:`datetime.strptime` class method creates a
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001654:class:`.datetime` object from a string representing a date and time and a
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001655corresponding format string. ``datetime.strptime(date_string, format)`` is
1656equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1657
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001658For :class:`.time` objects, the format codes for year, month, and day should not
Georg Brandl116aa622007-08-15 14:28:22 +00001659be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001660is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00001661
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001662For :class:`date` objects, the format codes for hours, minutes, seconds, and
1663microseconds should not be used, as :class:`date` objects have no such
1664values. If they're used anyway, ``0`` is substituted for them.
1665
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001666For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1667strings.
1668
1669For an aware object:
1670
1671``%z``
1672 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1673 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1674 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1675 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1676 replaced with the string ``'-0330'``.
1677
1678``%Z``
1679 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1680 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl116aa622007-08-15 14:28:22 +00001681
Georg Brandl116aa622007-08-15 14:28:22 +00001682The full set of format codes supported varies across platforms, because Python
1683calls the platform C library's :func:`strftime` function, and platform
Georg Brandl48310cd2009-01-03 21:18:54 +00001684variations are common.
Christian Heimes895627f2007-12-08 17:28:33 +00001685
1686The following is a list of all the format codes that the C standard (1989
1687version) requires, and these work on all platforms with a standard C
1688implementation. Note that the 1999 version of the C standard added additional
1689format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001690
Christian Heimes895627f2007-12-08 17:28:33 +00001691+-----------+--------------------------------+-------+
1692| Directive | Meaning | Notes |
1693+===========+================================+=======+
1694| ``%a`` | Locale's abbreviated weekday | |
1695| | name. | |
1696+-----------+--------------------------------+-------+
1697| ``%A`` | Locale's full weekday name. | |
1698+-----------+--------------------------------+-------+
1699| ``%b`` | Locale's abbreviated month | |
1700| | name. | |
1701+-----------+--------------------------------+-------+
1702| ``%B`` | Locale's full month name. | |
1703+-----------+--------------------------------+-------+
1704| ``%c`` | Locale's appropriate date and | |
1705| | time representation. | |
1706+-----------+--------------------------------+-------+
1707| ``%d`` | Day of the month as a decimal | |
1708| | number [01,31]. | |
1709+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001710| ``%f`` | Microsecond as a decimal | \(1) |
1711| | number [0,999999], zero-padded | |
1712| | on the left | |
1713+-----------+--------------------------------+-------+
Christian Heimes895627f2007-12-08 17:28:33 +00001714| ``%H`` | Hour (24-hour clock) as a | |
1715| | decimal number [00,23]. | |
1716+-----------+--------------------------------+-------+
1717| ``%I`` | Hour (12-hour clock) as a | |
1718| | decimal number [01,12]. | |
1719+-----------+--------------------------------+-------+
1720| ``%j`` | Day of the year as a decimal | |
1721| | number [001,366]. | |
1722+-----------+--------------------------------+-------+
1723| ``%m`` | Month as a decimal number | |
1724| | [01,12]. | |
1725+-----------+--------------------------------+-------+
1726| ``%M`` | Minute as a decimal number | |
1727| | [00,59]. | |
1728+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001729| ``%p`` | Locale's equivalent of either | \(2) |
Christian Heimes895627f2007-12-08 17:28:33 +00001730| | AM or PM. | |
1731+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001732| ``%S`` | Second as a decimal number | \(3) |
Alexander Belopolsky9971e002011-01-10 22:56:14 +00001733| | [00,59]. | |
Christian Heimes895627f2007-12-08 17:28:33 +00001734+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001735| ``%U`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001736| | (Sunday as the first day of | |
1737| | the week) as a decimal number | |
1738| | [00,53]. All days in a new | |
1739| | year preceding the first | |
1740| | Sunday are considered to be in | |
1741| | week 0. | |
1742+-----------+--------------------------------+-------+
1743| ``%w`` | Weekday as a decimal number | |
1744| | [0(Sunday),6]. | |
1745+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001746| ``%W`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001747| | (Monday as the first day of | |
1748| | the week) as a decimal number | |
1749| | [00,53]. All days in a new | |
1750| | year preceding the first | |
1751| | Monday are considered to be in | |
1752| | week 0. | |
1753+-----------+--------------------------------+-------+
1754| ``%x`` | Locale's appropriate date | |
1755| | representation. | |
1756+-----------+--------------------------------+-------+
1757| ``%X`` | Locale's appropriate time | |
1758| | representation. | |
1759+-----------+--------------------------------+-------+
1760| ``%y`` | Year without century as a | |
1761| | decimal number [00,99]. | |
1762+-----------+--------------------------------+-------+
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001763| ``%Y`` | Year with century as a decimal | \(5) |
1764| | number [0001,9999] (strptime), | |
1765| | [1000,9999] (strftime). | |
Christian Heimes895627f2007-12-08 17:28:33 +00001766+-----------+--------------------------------+-------+
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001767| ``%z`` | UTC offset in the form +HHMM | \(6) |
Christian Heimes895627f2007-12-08 17:28:33 +00001768| | or -HHMM (empty string if the | |
1769| | the object is naive). | |
1770+-----------+--------------------------------+-------+
1771| ``%Z`` | Time zone name (empty string | |
1772| | if the object is naive). | |
1773+-----------+--------------------------------+-------+
1774| ``%%`` | A literal ``'%'`` character. | |
1775+-----------+--------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001776
Christian Heimes895627f2007-12-08 17:28:33 +00001777Notes:
1778
1779(1)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001780 When used with the :meth:`strptime` method, the ``%f`` directive
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001781 accepts from one to six digits and zero pads on the right. ``%f`` is
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001782 an extension to the set of format characters in the C standard (but
1783 implemented separately in datetime objects, and therefore always
1784 available).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001785
1786(2)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001787 When used with the :meth:`strptime` method, the ``%p`` directive only affects
Christian Heimes895627f2007-12-08 17:28:33 +00001788 the output hour field if the ``%I`` directive is used to parse the hour.
1789
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001790(3)
Alexander Belopolsky9971e002011-01-10 22:56:14 +00001791 Unlike :mod:`time` module, :mod:`datetime` module does not support
1792 leap seconds.
Christian Heimes895627f2007-12-08 17:28:33 +00001793
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001794(4)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001795 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in
Christian Heimes895627f2007-12-08 17:28:33 +00001796 calculations when the day of the week and the year are specified.
1797
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001798(5)
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001799 For technical reasons, :meth:`strftime` method does not support
Alexander Belopolsky5fc850b2011-01-10 23:31:51 +00001800 dates before year 1000: ``t.strftime(format)`` will raise a
1801 :exc:`ValueError` when ``t.year < 1000`` even if ``format`` does
1802 not contain ``%Y`` directive. The :meth:`strptime` method can
1803 parse years in the full [1, 9999] range, but years < 1000 must be
1804 zero-filled to 4-digit width.
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001805
1806 .. versionchanged:: 3.2
1807 In previous versions, :meth:`strftime` method was restricted to
1808 years >= 1900.
1809
1810(6)
Christian Heimes895627f2007-12-08 17:28:33 +00001811 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1812 ``%z`` is replaced with the string ``'-0330'``.
Alexander Belopolskyca94f552010-06-17 18:30:34 +00001813
Georg Brandl67b21b72010-08-17 15:07:14 +00001814.. versionchanged:: 3.2
1815 When the ``%z`` directive is provided to the :meth:`strptime` method, an
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001816 aware :class:`.datetime` object will be produced. The ``tzinfo`` of the
Georg Brandl67b21b72010-08-17 15:07:14 +00001817 result will be set to a :class:`timezone` instance.
R David Murray9075d8b2012-05-14 22:14:46 -04001818
1819.. rubric:: Footnotes
1820
1821.. [#] If, that is, we ignore the effects of Relativity