blob: 88fa01c0d418f766eaaa484162eec3d3ddf77bfd [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):
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001130 ... def utcoffset(self, dt):
1131 ... return timedelta(hours=1) + self.dst(dt)
1132 ... def dst(self, dt):
1133 ... # DST starts last Sunday in March
Christian Heimes895627f2007-12-08 17:28:33 +00001134 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1135 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001136 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001137 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
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):
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001146 ... def utcoffset(self, dt):
1147 ... return timedelta(hours=2) + self.dst(dt)
1148 ... def dst(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001149 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001150 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001151 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001152 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001153 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001154 ... return timedelta(hours=1)
Christian Heimes895627f2007-12-08 17:28:33 +00001155 ... else:
1156 ... return timedelta(0)
1157 ... def tzname(self,dt):
1158 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001159 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001160 >>> gmt1 = GMT1()
1161 >>> # Daylight Saving Time
1162 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1163 >>> dt1.dst()
1164 datetime.timedelta(0)
1165 >>> dt1.utcoffset()
1166 datetime.timedelta(0, 3600)
1167 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1168 >>> dt2.dst()
1169 datetime.timedelta(0, 3600)
1170 >>> dt2.utcoffset()
1171 datetime.timedelta(0, 7200)
1172 >>> # Convert datetime to another time zone
1173 >>> dt3 = dt2.astimezone(GMT2())
1174 >>> dt3 # doctest: +ELLIPSIS
1175 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1176 >>> dt2 # doctest: +ELLIPSIS
1177 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1178 >>> dt2.utctimetuple() == dt3.utctimetuple()
1179 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001180
Christian Heimes895627f2007-12-08 17:28:33 +00001181
Georg Brandl116aa622007-08-15 14:28:22 +00001182
1183.. _datetime-time:
1184
1185:class:`time` Objects
1186---------------------
1187
1188A time object represents a (local) time of day, independent of any particular
1189day, and subject to adjustment via a :class:`tzinfo` object.
1190
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001191.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001192
1193 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001194 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001195 following ranges:
1196
1197 * ``0 <= hour < 24``
1198 * ``0 <= minute < 60``
1199 * ``0 <= second < 60``
1200 * ``0 <= microsecond < 1000000``.
1201
1202 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1203 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1204
1205Class attributes:
1206
1207
1208.. attribute:: time.min
1209
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001210 The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001211
1212
1213.. attribute:: time.max
1214
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001215 The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001216
1217
1218.. attribute:: time.resolution
1219
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001220 The smallest possible difference between non-equal :class:`.time` objects,
1221 ``timedelta(microseconds=1)``, although note that arithmetic on
1222 :class:`.time` objects is not supported.
Georg Brandl116aa622007-08-15 14:28:22 +00001223
Georg Brandl116aa622007-08-15 14:28:22 +00001224
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001225Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001226
1227.. attribute:: time.hour
1228
1229 In ``range(24)``.
1230
1231
1232.. attribute:: time.minute
1233
1234 In ``range(60)``.
1235
1236
1237.. attribute:: time.second
1238
1239 In ``range(60)``.
1240
1241
1242.. attribute:: time.microsecond
1243
1244 In ``range(1000000)``.
1245
1246
1247.. attribute:: time.tzinfo
1248
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001249 The object passed as the tzinfo argument to the :class:`.time` constructor, or
Georg Brandl116aa622007-08-15 14:28:22 +00001250 ``None`` if none was passed.
1251
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001252
Georg Brandl116aa622007-08-15 14:28:22 +00001253Supported operations:
1254
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001255* comparison of :class:`.time` to :class:`.time`, where *a* is considered less
Georg Brandl116aa622007-08-15 14:28:22 +00001256 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1257 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
Senthil Kumarana6bac952011-07-04 11:28:30 -07001258 the same :attr:`tzinfo` attribute, the common :attr:`tzinfo` attribute is
1259 ignored and the base times are compared. If both comparands are aware and
1260 have different :attr:`tzinfo` attributes, the comparands are first adjusted by
1261 subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
1262 to stop mixed-type comparisons from falling back to the default comparison by
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001263 object address, when a :class:`.time` object is compared to an object of a
Senthil Kumaran3aac1792011-07-04 11:43:51 -07001264 different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
Senthil Kumarana6bac952011-07-04 11:28:30 -07001265 ``!=``. The latter cases return :const:`False` or :const:`True`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +00001266
1267* hash, use as dict key
1268
1269* efficient pickling
1270
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001271* in Boolean contexts, a :class:`.time` object is considered to be true if and
Georg Brandl116aa622007-08-15 14:28:22 +00001272 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1273 ``0`` if that's ``None``), the result is non-zero.
1274
Georg Brandl116aa622007-08-15 14:28:22 +00001275
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001276Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001277
1278.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1279
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001280 Return a :class:`.time` with the same value, except for those attributes given
Senthil Kumarana6bac952011-07-04 11:28:30 -07001281 new values by whichever keyword arguments are specified. Note that
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001282 ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
1283 aware :class:`.time`, without conversion of the time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001284
1285
1286.. method:: time.isoformat()
1287
1288 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1289 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1290 6-character string is appended, giving the UTC offset in (signed) hours and
1291 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1292
1293
1294.. method:: time.__str__()
1295
1296 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1297
1298
1299.. method:: time.strftime(format)
1300
1301 Return a string representing the time, controlled by an explicit format string.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001302 See section :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001303
1304
1305.. method:: time.utcoffset()
1306
1307 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1308 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1309 return ``None`` or a :class:`timedelta` object representing a whole number of
1310 minutes with magnitude less than one day.
1311
1312
1313.. method:: time.dst()
1314
1315 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1316 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1317 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1318 with magnitude less than one day.
1319
1320
1321.. method:: time.tzname()
1322
1323 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1324 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1325 return ``None`` or a string object.
1326
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001327
Christian Heimesfe337bf2008-03-23 21:54:12 +00001328Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001329
Christian Heimes895627f2007-12-08 17:28:33 +00001330 >>> from datetime import time, tzinfo
1331 >>> class GMT1(tzinfo):
1332 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001333 ... return timedelta(hours=1)
1334 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001335 ... return timedelta(0)
1336 ... def tzname(self,dt):
1337 ... return "Europe/Prague"
1338 ...
1339 >>> t = time(12, 10, 30, tzinfo=GMT1())
1340 >>> t # doctest: +ELLIPSIS
1341 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1342 >>> gmt = GMT1()
1343 >>> t.isoformat()
1344 '12:10:30+01:00'
1345 >>> t.dst()
1346 datetime.timedelta(0)
1347 >>> t.tzname()
1348 'Europe/Prague'
1349 >>> t.strftime("%H:%M:%S %Z")
1350 '12:10:30 Europe/Prague'
1351
Georg Brandl116aa622007-08-15 14:28:22 +00001352
1353.. _datetime-tzinfo:
1354
1355:class:`tzinfo` Objects
1356-----------------------
1357
Brett Cannone1327f72009-01-29 04:10:21 +00001358:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001359instantiated directly. You need to derive a concrete subclass, and (at least)
1360supply implementations of the standard :class:`tzinfo` methods needed by the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001361:class:`.datetime` methods you use. The :mod:`datetime` module supplies
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001362a simple concrete subclass of :class:`tzinfo` :class:`timezone` which can reprsent
1363timezones with fixed offset from UTC such as UTC itself or North American EST and
1364EDT.
Georg Brandl116aa622007-08-15 14:28:22 +00001365
1366An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001367constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
Senthil Kumarana6bac952011-07-04 11:28:30 -07001368view their attributes as being in local time, and the :class:`tzinfo` object
Georg Brandl116aa622007-08-15 14:28:22 +00001369supports methods revealing offset of local time from UTC, the name of the time
1370zone, and DST offset, all relative to a date or time object passed to them.
1371
1372Special requirement for pickling: A :class:`tzinfo` subclass must have an
1373:meth:`__init__` method that can be called with no arguments, else it can be
1374pickled but possibly not unpickled again. This is a technical requirement that
1375may be relaxed in the future.
1376
1377A concrete subclass of :class:`tzinfo` may need to implement the following
1378methods. Exactly which methods are needed depends on the uses made of aware
1379:mod:`datetime` objects. If in doubt, simply implement all of them.
1380
1381
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001382.. method:: tzinfo.utcoffset(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001383
1384 Return offset of local time from UTC, in minutes east of UTC. If local time is
1385 west of UTC, this should be negative. Note that this is intended to be the
1386 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1387 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1388 the UTC offset isn't known, return ``None``. Else the value returned must be a
1389 :class:`timedelta` object specifying a whole number of minutes in the range
1390 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1391 than one day). Most implementations of :meth:`utcoffset` will probably look
1392 like one of these two::
1393
1394 return CONSTANT # fixed-offset class
1395 return CONSTANT + self.dst(dt) # daylight-aware class
1396
1397 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1398 ``None`` either.
1399
1400 The default implementation of :meth:`utcoffset` raises
1401 :exc:`NotImplementedError`.
1402
1403
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001404.. method:: tzinfo.dst(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001405
1406 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1407 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1408 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1409 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1410 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1411 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1412 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -07001413 attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
1414 should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
1415 DST changes when crossing time zones.
Georg Brandl116aa622007-08-15 14:28:22 +00001416
1417 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1418 daylight times must be consistent in this sense:
1419
1420 ``tz.utcoffset(dt) - tz.dst(dt)``
1421
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001422 must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo ==
Georg Brandl116aa622007-08-15 14:28:22 +00001423 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1424 zone's "standard offset", which should not depend on the date or the time, but
1425 only on geographic location. The implementation of :meth:`datetime.astimezone`
1426 relies on this, but cannot detect violations; it's the programmer's
1427 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1428 this, it may be able to override the default implementation of
1429 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1430
1431 Most implementations of :meth:`dst` will probably look like one of these two::
1432
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001433 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001434 # a fixed-offset class: doesn't account for DST
1435 return timedelta(0)
1436
1437 or ::
1438
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001439 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001440 # Code to set dston and dstoff to the time zone's DST
1441 # transition times based on the input dt.year, and expressed
1442 # in standard local time. Then
1443
1444 if dston <= dt.replace(tzinfo=None) < dstoff:
1445 return timedelta(hours=1)
1446 else:
1447 return timedelta(0)
1448
1449 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1450
1451
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001452.. method:: tzinfo.tzname(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001453
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001454 Return the time zone name corresponding to the :class:`.datetime` object *dt*, as
Georg Brandl116aa622007-08-15 14:28:22 +00001455 a string. Nothing about string names is defined by the :mod:`datetime` module,
1456 and there's no requirement that it mean anything in particular. For example,
1457 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1458 valid replies. Return ``None`` if a string name isn't known. Note that this is
1459 a method rather than a fixed string primarily because some :class:`tzinfo`
1460 subclasses will wish to return different names depending on the specific value
1461 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1462 daylight time.
1463
1464 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1465
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001466
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001467These methods are called by a :class:`.datetime` or :class:`.time` object, in
1468response to their methods of the same names. A :class:`.datetime` object passes
1469itself as the argument, and a :class:`.time` object passes ``None`` as the
Georg Brandl116aa622007-08-15 14:28:22 +00001470argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001471accept a *dt* argument of ``None``, or of class :class:`.datetime`.
Georg Brandl116aa622007-08-15 14:28:22 +00001472
1473When ``None`` is passed, it's up to the class designer to decide the best
1474response. For example, returning ``None`` is appropriate if the class wishes to
1475say that time objects don't participate in the :class:`tzinfo` protocols. It
1476may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1477there is no other convention for discovering the standard offset.
1478
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001479When a :class:`.datetime` object is passed in response to a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +00001480method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1481rely on this, unless user code calls :class:`tzinfo` methods directly. The
1482intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1483time, and not need worry about objects in other timezones.
1484
1485There is one more :class:`tzinfo` method that a subclass may wish to override:
1486
1487
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001488.. method:: tzinfo.fromutc(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001489
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001490 This is called from the default :class:`datetime.astimezone()`
1491 implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s
1492 date and time data are to be viewed as expressing a UTC time. The purpose
1493 of :meth:`fromutc` is to adjust the date and time data, returning an
Senthil Kumarana6bac952011-07-04 11:28:30 -07001494 equivalent datetime in *self*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00001495
1496 Most :class:`tzinfo` subclasses should be able to inherit the default
1497 :meth:`fromutc` implementation without problems. It's strong enough to handle
1498 fixed-offset time zones, and time zones accounting for both standard and
1499 daylight time, and the latter even if the DST transition times differ in
1500 different years. An example of a time zone the default :meth:`fromutc`
1501 implementation may not handle correctly in all cases is one where the standard
1502 offset (from UTC) depends on the specific date and time passed, which can happen
1503 for political reasons. The default implementations of :meth:`astimezone` and
1504 :meth:`fromutc` may not produce the result you want if the result is one of the
1505 hours straddling the moment the standard offset changes.
1506
1507 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1508 like::
1509
1510 def fromutc(self, dt):
1511 # raise ValueError error if dt.tzinfo is not self
1512 dtoff = dt.utcoffset()
1513 dtdst = dt.dst()
1514 # raise ValueError if dtoff is None or dtdst is None
1515 delta = dtoff - dtdst # this is self's standard offset
1516 if delta:
1517 dt += delta # convert to standard local time
1518 dtdst = dt.dst()
1519 # raise ValueError if dtdst is None
1520 if dtdst:
1521 return dt + dtdst
1522 else:
1523 return dt
1524
1525Example :class:`tzinfo` classes:
1526
1527.. literalinclude:: ../includes/tzinfo-examples.py
1528
Georg Brandl116aa622007-08-15 14:28:22 +00001529Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1530subclass accounting for both standard and daylight time, at the DST transition
1531points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00001532minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
15331:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001534
1535 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1536 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1537 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1538
1539 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1540
1541 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1542
1543When DST starts (the "start" line), the local wall clock leaps from 1:59 to
15443:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1545``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1546begins. In order for :meth:`astimezone` to make this guarantee, the
Senthil Kumaran72a80e82012-06-26 20:00:15 +08001547:meth:`tzinfo.dst` method must consider times in the "missing hour" (2:MM for
Georg Brandl116aa622007-08-15 14:28:22 +00001548Eastern) to be in daylight time.
1549
1550When DST ends (the "end" line), there's a potentially worse problem: there's an
1551hour that can't be spelled unambiguously in local wall time: the last hour of
1552daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1553daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1554to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1555:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1556hours into the same local hour then. In the Eastern example, UTC times of the
1557form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1558:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1559consider times in the "repeated hour" to be in standard time. This is easily
1560arranged, as in the example, by expressing DST switch times in the time zone's
1561standard local time.
1562
1563Applications that can't bear such ambiguities should avoid using hybrid
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001564:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`,
1565or any other fixed-offset :class:`tzinfo` subclass (such as a class representing
1566only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
1567
Sandro Tosid11d0d62012-04-24 19:46:06 +02001568.. seealso::
1569
1570 `pytz <http://pypi.python.org/pypi/pytz/>`_
Sandro Tosi100b8892012-04-28 11:19:37 +02001571 The standard library has no :class:`tzinfo` instances except for UTC, but
1572 there exists a third-party library which brings the *IANA timezone
1573 database* (also known as the Olson database) to Python: *pytz*.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001574
Sandro Tosi100b8892012-04-28 11:19:37 +02001575 *pytz* contains up-to-date information and its usage is recommended.
1576
1577 `IANA timezone database <http://www.iana.org/time-zones>`_
1578 The Time Zone Database (often called tz or zoneinfo) contains code and
1579 data that represent the history of local time for many representative
1580 locations around the globe. It is updated periodically to reflect changes
1581 made by political bodies to time zone boundaries, UTC offsets, and
1582 daylight-saving rules.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001583
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001584
1585.. _datetime-timezone:
1586
1587:class:`timezone` Objects
1588--------------------------
1589
1590A :class:`timezone` object represents a timezone that is defined by a
1591fixed offset from UTC. Note that objects of this class cannot be used
1592to represent timezone information in the locations where different
1593offsets are used in different days of the year or where historical
1594changes have been made to civil time.
1595
1596
1597.. class:: timezone(offset[, name])
1598
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001599 The *offset* argument must be specified as a :class:`timedelta`
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001600 object representing the difference between the local time and UTC. It must
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001601 be strictly between ``-timedelta(hours=24)`` and
1602 ``timedelta(hours=24)`` and represent a whole number of minutes,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001603 otherwise :exc:`ValueError` is raised.
1604
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001605 The *name* argument is optional. If specified it must be a string that
1606 is used as the value returned by the ``tzname(dt)`` method. Otherwise,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001607 ``tzname(dt)`` returns a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001608 *offset*, HH and MM are two digits of ``offset.hours`` and
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001609 ``offset.minutes`` respectively.
1610
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001611.. method:: timezone.utcoffset(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001612
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001613 Return the fixed value specified when the :class:`timezone` instance is
1614 constructed. The *dt* argument is ignored. The return value is a
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001615 :class:`timedelta` instance equal to the difference between the
1616 local time and UTC.
1617
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001618.. method:: timezone.tzname(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001619
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001620 Return the fixed value specified when the :class:`timezone` instance is
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001621 constructed or a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001622 *offset*, HH and MM are two digits of ``offset.hours`` and
1623 ``offset.minutes`` respectively.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001624
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001625.. method:: timezone.dst(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001626
1627 Always returns ``None``.
1628
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001629.. method:: timezone.fromutc(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001630
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001631 Return ``dt + offset``. The *dt* argument must be an aware
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001632 :class:`.datetime` instance, with ``tzinfo`` set to ``self``.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001633
1634Class attributes:
1635
1636.. attribute:: timezone.utc
1637
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001638 The UTC timezone, ``timezone(timedelta(0))``.
Georg Brandl48310cd2009-01-03 21:18:54 +00001639
Georg Brandl116aa622007-08-15 14:28:22 +00001640
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001641.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00001642
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001643:meth:`strftime` and :meth:`strptime` Behavior
1644----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001645
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001646:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
Georg Brandl116aa622007-08-15 14:28:22 +00001647``strftime(format)`` method, to create a string representing the time under the
1648control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1649acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1650although not all objects support a :meth:`timetuple` method.
1651
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001652Conversely, the :meth:`datetime.strptime` class method creates a
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001653:class:`.datetime` object from a string representing a date and time and a
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001654corresponding format string. ``datetime.strptime(date_string, format)`` is
1655equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1656
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001657For :class:`.time` objects, the format codes for year, month, and day should not
Georg Brandl116aa622007-08-15 14:28:22 +00001658be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001659is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00001660
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001661For :class:`date` objects, the format codes for hours, minutes, seconds, and
1662microseconds should not be used, as :class:`date` objects have no such
1663values. If they're used anyway, ``0`` is substituted for them.
1664
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001665For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1666strings.
1667
1668For an aware object:
1669
1670``%z``
1671 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1672 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1673 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1674 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1675 replaced with the string ``'-0330'``.
1676
1677``%Z``
1678 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1679 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl116aa622007-08-15 14:28:22 +00001680
Georg Brandl116aa622007-08-15 14:28:22 +00001681The full set of format codes supported varies across platforms, because Python
1682calls the platform C library's :func:`strftime` function, and platform
Georg Brandl48310cd2009-01-03 21:18:54 +00001683variations are common.
Christian Heimes895627f2007-12-08 17:28:33 +00001684
1685The following is a list of all the format codes that the C standard (1989
1686version) requires, and these work on all platforms with a standard C
1687implementation. Note that the 1999 version of the C standard added additional
1688format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001689
Christian Heimes895627f2007-12-08 17:28:33 +00001690+-----------+--------------------------------+-------+
1691| Directive | Meaning | Notes |
1692+===========+================================+=======+
1693| ``%a`` | Locale's abbreviated weekday | |
1694| | name. | |
1695+-----------+--------------------------------+-------+
1696| ``%A`` | Locale's full weekday name. | |
1697+-----------+--------------------------------+-------+
1698| ``%b`` | Locale's abbreviated month | |
1699| | name. | |
1700+-----------+--------------------------------+-------+
1701| ``%B`` | Locale's full month name. | |
1702+-----------+--------------------------------+-------+
1703| ``%c`` | Locale's appropriate date and | |
1704| | time representation. | |
1705+-----------+--------------------------------+-------+
1706| ``%d`` | Day of the month as a decimal | |
1707| | number [01,31]. | |
1708+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001709| ``%f`` | Microsecond as a decimal | \(1) |
1710| | number [0,999999], zero-padded | |
1711| | on the left | |
1712+-----------+--------------------------------+-------+
Christian Heimes895627f2007-12-08 17:28:33 +00001713| ``%H`` | Hour (24-hour clock) as a | |
1714| | decimal number [00,23]. | |
1715+-----------+--------------------------------+-------+
1716| ``%I`` | Hour (12-hour clock) as a | |
1717| | decimal number [01,12]. | |
1718+-----------+--------------------------------+-------+
1719| ``%j`` | Day of the year as a decimal | |
1720| | number [001,366]. | |
1721+-----------+--------------------------------+-------+
1722| ``%m`` | Month as a decimal number | |
1723| | [01,12]. | |
1724+-----------+--------------------------------+-------+
1725| ``%M`` | Minute as a decimal number | |
1726| | [00,59]. | |
1727+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001728| ``%p`` | Locale's equivalent of either | \(2) |
Christian Heimes895627f2007-12-08 17:28:33 +00001729| | AM or PM. | |
1730+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001731| ``%S`` | Second as a decimal number | \(3) |
Alexander Belopolsky9971e002011-01-10 22:56:14 +00001732| | [00,59]. | |
Christian Heimes895627f2007-12-08 17:28:33 +00001733+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001734| ``%U`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001735| | (Sunday as the first day of | |
1736| | the week) as a decimal number | |
1737| | [00,53]. All days in a new | |
1738| | year preceding the first | |
1739| | Sunday are considered to be in | |
1740| | week 0. | |
1741+-----------+--------------------------------+-------+
1742| ``%w`` | Weekday as a decimal number | |
1743| | [0(Sunday),6]. | |
1744+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001745| ``%W`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001746| | (Monday as the first day of | |
1747| | the week) as a decimal number | |
1748| | [00,53]. All days in a new | |
1749| | year preceding the first | |
1750| | Monday are considered to be in | |
1751| | week 0. | |
1752+-----------+--------------------------------+-------+
1753| ``%x`` | Locale's appropriate date | |
1754| | representation. | |
1755+-----------+--------------------------------+-------+
1756| ``%X`` | Locale's appropriate time | |
1757| | representation. | |
1758+-----------+--------------------------------+-------+
1759| ``%y`` | Year without century as a | |
1760| | decimal number [00,99]. | |
1761+-----------+--------------------------------+-------+
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001762| ``%Y`` | Year with century as a decimal | \(5) |
1763| | number [0001,9999] (strptime), | |
1764| | [1000,9999] (strftime). | |
Christian Heimes895627f2007-12-08 17:28:33 +00001765+-----------+--------------------------------+-------+
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001766| ``%z`` | UTC offset in the form +HHMM | \(6) |
Christian Heimes895627f2007-12-08 17:28:33 +00001767| | or -HHMM (empty string if the | |
1768| | the object is naive). | |
1769+-----------+--------------------------------+-------+
1770| ``%Z`` | Time zone name (empty string | |
1771| | if the object is naive). | |
1772+-----------+--------------------------------+-------+
1773| ``%%`` | A literal ``'%'`` character. | |
1774+-----------+--------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001775
Christian Heimes895627f2007-12-08 17:28:33 +00001776Notes:
1777
1778(1)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001779 When used with the :meth:`strptime` method, the ``%f`` directive
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001780 accepts from one to six digits and zero pads on the right. ``%f`` is
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001781 an extension to the set of format characters in the C standard (but
1782 implemented separately in datetime objects, and therefore always
1783 available).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001784
1785(2)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001786 When used with the :meth:`strptime` method, the ``%p`` directive only affects
Christian Heimes895627f2007-12-08 17:28:33 +00001787 the output hour field if the ``%I`` directive is used to parse the hour.
1788
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001789(3)
Alexander Belopolsky9971e002011-01-10 22:56:14 +00001790 Unlike :mod:`time` module, :mod:`datetime` module does not support
1791 leap seconds.
Christian Heimes895627f2007-12-08 17:28:33 +00001792
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001793(4)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001794 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in
Christian Heimes895627f2007-12-08 17:28:33 +00001795 calculations when the day of the week and the year are specified.
1796
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001797(5)
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001798 For technical reasons, :meth:`strftime` method does not support
Alexander Belopolsky5fc850b2011-01-10 23:31:51 +00001799 dates before year 1000: ``t.strftime(format)`` will raise a
1800 :exc:`ValueError` when ``t.year < 1000`` even if ``format`` does
1801 not contain ``%Y`` directive. The :meth:`strptime` method can
1802 parse years in the full [1, 9999] range, but years < 1000 must be
1803 zero-filled to 4-digit width.
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001804
1805 .. versionchanged:: 3.2
1806 In previous versions, :meth:`strftime` method was restricted to
1807 years >= 1900.
1808
1809(6)
Christian Heimes895627f2007-12-08 17:28:33 +00001810 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1811 ``%z`` is replaced with the string ``'-0330'``.
Alexander Belopolskyca94f552010-06-17 18:30:34 +00001812
Georg Brandl67b21b72010-08-17 15:07:14 +00001813.. versionchanged:: 3.2
1814 When the ``%z`` directive is provided to the :meth:`strptime` method, an
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001815 aware :class:`.datetime` object will be produced. The ``tzinfo`` of the
Georg Brandl67b21b72010-08-17 15:07:14 +00001816 result will be set to a :class:`timezone` instance.
R David Murray9075d8b2012-05-14 22:14:46 -04001817
1818.. rubric:: Footnotes
1819
1820.. [#] If, that is, we ignore the effects of Relativity