blob: c8dcbc1596963a0e9440fb9aae33b073c768aae3 [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
Georg Brandl116aa622007-08-15 14:28:22 +000015formatting and manipulation. For related
16functionality, see also the :mod:`time` and :mod:`calendar` modules.
17
18There are two kinds of date and time objects: "naive" and "aware". This
19distinction refers to whether the object has any notion of time zone, daylight
20saving time, or other kind of algorithmic or political time adjustment. Whether
Ezio Melotti35ec7f72011-10-02 12:44:50 +030021a naive :class:`.datetime` object represents Coordinated Universal Time (UTC),
Georg Brandl116aa622007-08-15 14:28:22 +000022local time, or time in some other timezone is purely up to the program, just
23like it's up to the program whether a particular number represents metres,
Ezio Melotti35ec7f72011-10-02 12:44:50 +030024miles, or mass. Naive :class:`.datetime` objects are easy to understand and to
Georg Brandl116aa622007-08-15 14:28:22 +000025work with, at the cost of ignoring some aspects of reality.
26
Ezio Melotti35ec7f72011-10-02 12:44:50 +030027For applications requiring more, :class:`.datetime` and :class:`.time` objects
Senthil Kumaran023c6f72011-07-17 19:01:14 +080028have an optional time zone information attribute, :attr:`tzinfo`, that can be
29set to an instance of a subclass of the abstract :class:`tzinfo` class. These
Georg Brandl116aa622007-08-15 14:28:22 +000030:class:`tzinfo` objects capture information about the offset from UTC time, the
Alexander Belopolsky4e749a12010-06-14 14:15:50 +000031time zone name, and whether Daylight Saving Time is in effect. Note that only
32one concrete :class:`tzinfo` class, the :class:`timezone` class, is supplied by the
Georg Brandl75546062011-09-17 20:20:04 +020033:mod:`datetime` module. The :class:`timezone` class can represent simple
Alexander Belopolsky4e749a12010-06-14 14:15:50 +000034timezones with fixed offset from UTC such as UTC itself or North American EST and
35EDT timezones. Supporting timezones at whatever level of detail is
36required is up to the application. The rules for time adjustment across the
37world are more political than rational, change frequently, and there is no
38standard suitable for every application aside from UTC.
Georg Brandl116aa622007-08-15 14:28:22 +000039
40The :mod:`datetime` module exports the following constants:
41
Georg Brandl116aa622007-08-15 14:28:22 +000042.. data:: MINYEAR
43
Ezio Melotti35ec7f72011-10-02 12:44:50 +030044 The smallest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl116aa622007-08-15 14:28:22 +000045 :const:`MINYEAR` is ``1``.
46
47
48.. data:: MAXYEAR
49
Ezio Melotti35ec7f72011-10-02 12:44:50 +030050 The largest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl116aa622007-08-15 14:28:22 +000051 :const:`MAXYEAR` is ``9999``.
52
53
54.. seealso::
55
56 Module :mod:`calendar`
57 General calendar related functions.
58
59 Module :mod:`time`
60 Time access and conversions.
61
62
63Available Types
64---------------
65
Georg Brandl116aa622007-08-15 14:28:22 +000066.. class:: date
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000067 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000068
69 An idealized naive date, assuming the current Gregorian calendar always was, and
70 always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and
71 :attr:`day`.
72
73
74.. class:: time
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000075 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000076
77 An idealized time, independent of any particular day, assuming that every day
78 has exactly 24\*60\*60 seconds (there is no notion of "leap seconds" here).
79 Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
80 and :attr:`tzinfo`.
81
82
83.. class:: datetime
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000084 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000085
86 A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`,
87 :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
88 and :attr:`tzinfo`.
89
90
91.. class:: timedelta
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000092 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000093
Ezio Melotti35ec7f72011-10-02 12:44:50 +030094 A duration expressing the difference between two :class:`date`, :class:`.time`,
95 or :class:`.datetime` instances to microsecond resolution.
Georg Brandl116aa622007-08-15 14:28:22 +000096
97
98.. class:: tzinfo
99
100 An abstract base class for time zone information objects. These are used by the
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300101 :class:`.datetime` and :class:`.time` classes to provide a customizable notion of
Georg Brandl116aa622007-08-15 14:28:22 +0000102 time adjustment (for example, to account for time zone and/or daylight saving
103 time).
104
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000105.. class:: timezone
106
107 A class that implements the :class:`tzinfo` abstract base class as a
108 fixed offset from the UTC.
109
110 .. versionadded:: 3.2
111
112
Georg Brandl116aa622007-08-15 14:28:22 +0000113Objects of these types are immutable.
114
115Objects of the :class:`date` type are always naive.
116
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300117An object *d* of type :class:`.time` or :class:`.datetime` may be naive or aware.
Georg Brandl116aa622007-08-15 14:28:22 +0000118*d* is aware if ``d.tzinfo`` is not ``None`` and ``d.tzinfo.utcoffset(d)`` does
119not return ``None``. If ``d.tzinfo`` is ``None``, or if ``d.tzinfo`` is not
120``None`` but ``d.tzinfo.utcoffset(d)`` returns ``None``, *d* is naive.
121
122The distinction between naive and aware doesn't apply to :class:`timedelta`
123objects.
124
125Subclass relationships::
126
127 object
128 timedelta
129 tzinfo
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000130 timezone
Georg Brandl116aa622007-08-15 14:28:22 +0000131 time
132 date
133 datetime
134
135
136.. _datetime-timedelta:
137
138:class:`timedelta` Objects
139--------------------------
140
141A :class:`timedelta` object represents a duration, the difference between two
142dates or times.
143
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000144.. class:: timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000145
Georg Brandl5c106642007-11-29 17:41:05 +0000146 All arguments are optional and default to ``0``. Arguments may be integers
Georg Brandl116aa622007-08-15 14:28:22 +0000147 or floats, and may be positive or negative.
148
149 Only *days*, *seconds* and *microseconds* are stored internally. Arguments are
150 converted to those units:
151
152 * A millisecond is converted to 1000 microseconds.
153 * A minute is converted to 60 seconds.
154 * An hour is converted to 3600 seconds.
155 * A week is converted to 7 days.
156
157 and days, seconds and microseconds are then normalized so that the
158 representation is unique, with
159
160 * ``0 <= microseconds < 1000000``
161 * ``0 <= seconds < 3600*24`` (the number of seconds in one day)
162 * ``-999999999 <= days <= 999999999``
163
164 If any argument is a float and there are fractional microseconds, the fractional
165 microseconds left over from all arguments are combined and their sum is rounded
166 to the nearest microsecond. If no argument is a float, the conversion and
167 normalization processes are exact (no information is lost).
168
169 If the normalized value of days lies outside the indicated range,
170 :exc:`OverflowError` is raised.
171
172 Note that normalization of negative values may be surprising at first. For
Christian Heimesfe337bf2008-03-23 21:54:12 +0000173 example,
Georg Brandl116aa622007-08-15 14:28:22 +0000174
Christian Heimes895627f2007-12-08 17:28:33 +0000175 >>> from datetime import timedelta
Georg Brandl116aa622007-08-15 14:28:22 +0000176 >>> d = timedelta(microseconds=-1)
177 >>> (d.days, d.seconds, d.microseconds)
178 (-1, 86399, 999999)
179
Georg Brandl116aa622007-08-15 14:28:22 +0000180
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000181Class attributes are:
Georg Brandl116aa622007-08-15 14:28:22 +0000182
183.. attribute:: timedelta.min
184
185 The most negative :class:`timedelta` object, ``timedelta(-999999999)``.
186
187
188.. attribute:: timedelta.max
189
190 The most positive :class:`timedelta` object, ``timedelta(days=999999999,
191 hours=23, minutes=59, seconds=59, microseconds=999999)``.
192
193
194.. attribute:: timedelta.resolution
195
196 The smallest possible difference between non-equal :class:`timedelta` objects,
197 ``timedelta(microseconds=1)``.
198
199Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``.
200``-timedelta.max`` is not representable as a :class:`timedelta` object.
201
202Instance attributes (read-only):
203
204+------------------+--------------------------------------------+
205| Attribute | Value |
206+==================+============================================+
207| ``days`` | Between -999999999 and 999999999 inclusive |
208+------------------+--------------------------------------------+
209| ``seconds`` | Between 0 and 86399 inclusive |
210+------------------+--------------------------------------------+
211| ``microseconds`` | Between 0 and 999999 inclusive |
212+------------------+--------------------------------------------+
213
214Supported operations:
215
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000216.. XXX this table is too wide!
Georg Brandl116aa622007-08-15 14:28:22 +0000217
218+--------------------------------+-----------------------------------------------+
219| Operation | Result |
220+================================+===============================================+
221| ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == |
222| | *t3* and *t1*-*t3* == *t2* are true. (1) |
223+--------------------------------+-----------------------------------------------+
224| ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* |
225| | == *t2* - *t3* and *t2* == *t1* + *t3* are |
226| | true. (1) |
227+--------------------------------+-----------------------------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000228| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer. |
Georg Brandl116aa622007-08-15 14:28:22 +0000229| | Afterwards *t1* // i == *t2* is true, |
230| | provided ``i != 0``. |
231+--------------------------------+-----------------------------------------------+
232| | In general, *t1* \* i == *t1* \* (i-1) + *t1* |
233| | is true. (1) |
234+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000235| ``t1 = t2 * f or t1 = f * t2`` | Delta multiplied by a float. The result is |
236| | rounded to the nearest multiple of |
237| | timedelta.resolution using round-half-to-even.|
238+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000239| ``f = t2 / t3`` | Division (3) of *t2* by *t3*. Returns a |
240| | :class:`float` object. |
241+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000242| ``t1 = t2 / f or t1 = t2 / i`` | Delta divided by a float or an int. The result|
243| | is rounded to the nearest multiple of |
244| | timedelta.resolution using round-half-to-even.|
245+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000246| ``t1 = t2 // i`` or | The floor is computed and the remainder (if |
247| ``t1 = t2 // t3`` | any) is thrown away. In the second case, an |
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000248| | integer is returned. (3) |
Mark Dickinson7c186e22010-04-20 22:32:49 +0000249+--------------------------------+-----------------------------------------------+
250| ``t1 = t2 % t3`` | The remainder is computed as a |
251| | :class:`timedelta` object. (3) |
252+--------------------------------+-----------------------------------------------+
253| ``q, r = divmod(t1, t2)`` | Computes the quotient and the remainder: |
254| | ``q = t1 // t2`` (3) and ``r = t1 % t2``. |
255| | q is an integer and r is a :class:`timedelta` |
256| | object. |
Georg Brandl116aa622007-08-15 14:28:22 +0000257+--------------------------------+-----------------------------------------------+
258| ``+t1`` | Returns a :class:`timedelta` object with the |
259| | same value. (2) |
260+--------------------------------+-----------------------------------------------+
261| ``-t1`` | equivalent to :class:`timedelta`\ |
262| | (-*t1.days*, -*t1.seconds*, |
263| | -*t1.microseconds*), and to *t1*\* -1. (1)(4) |
264+--------------------------------+-----------------------------------------------+
Georg Brandl495f7b52009-10-27 15:28:25 +0000265| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, and|
Georg Brandl116aa622007-08-15 14:28:22 +0000266| | to -*t* when ``t.days < 0``. (2) |
267+--------------------------------+-----------------------------------------------+
Georg Brandlf55c3152010-07-31 11:40:07 +0000268| ``str(t)`` | Returns a string in the form |
269| | ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D |
270| | is negative for negative ``t``. (5) |
271+--------------------------------+-----------------------------------------------+
272| ``repr(t)`` | Returns a string in the form |
273| | ``datetime.timedelta(D[, S[, U]])``, where D |
274| | is negative for negative ``t``. (5) |
275+--------------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000276
277Notes:
278
279(1)
280 This is exact, but may overflow.
281
282(2)
283 This is exact, and cannot overflow.
284
285(3)
286 Division by 0 raises :exc:`ZeroDivisionError`.
287
288(4)
289 -*timedelta.max* is not representable as a :class:`timedelta` object.
290
Georg Brandlf55c3152010-07-31 11:40:07 +0000291(5)
292 String representations of :class:`timedelta` objects are normalized
293 similarly to their internal representation. This leads to somewhat
294 unusual results for negative timedeltas. For example:
295
296 >>> timedelta(hours=-5)
297 datetime.timedelta(-1, 68400)
298 >>> print(_)
299 -1 day, 19:00:00
300
Georg Brandl116aa622007-08-15 14:28:22 +0000301In addition to the operations listed above :class:`timedelta` objects support
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300302certain additions and subtractions with :class:`date` and :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +0000303objects (see below).
304
Georg Brandl67b21b72010-08-17 15:07:14 +0000305.. versionchanged:: 3.2
306 Floor division and true division of a :class:`timedelta` object by another
307 :class:`timedelta` object are now supported, as are remainder operations and
308 the :func:`divmod` function. True division and multiplication of a
309 :class:`timedelta` object by a :class:`float` object are now supported.
Mark Dickinson7c186e22010-04-20 22:32:49 +0000310
311
Georg Brandl116aa622007-08-15 14:28:22 +0000312Comparisons of :class:`timedelta` objects are supported with the
313:class:`timedelta` object representing the smaller duration considered to be the
314smaller timedelta. In order to stop mixed-type comparisons from falling back to
315the default comparison by object address, when a :class:`timedelta` object is
316compared to an object of a different type, :exc:`TypeError` is raised unless the
317comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
318:const:`True`, respectively.
319
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000320:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl116aa622007-08-15 14:28:22 +0000321efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
322considered to be true if and only if it isn't equal to ``timedelta(0)``.
323
Antoine Pitroube6859d2009-11-25 23:02:32 +0000324Instance methods:
325
326.. method:: timedelta.total_seconds()
327
328 Return the total number of seconds contained in the duration. Equivalent to
Mark Dickinson0381e3f2010-05-08 14:35:02 +0000329 ``td / timedelta(seconds=1)``.
330
331 Note that for very large time intervals (greater than 270 years on
332 most platforms) this method will lose microsecond accuracy.
Antoine Pitroube6859d2009-11-25 23:02:32 +0000333
334 .. versionadded:: 3.2
335
336
Christian Heimesfe337bf2008-03-23 21:54:12 +0000337Example usage:
Georg Brandl48310cd2009-01-03 21:18:54 +0000338
Christian Heimes895627f2007-12-08 17:28:33 +0000339 >>> from datetime import timedelta
340 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000341 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Christian Heimes895627f2007-12-08 17:28:33 +0000342 ... minutes=50, seconds=600) # adds up to 365 days
Antoine Pitroube6859d2009-11-25 23:02:32 +0000343 >>> year.total_seconds()
344 31536000.0
Christian Heimes895627f2007-12-08 17:28:33 +0000345 >>> year == another_year
346 True
347 >>> ten_years = 10 * year
348 >>> ten_years, ten_years.days // 365
349 (datetime.timedelta(3650), 10)
350 >>> nine_years = ten_years - year
351 >>> nine_years, nine_years.days // 365
352 (datetime.timedelta(3285), 9)
353 >>> three_years = nine_years // 3;
354 >>> three_years, three_years.days // 365
355 (datetime.timedelta(1095), 3)
356 >>> abs(three_years - ten_years) == 2 * three_years + year
357 True
358
Georg Brandl116aa622007-08-15 14:28:22 +0000359
360.. _datetime-date:
361
362:class:`date` Objects
363---------------------
364
365A :class:`date` object represents a date (year, month and day) in an idealized
366calendar, the current Gregorian calendar indefinitely extended in both
367directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
368called day number 2, and so on. This matches the definition of the "proleptic
369Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
370where it's the base calendar for all computations. See the book for algorithms
371for converting between proleptic Gregorian ordinals and many other calendar
372systems.
373
374
375.. class:: date(year, month, day)
376
Georg Brandl5c106642007-11-29 17:41:05 +0000377 All arguments are required. Arguments may be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000378 ranges:
379
380 * ``MINYEAR <= year <= MAXYEAR``
381 * ``1 <= month <= 12``
382 * ``1 <= day <= number of days in the given month and year``
383
384 If an argument outside those ranges is given, :exc:`ValueError` is raised.
385
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000386
Georg Brandl116aa622007-08-15 14:28:22 +0000387Other constructors, all class methods:
388
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000389.. classmethod:: date.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000390
391 Return the current local date. This is equivalent to
392 ``date.fromtimestamp(time.time())``.
393
394
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000395.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000396
397 Return the local date corresponding to the POSIX timestamp, such as is returned
Victor Stinner5d272cc2012-03-13 13:35:55 +0100398 by :func:`time.time`. This may raise :exc:`OverflowError`, if the timestamp is out
Georg Brandl60203b42010-10-06 10:11:56 +0000399 of the range of values supported by the platform C :c:func:`localtime` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000400 It's common for this to be restricted to years from 1970 through 2038. Note
401 that on non-POSIX systems that include leap seconds in their notion of a
402 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
403
Victor Stinner5d272cc2012-03-13 13:35:55 +0100404 .. versionchanged:: 3.3
405 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
406 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100407 :c:func:`localtime` function. Raise :exc:`OSError` instead of
408 :exc:`ValueError` on :c:func:`localtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100409
Georg Brandl116aa622007-08-15 14:28:22 +0000410
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000411.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000412
413 Return the date corresponding to the proleptic Gregorian ordinal, where January
414 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
415 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
416 d``.
417
Georg Brandl116aa622007-08-15 14:28:22 +0000418
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000419Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000420
421.. attribute:: date.min
422
423 The earliest representable date, ``date(MINYEAR, 1, 1)``.
424
425
426.. attribute:: date.max
427
428 The latest representable date, ``date(MAXYEAR, 12, 31)``.
429
430
431.. attribute:: date.resolution
432
433 The smallest possible difference between non-equal date objects,
434 ``timedelta(days=1)``.
435
Georg Brandl116aa622007-08-15 14:28:22 +0000436
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000437Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000438
439.. attribute:: date.year
440
441 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
442
443
444.. attribute:: date.month
445
446 Between 1 and 12 inclusive.
447
448
449.. attribute:: date.day
450
451 Between 1 and the number of days in the given month of the given year.
452
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000453
Georg Brandl116aa622007-08-15 14:28:22 +0000454Supported operations:
455
456+-------------------------------+----------------------------------------------+
457| Operation | Result |
458+===============================+==============================================+
459| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
460| | from *date1*. (1) |
461+-------------------------------+----------------------------------------------+
462| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
463| | timedelta == date1``. (2) |
464+-------------------------------+----------------------------------------------+
465| ``timedelta = date1 - date2`` | \(3) |
466+-------------------------------+----------------------------------------------+
467| ``date1 < date2`` | *date1* is considered less than *date2* when |
468| | *date1* precedes *date2* in time. (4) |
469+-------------------------------+----------------------------------------------+
470
471Notes:
472
473(1)
474 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
475 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
476 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
477 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
478 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
479
480(2)
481 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
482 isolation can overflow in cases where date1 - timedelta does not.
483 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
484
485(3)
486 This is exact, and cannot overflow. timedelta.seconds and
487 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
488
489(4)
490 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
491 date2.toordinal()``. In order to stop comparison from falling back to the
492 default scheme of comparing object addresses, date comparison normally raises
493 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
494 However, ``NotImplemented`` is returned instead if the other comparand has a
495 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
496 chance at implementing mixed-type comparison. If not, when a :class:`date`
497 object is compared to an object of a different type, :exc:`TypeError` is raised
498 unless the comparison is ``==`` or ``!=``. The latter cases return
499 :const:`False` or :const:`True`, respectively.
500
501Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
502objects are considered to be true.
503
504Instance methods:
505
Georg Brandl116aa622007-08-15 14:28:22 +0000506.. method:: date.replace(year, month, day)
507
Senthil Kumarana6bac952011-07-04 11:28:30 -0700508 Return a date with the same value, except for those parameters given new
509 values by whichever keyword arguments are specified. For example, if ``d ==
510 date(2002, 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000511
512
513.. method:: date.timetuple()
514
515 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
516 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
517 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000518 d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1,
519 1).toordinal() + 1`` is the day number within the current year starting with
520 ``1`` for January 1st.
Georg Brandl116aa622007-08-15 14:28:22 +0000521
522
523.. method:: date.toordinal()
524
525 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
526 has ordinal 1. For any :class:`date` object *d*,
527 ``date.fromordinal(d.toordinal()) == d``.
528
529
530.. method:: date.weekday()
531
532 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
533 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
534 :meth:`isoweekday`.
535
536
537.. method:: date.isoweekday()
538
539 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
540 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
541 :meth:`weekday`, :meth:`isocalendar`.
542
543
544.. method:: date.isocalendar()
545
546 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
547
548 The ISO calendar is a widely used variant of the Gregorian calendar. See
Mark Dickinsonf964ac22009-11-03 16:29:10 +0000549 http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
550 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000551
552 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
553 Monday and ends on a Sunday. The first week of an ISO year is the first
554 (Gregorian) calendar week of a year containing a Thursday. This is called week
555 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
556
557 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
558 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
559 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
560 4).isocalendar() == (2004, 1, 7)``.
561
562
563.. method:: date.isoformat()
564
565 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
566 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
567
568
569.. method:: date.__str__()
570
571 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
572
573
574.. method:: date.ctime()
575
576 Return a string representing the date, for example ``date(2002, 12,
577 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
578 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
Georg Brandl60203b42010-10-06 10:11:56 +0000579 :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +0000580 :meth:`date.ctime` does not invoke) conforms to the C standard.
581
582
583.. method:: date.strftime(format)
584
585 Return a string representing the date, controlled by an explicit format string.
586 Format codes referring to hours, minutes or seconds will see 0 values. See
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000587 section :ref:`strftime-strptime-behavior`.
588
Georg Brandl116aa622007-08-15 14:28:22 +0000589
Christian Heimes895627f2007-12-08 17:28:33 +0000590Example of counting days to an event::
591
592 >>> import time
593 >>> from datetime import date
594 >>> today = date.today()
595 >>> today
596 datetime.date(2007, 12, 5)
597 >>> today == date.fromtimestamp(time.time())
598 True
599 >>> my_birthday = date(today.year, 6, 24)
600 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000601 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000602 >>> my_birthday
603 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000604 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000605 >>> time_to_birthday.days
606 202
607
Christian Heimesfe337bf2008-03-23 21:54:12 +0000608Example of working with :class:`date`:
609
610.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000611
612 >>> from datetime import date
613 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
614 >>> d
615 datetime.date(2002, 3, 11)
616 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000617 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000618 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000619 2002 # year
620 3 # month
621 11 # day
622 0
623 0
624 0
625 0 # weekday (0 = Monday)
626 70 # 70th day in the year
627 -1
628 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000629 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000630 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000631 2002 # ISO year
632 11 # ISO week number
633 1 # ISO day number ( 1 = Monday )
634 >>> d.isoformat()
635 '2002-03-11'
636 >>> d.strftime("%d/%m/%y")
637 '11/03/02'
638 >>> d.strftime("%A %d. %B %Y")
639 'Monday 11. March 2002'
640
Georg Brandl116aa622007-08-15 14:28:22 +0000641
642.. _datetime-datetime:
643
644:class:`datetime` Objects
645-------------------------
646
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300647A :class:`.datetime` object is a single object containing all the information
648from a :class:`date` object and a :class:`.time` object. Like a :class:`date`
649object, :class:`.datetime` assumes the current Gregorian calendar extended in
650both directions; like a time object, :class:`.datetime` assumes there are exactly
Georg Brandl116aa622007-08-15 14:28:22 +00006513600\*24 seconds in every day.
652
653Constructor:
654
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000655.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000656
657 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000658 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
659 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000660
661 * ``MINYEAR <= year <= MAXYEAR``
662 * ``1 <= month <= 12``
663 * ``1 <= day <= number of days in the given month and year``
664 * ``0 <= hour < 24``
665 * ``0 <= minute < 60``
666 * ``0 <= second < 60``
667 * ``0 <= microsecond < 1000000``
668
669 If an argument outside those ranges is given, :exc:`ValueError` is raised.
670
671Other constructors, all class methods:
672
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000673.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000674
675 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
676 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
677 :meth:`fromtimestamp`.
678
679
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000680.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000681
682 Return the current local date and time. If optional argument *tz* is ``None``
683 or not specified, this is like :meth:`today`, but, if possible, supplies more
684 precision than can be gotten from going through a :func:`time.time` timestamp
685 (for example, this may be possible on platforms supplying the C
Georg Brandl60203b42010-10-06 10:11:56 +0000686 :c:func:`gettimeofday` function).
Georg Brandl116aa622007-08-15 14:28:22 +0000687
688 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
689 current date and time are converted to *tz*'s time zone. In this case the
690 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
691 See also :meth:`today`, :meth:`utcnow`.
692
693
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000694.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000695
696 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
697 :meth:`now`, but returns the current UTC date and time, as a naive
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300698 :class:`.datetime` object. An aware current UTC datetime can be obtained by
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000699 calling ``datetime.now(timezone.utc)``. See also :meth:`now`.
Georg Brandl116aa622007-08-15 14:28:22 +0000700
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000701.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000702
703 Return the local date and time corresponding to the POSIX timestamp, such as is
704 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
705 specified, the timestamp is converted to the platform's local date and time, and
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300706 the returned :class:`.datetime` object is naive.
Georg Brandl116aa622007-08-15 14:28:22 +0000707
708 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
709 timestamp is converted to *tz*'s time zone. In this case the result is
710 equivalent to
711 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
712
713 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
Georg Brandl60203b42010-10-06 10:11:56 +0000714 the range of values supported by the platform C :c:func:`localtime` or
715 :c:func:`gmtime` functions. It's common for this to be restricted to years in
Georg Brandl116aa622007-08-15 14:28:22 +0000716 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
717 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
718 and then it's possible to have two timestamps differing by a second that yield
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300719 identical :class:`.datetime` objects. See also :meth:`utcfromtimestamp`.
Georg Brandl116aa622007-08-15 14:28:22 +0000720
Victor Stinner5d272cc2012-03-13 13:35:55 +0100721 .. versionchanged:: 3.3
722 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
723 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100724 :c:func:`localtime` or :c:func:`gmtime` functions. Raise :exc:`OSError`
725 instead of :exc:`ValueError` on :c:func:`localtime` or :c:func:`gmtime`
726 failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100727
Georg Brandl116aa622007-08-15 14:28:22 +0000728
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000729.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000730
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300731 Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with
Georg Brandl116aa622007-08-15 14:28:22 +0000732 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
Georg Brandl60203b42010-10-06 10:11:56 +0000733 out of the range of values supported by the platform C :c:func:`gmtime` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000734 It's common for this to be restricted to years in 1970 through 2038. See also
735 :meth:`fromtimestamp`.
736
Alexander Belopolsky54afa552011-04-25 13:00:40 -0400737 On the POSIX compliant platforms, ``utcfromtimestamp(timestamp)``
738 is equivalent to the following expression::
739
740 datetime(1970, 1, 1) + timedelta(seconds=timestamp)
741
742 There is no method to obtain the timestamp from a :class:`datetime`
743 instance, but POSIX timestamp corresponding to a :class:`datetime`
744 instance ``dt`` can be easily calculated as follows. For a naive
745 ``dt``::
746
747 timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
748
749 And for an aware ``dt``::
750
751 timestamp = (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)) / timedelta(seconds=1)
752
Victor Stinner5d272cc2012-03-13 13:35:55 +0100753 .. versionchanged:: 3.3
754 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
755 is out of the range of values supported by the platform C
Victor Stinner21f58932012-03-14 00:15:40 +0100756 :c:func:`gmtime` function. Raise :exc:`OSError` instead of
757 :exc:`ValueError` on :c:func:`gmtime` failure.
Victor Stinner5d272cc2012-03-13 13:35:55 +0100758
Georg Brandl116aa622007-08-15 14:28:22 +0000759
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000760.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000761
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300762 Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal,
Georg Brandl116aa622007-08-15 14:28:22 +0000763 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
764 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
765 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
766
767
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000768.. classmethod:: datetime.combine(date, time)
Georg Brandl116aa622007-08-15 14:28:22 +0000769
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300770 Return a new :class:`.datetime` object whose date components are equal to the
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800771 given :class:`date` object's, and whose time components and :attr:`tzinfo`
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300772 attributes are equal to the given :class:`.time` object's. For any
773 :class:`.datetime` object *d*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800774 ``d == datetime.combine(d.date(), d.timetz())``. If date is a
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300775 :class:`.datetime` object, its time components and :attr:`tzinfo` attributes
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800776 are ignored.
Georg Brandl116aa622007-08-15 14:28:22 +0000777
778
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000779.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000780
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300781 Return a :class:`.datetime` corresponding to *date_string*, parsed according to
Georg Brandl116aa622007-08-15 14:28:22 +0000782 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
783 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
784 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 +0000785 time tuple. See section :ref:`strftime-strptime-behavior`.
786
Georg Brandl116aa622007-08-15 14:28:22 +0000787
Georg Brandl116aa622007-08-15 14:28:22 +0000788
789Class attributes:
790
Georg Brandl116aa622007-08-15 14:28:22 +0000791.. attribute:: datetime.min
792
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300793 The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1,
Georg Brandl116aa622007-08-15 14:28:22 +0000794 tzinfo=None)``.
795
796
797.. attribute:: datetime.max
798
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300799 The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
Georg Brandl116aa622007-08-15 14:28:22 +0000800 59, 999999, tzinfo=None)``.
801
802
803.. attribute:: datetime.resolution
804
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300805 The smallest possible difference between non-equal :class:`.datetime` objects,
Georg Brandl116aa622007-08-15 14:28:22 +0000806 ``timedelta(microseconds=1)``.
807
Georg Brandl116aa622007-08-15 14:28:22 +0000808
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000809Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000810
811.. attribute:: datetime.year
812
813 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
814
815
816.. attribute:: datetime.month
817
818 Between 1 and 12 inclusive.
819
820
821.. attribute:: datetime.day
822
823 Between 1 and the number of days in the given month of the given year.
824
825
826.. attribute:: datetime.hour
827
828 In ``range(24)``.
829
830
831.. attribute:: datetime.minute
832
833 In ``range(60)``.
834
835
836.. attribute:: datetime.second
837
838 In ``range(60)``.
839
840
841.. attribute:: datetime.microsecond
842
843 In ``range(1000000)``.
844
845
846.. attribute:: datetime.tzinfo
847
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300848 The object passed as the *tzinfo* argument to the :class:`.datetime` constructor,
Georg Brandl116aa622007-08-15 14:28:22 +0000849 or ``None`` if none was passed.
850
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000851
Georg Brandl116aa622007-08-15 14:28:22 +0000852Supported operations:
853
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300854+---------------------------------------+--------------------------------+
855| Operation | Result |
856+=======================================+================================+
857| ``datetime2 = datetime1 + timedelta`` | \(1) |
858+---------------------------------------+--------------------------------+
859| ``datetime2 = datetime1 - timedelta`` | \(2) |
860+---------------------------------------+--------------------------------+
861| ``timedelta = datetime1 - datetime2`` | \(3) |
862+---------------------------------------+--------------------------------+
863| ``datetime1 < datetime2`` | Compares :class:`.datetime` to |
864| | :class:`.datetime`. (4) |
865+---------------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000866
867(1)
868 datetime2 is a duration of timedelta removed from datetime1, moving forward in
869 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
Senthil Kumarana6bac952011-07-04 11:28:30 -0700870 result has the same :attr:`tzinfo` attribute as the input datetime, and
871 datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
872 datetime2.year would be smaller than :const:`MINYEAR` or larger than
873 :const:`MAXYEAR`. Note that no time zone adjustments are done even if the
874 input is an aware object.
Georg Brandl116aa622007-08-15 14:28:22 +0000875
876(2)
877 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
Senthil Kumarana6bac952011-07-04 11:28:30 -0700878 addition, the result has the same :attr:`tzinfo` attribute as the input
879 datetime, and no time zone adjustments are done even if the input is aware.
880 This isn't quite equivalent to datetime1 + (-timedelta), because -timedelta
881 in isolation can overflow in cases where datetime1 - timedelta does not.
Georg Brandl116aa622007-08-15 14:28:22 +0000882
883(3)
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300884 Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if
Georg Brandl116aa622007-08-15 14:28:22 +0000885 both operands are naive, or if both are aware. If one is aware and the other is
886 naive, :exc:`TypeError` is raised.
887
Senthil Kumarana6bac952011-07-04 11:28:30 -0700888 If both are naive, or both are aware and have the same :attr:`tzinfo` attribute,
889 the :attr:`tzinfo` attributes are ignored, and the result is a :class:`timedelta`
Georg Brandl116aa622007-08-15 14:28:22 +0000890 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
891 are done in this case.
892
Senthil Kumarana6bac952011-07-04 11:28:30 -0700893 If both are aware and have different :attr:`tzinfo` attributes, ``a-b`` acts
894 as if *a* and *b* were first converted to naive UTC datetimes first. The
895 result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
896 - b.utcoffset())`` except that the implementation never overflows.
Georg Brandl116aa622007-08-15 14:28:22 +0000897
898(4)
899 *datetime1* is considered less than *datetime2* when *datetime1* precedes
900 *datetime2* in time.
901
902 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
Senthil Kumarana6bac952011-07-04 11:28:30 -0700903 If both comparands are aware, and have the same :attr:`tzinfo` attribute, the
904 common :attr:`tzinfo` attribute is ignored and the base datetimes are
905 compared. If both comparands are aware and have different :attr:`tzinfo`
906 attributes, the comparands are first adjusted by subtracting their UTC
907 offsets (obtained from ``self.utcoffset()``).
Georg Brandl116aa622007-08-15 14:28:22 +0000908
909 .. note::
910
911 In order to stop comparison from falling back to the default scheme of comparing
912 object addresses, datetime comparison normally raises :exc:`TypeError` if the
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300913 other comparand isn't also a :class:`.datetime` object. However,
Georg Brandl116aa622007-08-15 14:28:22 +0000914 ``NotImplemented`` is returned instead if the other comparand has a
915 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300916 chance at implementing mixed-type comparison. If not, when a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +0000917 object is compared to an object of a different type, :exc:`TypeError` is raised
918 unless the comparison is ``==`` or ``!=``. The latter cases return
919 :const:`False` or :const:`True`, respectively.
920
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300921:class:`.datetime` objects can be used as dictionary keys. In Boolean contexts,
922all :class:`.datetime` objects are considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +0000923
924Instance methods:
925
Georg Brandl116aa622007-08-15 14:28:22 +0000926.. method:: datetime.date()
927
928 Return :class:`date` object with same year, month and day.
929
930
931.. method:: datetime.time()
932
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300933 Return :class:`.time` object with same hour, minute, second and microsecond.
Georg Brandl116aa622007-08-15 14:28:22 +0000934 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
935
936
937.. method:: datetime.timetz()
938
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300939 Return :class:`.time` object with same hour, minute, second, microsecond, and
Senthil Kumarana6bac952011-07-04 11:28:30 -0700940 tzinfo attributes. See also method :meth:`time`.
Georg Brandl116aa622007-08-15 14:28:22 +0000941
942
943.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
944
Senthil Kumarana6bac952011-07-04 11:28:30 -0700945 Return a datetime with the same attributes, except for those attributes given
946 new values by whichever keyword arguments are specified. Note that
947 ``tzinfo=None`` can be specified to create a naive datetime from an aware
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800948 datetime with no conversion of date and time data.
Georg Brandl116aa622007-08-15 14:28:22 +0000949
950
951.. method:: datetime.astimezone(tz)
952
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300953 Return a :class:`.datetime` object with new :attr:`tzinfo` attribute *tz*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800954 adjusting the date and time data so the result is the same UTC time as
Senthil Kumarana6bac952011-07-04 11:28:30 -0700955 *self*, but in *tz*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +0000956
957 *tz* must be an instance of a :class:`tzinfo` subclass, and its
958 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
959 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
960 not return ``None``).
961
962 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800963 adjustment of date or time data is performed. Else the result is local
Senthil Kumarana6bac952011-07-04 11:28:30 -0700964 time in time zone *tz*, representing the same UTC time as *self*: after
965 ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800966 the same date and time data as ``dt - dt.utcoffset()``. The discussion
Senthil Kumarana6bac952011-07-04 11:28:30 -0700967 of class :class:`tzinfo` explains the cases at Daylight Saving Time transition
968 boundaries where this cannot be achieved (an issue only if *tz* models both
969 standard and daylight time).
Georg Brandl116aa622007-08-15 14:28:22 +0000970
971 If you merely want to attach a time zone object *tz* to a datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800972 adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you
Georg Brandl116aa622007-08-15 14:28:22 +0000973 merely want to remove the time zone object from an aware datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800974 conversion of date and time data, use ``dt.replace(tzinfo=None)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000975
976 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
977 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
978 Ignoring error cases, :meth:`astimezone` acts like::
979
980 def astimezone(self, tz):
981 if self.tzinfo is tz:
982 return self
983 # Convert self to UTC, and attach the new time zone object.
984 utc = (self - self.utcoffset()).replace(tzinfo=tz)
985 # Convert from UTC to tz's local time.
986 return tz.fromutc(utc)
987
988
989.. method:: datetime.utcoffset()
990
991 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
992 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
993 return ``None``, or a :class:`timedelta` object representing a whole number of
994 minutes with magnitude less than one day.
995
996
997.. method:: datetime.dst()
998
999 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1000 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
1001 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1002 with magnitude less than one day.
1003
1004
1005.. method:: datetime.tzname()
1006
1007 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1008 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
1009 ``None`` or a string object,
1010
1011
1012.. method:: datetime.timetuple()
1013
1014 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
1015 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
Alexander Belopolsky64912482010-06-08 18:59:20 +00001016 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
1017 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
1018 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
1019 of the result is set according to the :meth:`dst` method: :attr:`tzinfo` is
Georg Brandl682d7e02010-10-06 10:26:05 +00001020 ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
Alexander Belopolsky64912482010-06-08 18:59:20 +00001021 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
Alexander Belopolskyda62f2f2010-06-09 17:11:01 +00001022 else :attr:`tm_isdst` is set to ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +00001023
1024
1025.. method:: datetime.utctimetuple()
1026
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001027 If :class:`.datetime` instance *d* is naive, this is the same as
Georg Brandl116aa622007-08-15 14:28:22 +00001028 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
1029 ``d.dst()`` returns. DST is never in effect for a UTC time.
1030
1031 If *d* is aware, *d* is normalized to UTC time, by subtracting
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00001032 ``d.utcoffset()``, and a :class:`time.struct_time` for the
1033 normalized time is returned. :attr:`tm_isdst` is forced to 0. Note
1034 that an :exc:`OverflowError` may be raised if *d*.year was
1035 ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
Georg Brandl116aa622007-08-15 14:28:22 +00001036 boundary.
1037
1038
1039.. method:: datetime.toordinal()
1040
1041 Return the proleptic Gregorian ordinal of the date. The same as
1042 ``self.date().toordinal()``.
1043
1044
1045.. method:: datetime.weekday()
1046
1047 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
1048 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
1049
1050
1051.. method:: datetime.isoweekday()
1052
1053 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
1054 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
1055 :meth:`isocalendar`.
1056
1057
1058.. method:: datetime.isocalendar()
1059
1060 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
1061 ``self.date().isocalendar()``.
1062
1063
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001064.. method:: datetime.isoformat(sep='T')
Georg Brandl116aa622007-08-15 14:28:22 +00001065
1066 Return a string representing the date and time in ISO 8601 format,
1067 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
1068 YYYY-MM-DDTHH:MM:SS
1069
1070 If :meth:`utcoffset` does not return ``None``, a 6-character string is
1071 appended, giving the UTC offset in (signed) hours and minutes:
1072 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
1073 YYYY-MM-DDTHH:MM:SS+HH:MM
1074
1075 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +00001076 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +00001077
1078 >>> from datetime import tzinfo, timedelta, datetime
1079 >>> class TZ(tzinfo):
1080 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1081 ...
1082 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1083 '2002-12-25 00:00:00-06:39'
1084
1085
1086.. method:: datetime.__str__()
1087
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001088 For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to
Georg Brandl116aa622007-08-15 14:28:22 +00001089 ``d.isoformat(' ')``.
1090
1091
1092.. method:: datetime.ctime()
1093
1094 Return a string representing the date and time, for example ``datetime(2002, 12,
1095 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1096 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
Georg Brandl60203b42010-10-06 10:11:56 +00001097 native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +00001098 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1099
1100
1101.. method:: datetime.strftime(format)
1102
1103 Return a string representing the date and time, controlled by an explicit format
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001104 string. See section :ref:`strftime-strptime-behavior`.
1105
Georg Brandl116aa622007-08-15 14:28:22 +00001106
Christian Heimesfe337bf2008-03-23 21:54:12 +00001107Examples of working with datetime objects:
1108
1109.. doctest::
1110
Christian Heimes895627f2007-12-08 17:28:33 +00001111 >>> from datetime import datetime, date, time
1112 >>> # Using datetime.combine()
1113 >>> d = date(2005, 7, 14)
1114 >>> t = time(12, 30)
1115 >>> datetime.combine(d, t)
1116 datetime.datetime(2005, 7, 14, 12, 30)
1117 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001118 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001119 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001120 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001121 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1122 >>> # Using datetime.strptime()
1123 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1124 >>> dt
1125 datetime.datetime(2006, 11, 21, 16, 30)
1126 >>> # Using datetime.timetuple() to get tuple of all attributes
1127 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001128 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001129 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001130 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001131 2006 # year
1132 11 # month
1133 21 # day
1134 16 # hour
1135 30 # minute
1136 0 # second
1137 1 # weekday (0 = Monday)
1138 325 # number of days since 1st January
1139 -1 # dst - method tzinfo.dst() returned None
1140 >>> # Date in ISO format
1141 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001142 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001143 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001144 ...
1145 2006 # ISO year
1146 47 # ISO week
1147 2 # ISO weekday
1148 >>> # Formatting datetime
1149 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1150 'Tuesday, 21. November 2006 04:30PM'
1151
Christian Heimesfe337bf2008-03-23 21:54:12 +00001152Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001153
1154 >>> from datetime import timedelta, datetime, tzinfo
1155 >>> class GMT1(tzinfo):
1156 ... def __init__(self): # DST starts last Sunday in March
1157 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1158 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001159 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001160 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1161 ... def utcoffset(self, dt):
1162 ... return timedelta(hours=1) + self.dst(dt)
Georg Brandl48310cd2009-01-03 21:18:54 +00001163 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001164 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1165 ... return timedelta(hours=1)
1166 ... else:
1167 ... return timedelta(0)
1168 ... def tzname(self,dt):
1169 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001170 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001171 >>> class GMT2(tzinfo):
1172 ... def __init__(self):
Georg Brandl48310cd2009-01-03 21:18:54 +00001173 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001174 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001175 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001176 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1177 ... def utcoffset(self, dt):
1178 ... return timedelta(hours=1) + self.dst(dt)
1179 ... def dst(self, dt):
1180 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1181 ... return timedelta(hours=2)
1182 ... else:
1183 ... return timedelta(0)
1184 ... def tzname(self,dt):
1185 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001186 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001187 >>> gmt1 = GMT1()
1188 >>> # Daylight Saving Time
1189 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1190 >>> dt1.dst()
1191 datetime.timedelta(0)
1192 >>> dt1.utcoffset()
1193 datetime.timedelta(0, 3600)
1194 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1195 >>> dt2.dst()
1196 datetime.timedelta(0, 3600)
1197 >>> dt2.utcoffset()
1198 datetime.timedelta(0, 7200)
1199 >>> # Convert datetime to another time zone
1200 >>> dt3 = dt2.astimezone(GMT2())
1201 >>> dt3 # doctest: +ELLIPSIS
1202 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1203 >>> dt2 # doctest: +ELLIPSIS
1204 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1205 >>> dt2.utctimetuple() == dt3.utctimetuple()
1206 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001207
Christian Heimes895627f2007-12-08 17:28:33 +00001208
Georg Brandl116aa622007-08-15 14:28:22 +00001209
1210.. _datetime-time:
1211
1212:class:`time` Objects
1213---------------------
1214
1215A time object represents a (local) time of day, independent of any particular
1216day, and subject to adjustment via a :class:`tzinfo` object.
1217
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001218.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001219
1220 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001221 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001222 following ranges:
1223
1224 * ``0 <= hour < 24``
1225 * ``0 <= minute < 60``
1226 * ``0 <= second < 60``
1227 * ``0 <= microsecond < 1000000``.
1228
1229 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1230 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1231
1232Class attributes:
1233
1234
1235.. attribute:: time.min
1236
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001237 The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001238
1239
1240.. attribute:: time.max
1241
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001242 The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001243
1244
1245.. attribute:: time.resolution
1246
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001247 The smallest possible difference between non-equal :class:`.time` objects,
1248 ``timedelta(microseconds=1)``, although note that arithmetic on
1249 :class:`.time` objects is not supported.
Georg Brandl116aa622007-08-15 14:28:22 +00001250
Georg Brandl116aa622007-08-15 14:28:22 +00001251
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001252Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001253
1254.. attribute:: time.hour
1255
1256 In ``range(24)``.
1257
1258
1259.. attribute:: time.minute
1260
1261 In ``range(60)``.
1262
1263
1264.. attribute:: time.second
1265
1266 In ``range(60)``.
1267
1268
1269.. attribute:: time.microsecond
1270
1271 In ``range(1000000)``.
1272
1273
1274.. attribute:: time.tzinfo
1275
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001276 The object passed as the tzinfo argument to the :class:`.time` constructor, or
Georg Brandl116aa622007-08-15 14:28:22 +00001277 ``None`` if none was passed.
1278
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001279
Georg Brandl116aa622007-08-15 14:28:22 +00001280Supported operations:
1281
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001282* comparison of :class:`.time` to :class:`.time`, where *a* is considered less
Georg Brandl116aa622007-08-15 14:28:22 +00001283 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1284 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
Senthil Kumarana6bac952011-07-04 11:28:30 -07001285 the same :attr:`tzinfo` attribute, the common :attr:`tzinfo` attribute is
1286 ignored and the base times are compared. If both comparands are aware and
1287 have different :attr:`tzinfo` attributes, the comparands are first adjusted by
1288 subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
1289 to stop mixed-type comparisons from falling back to the default comparison by
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001290 object address, when a :class:`.time` object is compared to an object of a
Senthil Kumaran3aac1792011-07-04 11:43:51 -07001291 different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
Senthil Kumarana6bac952011-07-04 11:28:30 -07001292 ``!=``. The latter cases return :const:`False` or :const:`True`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +00001293
1294* hash, use as dict key
1295
1296* efficient pickling
1297
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001298* in Boolean contexts, a :class:`.time` object is considered to be true if and
Georg Brandl116aa622007-08-15 14:28:22 +00001299 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1300 ``0`` if that's ``None``), the result is non-zero.
1301
Georg Brandl116aa622007-08-15 14:28:22 +00001302
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001303Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001304
1305.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1306
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001307 Return a :class:`.time` with the same value, except for those attributes given
Senthil Kumarana6bac952011-07-04 11:28:30 -07001308 new values by whichever keyword arguments are specified. Note that
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001309 ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
1310 aware :class:`.time`, without conversion of the time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001311
1312
1313.. method:: time.isoformat()
1314
1315 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1316 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1317 6-character string is appended, giving the UTC offset in (signed) hours and
1318 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1319
1320
1321.. method:: time.__str__()
1322
1323 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1324
1325
1326.. method:: time.strftime(format)
1327
1328 Return a string representing the time, controlled by an explicit format string.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001329 See section :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001330
1331
1332.. method:: time.utcoffset()
1333
1334 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1335 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1336 return ``None`` or a :class:`timedelta` object representing a whole number of
1337 minutes with magnitude less than one day.
1338
1339
1340.. method:: time.dst()
1341
1342 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1343 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1344 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1345 with magnitude less than one day.
1346
1347
1348.. method:: time.tzname()
1349
1350 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1351 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1352 return ``None`` or a string object.
1353
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001354
Christian Heimesfe337bf2008-03-23 21:54:12 +00001355Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001356
Christian Heimes895627f2007-12-08 17:28:33 +00001357 >>> from datetime import time, tzinfo
1358 >>> class GMT1(tzinfo):
1359 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001360 ... return timedelta(hours=1)
1361 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001362 ... return timedelta(0)
1363 ... def tzname(self,dt):
1364 ... return "Europe/Prague"
1365 ...
1366 >>> t = time(12, 10, 30, tzinfo=GMT1())
1367 >>> t # doctest: +ELLIPSIS
1368 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1369 >>> gmt = GMT1()
1370 >>> t.isoformat()
1371 '12:10:30+01:00'
1372 >>> t.dst()
1373 datetime.timedelta(0)
1374 >>> t.tzname()
1375 'Europe/Prague'
1376 >>> t.strftime("%H:%M:%S %Z")
1377 '12:10:30 Europe/Prague'
1378
Georg Brandl116aa622007-08-15 14:28:22 +00001379
1380.. _datetime-tzinfo:
1381
1382:class:`tzinfo` Objects
1383-----------------------
1384
Brett Cannone1327f72009-01-29 04:10:21 +00001385:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001386instantiated directly. You need to derive a concrete subclass, and (at least)
1387supply implementations of the standard :class:`tzinfo` methods needed by the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001388:class:`.datetime` methods you use. The :mod:`datetime` module supplies
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001389a simple concrete subclass of :class:`tzinfo` :class:`timezone` which can reprsent
1390timezones with fixed offset from UTC such as UTC itself or North American EST and
1391EDT.
Georg Brandl116aa622007-08-15 14:28:22 +00001392
1393An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001394constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
Senthil Kumarana6bac952011-07-04 11:28:30 -07001395view their attributes as being in local time, and the :class:`tzinfo` object
Georg Brandl116aa622007-08-15 14:28:22 +00001396supports methods revealing offset of local time from UTC, the name of the time
1397zone, and DST offset, all relative to a date or time object passed to them.
1398
1399Special requirement for pickling: A :class:`tzinfo` subclass must have an
1400:meth:`__init__` method that can be called with no arguments, else it can be
1401pickled but possibly not unpickled again. This is a technical requirement that
1402may be relaxed in the future.
1403
1404A concrete subclass of :class:`tzinfo` may need to implement the following
1405methods. Exactly which methods are needed depends on the uses made of aware
1406:mod:`datetime` objects. If in doubt, simply implement all of them.
1407
1408
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001409.. method:: tzinfo.utcoffset(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001410
1411 Return offset of local time from UTC, in minutes east of UTC. If local time is
1412 west of UTC, this should be negative. Note that this is intended to be the
1413 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1414 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1415 the UTC offset isn't known, return ``None``. Else the value returned must be a
1416 :class:`timedelta` object specifying a whole number of minutes in the range
1417 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1418 than one day). Most implementations of :meth:`utcoffset` will probably look
1419 like one of these two::
1420
1421 return CONSTANT # fixed-offset class
1422 return CONSTANT + self.dst(dt) # daylight-aware class
1423
1424 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1425 ``None`` either.
1426
1427 The default implementation of :meth:`utcoffset` raises
1428 :exc:`NotImplementedError`.
1429
1430
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001431.. method:: tzinfo.dst(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001432
1433 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1434 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1435 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1436 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1437 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1438 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1439 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -07001440 attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
1441 should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
1442 DST changes when crossing time zones.
Georg Brandl116aa622007-08-15 14:28:22 +00001443
1444 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1445 daylight times must be consistent in this sense:
1446
1447 ``tz.utcoffset(dt) - tz.dst(dt)``
1448
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001449 must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo ==
Georg Brandl116aa622007-08-15 14:28:22 +00001450 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1451 zone's "standard offset", which should not depend on the date or the time, but
1452 only on geographic location. The implementation of :meth:`datetime.astimezone`
1453 relies on this, but cannot detect violations; it's the programmer's
1454 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1455 this, it may be able to override the default implementation of
1456 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1457
1458 Most implementations of :meth:`dst` will probably look like one of these two::
1459
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001460 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001461 # a fixed-offset class: doesn't account for DST
1462 return timedelta(0)
1463
1464 or ::
1465
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001466 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001467 # Code to set dston and dstoff to the time zone's DST
1468 # transition times based on the input dt.year, and expressed
1469 # in standard local time. Then
1470
1471 if dston <= dt.replace(tzinfo=None) < dstoff:
1472 return timedelta(hours=1)
1473 else:
1474 return timedelta(0)
1475
1476 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1477
1478
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001479.. method:: tzinfo.tzname(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001480
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001481 Return the time zone name corresponding to the :class:`.datetime` object *dt*, as
Georg Brandl116aa622007-08-15 14:28:22 +00001482 a string. Nothing about string names is defined by the :mod:`datetime` module,
1483 and there's no requirement that it mean anything in particular. For example,
1484 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1485 valid replies. Return ``None`` if a string name isn't known. Note that this is
1486 a method rather than a fixed string primarily because some :class:`tzinfo`
1487 subclasses will wish to return different names depending on the specific value
1488 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1489 daylight time.
1490
1491 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1492
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001493
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001494These methods are called by a :class:`.datetime` or :class:`.time` object, in
1495response to their methods of the same names. A :class:`.datetime` object passes
1496itself as the argument, and a :class:`.time` object passes ``None`` as the
Georg Brandl116aa622007-08-15 14:28:22 +00001497argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001498accept a *dt* argument of ``None``, or of class :class:`.datetime`.
Georg Brandl116aa622007-08-15 14:28:22 +00001499
1500When ``None`` is passed, it's up to the class designer to decide the best
1501response. For example, returning ``None`` is appropriate if the class wishes to
1502say that time objects don't participate in the :class:`tzinfo` protocols. It
1503may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1504there is no other convention for discovering the standard offset.
1505
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001506When a :class:`.datetime` object is passed in response to a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +00001507method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1508rely on this, unless user code calls :class:`tzinfo` methods directly. The
1509intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1510time, and not need worry about objects in other timezones.
1511
1512There is one more :class:`tzinfo` method that a subclass may wish to override:
1513
1514
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001515.. method:: tzinfo.fromutc(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001516
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001517 This is called from the default :class:`datetime.astimezone()`
1518 implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s
1519 date and time data are to be viewed as expressing a UTC time. The purpose
1520 of :meth:`fromutc` is to adjust the date and time data, returning an
Senthil Kumarana6bac952011-07-04 11:28:30 -07001521 equivalent datetime in *self*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00001522
1523 Most :class:`tzinfo` subclasses should be able to inherit the default
1524 :meth:`fromutc` implementation without problems. It's strong enough to handle
1525 fixed-offset time zones, and time zones accounting for both standard and
1526 daylight time, and the latter even if the DST transition times differ in
1527 different years. An example of a time zone the default :meth:`fromutc`
1528 implementation may not handle correctly in all cases is one where the standard
1529 offset (from UTC) depends on the specific date and time passed, which can happen
1530 for political reasons. The default implementations of :meth:`astimezone` and
1531 :meth:`fromutc` may not produce the result you want if the result is one of the
1532 hours straddling the moment the standard offset changes.
1533
1534 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1535 like::
1536
1537 def fromutc(self, dt):
1538 # raise ValueError error if dt.tzinfo is not self
1539 dtoff = dt.utcoffset()
1540 dtdst = dt.dst()
1541 # raise ValueError if dtoff is None or dtdst is None
1542 delta = dtoff - dtdst # this is self's standard offset
1543 if delta:
1544 dt += delta # convert to standard local time
1545 dtdst = dt.dst()
1546 # raise ValueError if dtdst is None
1547 if dtdst:
1548 return dt + dtdst
1549 else:
1550 return dt
1551
1552Example :class:`tzinfo` classes:
1553
1554.. literalinclude:: ../includes/tzinfo-examples.py
1555
1556
1557Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1558subclass accounting for both standard and daylight time, at the DST transition
1559points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00001560minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
15611:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001562
1563 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1564 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1565 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1566
1567 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1568
1569 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1570
1571When DST starts (the "start" line), the local wall clock leaps from 1:59 to
15723:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1573``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1574begins. In order for :meth:`astimezone` to make this guarantee, the
1575:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1576Eastern) to be in daylight time.
1577
1578When DST ends (the "end" line), there's a potentially worse problem: there's an
1579hour that can't be spelled unambiguously in local wall time: the last hour of
1580daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1581daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1582to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1583:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1584hours into the same local hour then. In the Eastern example, UTC times of the
1585form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1586:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1587consider times in the "repeated hour" to be in standard time. This is easily
1588arranged, as in the example, by expressing DST switch times in the time zone's
1589standard local time.
1590
1591Applications that can't bear such ambiguities should avoid using hybrid
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001592:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`,
1593or any other fixed-offset :class:`tzinfo` subclass (such as a class representing
1594only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
1595
1596
1597.. _datetime-timezone:
1598
1599:class:`timezone` Objects
1600--------------------------
1601
Alexander Belopolsky6d3c9a62011-05-04 10:28:26 -04001602The :class:`timezone` class is a subclass of :class:`tzinfo`, each
1603instance of which represents a timezone defined by a fixed offset from
1604UTC. Note that objects of this class cannot be used to represent
1605timezone information in the locations where different offsets are used
1606in different days of the year or where historical changes have been
1607made to civil time.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001608
1609
1610.. class:: timezone(offset[, name])
1611
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001612 The *offset* argument must be specified as a :class:`timedelta`
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001613 object representing the difference between the local time and UTC. It must
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001614 be strictly between ``-timedelta(hours=24)`` and
1615 ``timedelta(hours=24)`` and represent a whole number of minutes,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001616 otherwise :exc:`ValueError` is raised.
1617
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001618 The *name* argument is optional. If specified it must be a string that
1619 is used as the value returned by the ``tzname(dt)`` method. Otherwise,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001620 ``tzname(dt)`` returns a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001621 *offset*, HH and MM are two digits of ``offset.hours`` and
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001622 ``offset.minutes`` respectively.
1623
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001624.. method:: timezone.utcoffset(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001625
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001626 Return the fixed value specified when the :class:`timezone` instance is
1627 constructed. The *dt* argument is ignored. The return value is a
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001628 :class:`timedelta` instance equal to the difference between the
1629 local time and UTC.
1630
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001631.. method:: timezone.tzname(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001632
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001633 Return the fixed value specified when the :class:`timezone` instance is
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001634 constructed or a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001635 *offset*, HH and MM are two digits of ``offset.hours`` and
1636 ``offset.minutes`` respectively.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001637
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001638.. method:: timezone.dst(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001639
1640 Always returns ``None``.
1641
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001642.. method:: timezone.fromutc(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001643
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001644 Return ``dt + offset``. The *dt* argument must be an aware
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001645 :class:`.datetime` instance, with ``tzinfo`` set to ``self``.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001646
1647Class attributes:
1648
1649.. attribute:: timezone.utc
1650
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001651 The UTC timezone, ``timezone(timedelta(0))``.
Georg Brandl48310cd2009-01-03 21:18:54 +00001652
Georg Brandl116aa622007-08-15 14:28:22 +00001653
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001654.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00001655
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001656:meth:`strftime` and :meth:`strptime` Behavior
1657----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001658
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001659:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
Georg Brandl116aa622007-08-15 14:28:22 +00001660``strftime(format)`` method, to create a string representing the time under the
1661control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1662acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1663although not all objects support a :meth:`timetuple` method.
1664
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001665Conversely, the :meth:`datetime.strptime` class method creates a
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001666:class:`.datetime` object from a string representing a date and time and a
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001667corresponding format string. ``datetime.strptime(date_string, format)`` is
1668equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1669
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001670For :class:`.time` objects, the format codes for year, month, and day should not
Georg Brandl116aa622007-08-15 14:28:22 +00001671be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001672is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00001673
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001674For :class:`date` objects, the format codes for hours, minutes, seconds, and
1675microseconds should not be used, as :class:`date` objects have no such
1676values. If they're used anyway, ``0`` is substituted for them.
1677
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001678For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1679strings.
1680
1681For an aware object:
1682
1683``%z``
1684 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1685 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1686 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1687 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1688 replaced with the string ``'-0330'``.
1689
1690``%Z``
1691 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1692 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl116aa622007-08-15 14:28:22 +00001693
Georg Brandl116aa622007-08-15 14:28:22 +00001694The full set of format codes supported varies across platforms, because Python
1695calls the platform C library's :func:`strftime` function, and platform
Georg Brandl48310cd2009-01-03 21:18:54 +00001696variations are common.
Christian Heimes895627f2007-12-08 17:28:33 +00001697
1698The following is a list of all the format codes that the C standard (1989
1699version) requires, and these work on all platforms with a standard C
1700implementation. Note that the 1999 version of the C standard added additional
1701format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001702
Christian Heimes895627f2007-12-08 17:28:33 +00001703+-----------+--------------------------------+-------+
1704| Directive | Meaning | Notes |
1705+===========+================================+=======+
1706| ``%a`` | Locale's abbreviated weekday | |
1707| | name. | |
1708+-----------+--------------------------------+-------+
1709| ``%A`` | Locale's full weekday name. | |
1710+-----------+--------------------------------+-------+
1711| ``%b`` | Locale's abbreviated month | |
1712| | name. | |
1713+-----------+--------------------------------+-------+
1714| ``%B`` | Locale's full month name. | |
1715+-----------+--------------------------------+-------+
1716| ``%c`` | Locale's appropriate date and | |
1717| | time representation. | |
1718+-----------+--------------------------------+-------+
1719| ``%d`` | Day of the month as a decimal | |
1720| | number [01,31]. | |
1721+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001722| ``%f`` | Microsecond as a decimal | \(1) |
1723| | number [0,999999], zero-padded | |
1724| | on the left | |
1725+-----------+--------------------------------+-------+
Christian Heimes895627f2007-12-08 17:28:33 +00001726| ``%H`` | Hour (24-hour clock) as a | |
1727| | decimal number [00,23]. | |
1728+-----------+--------------------------------+-------+
1729| ``%I`` | Hour (12-hour clock) as a | |
1730| | decimal number [01,12]. | |
1731+-----------+--------------------------------+-------+
1732| ``%j`` | Day of the year as a decimal | |
1733| | number [001,366]. | |
1734+-----------+--------------------------------+-------+
1735| ``%m`` | Month as a decimal number | |
1736| | [01,12]. | |
1737+-----------+--------------------------------+-------+
1738| ``%M`` | Minute as a decimal number | |
1739| | [00,59]. | |
1740+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001741| ``%p`` | Locale's equivalent of either | \(2) |
Christian Heimes895627f2007-12-08 17:28:33 +00001742| | AM or PM. | |
1743+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001744| ``%S`` | Second as a decimal number | \(3) |
Alexander Belopolsky9971e002011-01-10 22:56:14 +00001745| | [00,59]. | |
Christian Heimes895627f2007-12-08 17:28:33 +00001746+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001747| ``%U`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001748| | (Sunday as the first day of | |
1749| | the week) as a decimal number | |
1750| | [00,53]. All days in a new | |
1751| | year preceding the first | |
1752| | Sunday are considered to be in | |
1753| | week 0. | |
1754+-----------+--------------------------------+-------+
1755| ``%w`` | Weekday as a decimal number | |
1756| | [0(Sunday),6]. | |
1757+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001758| ``%W`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001759| | (Monday as the first day of | |
1760| | the week) as a decimal number | |
1761| | [00,53]. All days in a new | |
1762| | year preceding the first | |
1763| | Monday are considered to be in | |
1764| | week 0. | |
1765+-----------+--------------------------------+-------+
1766| ``%x`` | Locale's appropriate date | |
1767| | representation. | |
1768+-----------+--------------------------------+-------+
1769| ``%X`` | Locale's appropriate time | |
1770| | representation. | |
1771+-----------+--------------------------------+-------+
1772| ``%y`` | Year without century as a | |
1773| | decimal number [00,99]. | |
1774+-----------+--------------------------------+-------+
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001775| ``%Y`` | Year with century as a decimal | \(5) |
Alexander Belopolsky89da3492011-05-02 13:14:24 -04001776| | number [0001,9999]. | |
Christian Heimes895627f2007-12-08 17:28:33 +00001777+-----------+--------------------------------+-------+
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001778| ``%z`` | UTC offset in the form +HHMM | \(6) |
Christian Heimes895627f2007-12-08 17:28:33 +00001779| | or -HHMM (empty string if the | |
1780| | the object is naive). | |
1781+-----------+--------------------------------+-------+
1782| ``%Z`` | Time zone name (empty string | |
1783| | if the object is naive). | |
1784+-----------+--------------------------------+-------+
1785| ``%%`` | A literal ``'%'`` character. | |
1786+-----------+--------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001787
Christian Heimes895627f2007-12-08 17:28:33 +00001788Notes:
1789
1790(1)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001791 When used with the :meth:`strptime` method, the ``%f`` directive
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001792 accepts from one to six digits and zero pads on the right. ``%f`` is
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001793 an extension to the set of format characters in the C standard (but
1794 implemented separately in datetime objects, and therefore always
1795 available).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001796
1797(2)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001798 When used with the :meth:`strptime` method, the ``%p`` directive only affects
Christian Heimes895627f2007-12-08 17:28:33 +00001799 the output hour field if the ``%I`` directive is used to parse the hour.
1800
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001801(3)
Alexander Belopolsky9971e002011-01-10 22:56:14 +00001802 Unlike :mod:`time` module, :mod:`datetime` module does not support
1803 leap seconds.
Christian Heimes895627f2007-12-08 17:28:33 +00001804
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001805(4)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001806 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in
Christian Heimes895627f2007-12-08 17:28:33 +00001807 calculations when the day of the week and the year are specified.
1808
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001809(5)
Alexander Belopolsky89da3492011-05-02 13:14:24 -04001810 The :meth:`strptime` method can
Alexander Belopolsky5fc850b2011-01-10 23:31:51 +00001811 parse years in the full [1, 9999] range, but years < 1000 must be
1812 zero-filled to 4-digit width.
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001813
1814 .. versionchanged:: 3.2
1815 In previous versions, :meth:`strftime` method was restricted to
1816 years >= 1900.
1817
Alexander Belopolsky5611a1c2011-05-02 14:14:48 -04001818 .. versionchanged:: 3.3
1819 In version 3.2, :meth:`strftime` method was restricted to
1820 years >= 1000.
1821
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001822(6)
Christian Heimes895627f2007-12-08 17:28:33 +00001823 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1824 ``%z`` is replaced with the string ``'-0330'``.
Alexander Belopolskyca94f552010-06-17 18:30:34 +00001825
Georg Brandl67b21b72010-08-17 15:07:14 +00001826.. versionchanged:: 3.2
1827 When the ``%z`` directive is provided to the :meth:`strptime` method, an
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001828 aware :class:`.datetime` object will be produced. The ``tzinfo`` of the
Georg Brandl67b21b72010-08-17 15:07:14 +00001829 result will be set to a :class:`timezone` instance.