blob: d16551e713ac2e070b3269f5dd95fe75a7a08c5e [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
407 :c:func:`localtime` function.
408
Georg Brandl116aa622007-08-15 14:28:22 +0000409
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000410.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000411
412 Return the date corresponding to the proleptic Gregorian ordinal, where January
413 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
414 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
415 d``.
416
Georg Brandl116aa622007-08-15 14:28:22 +0000417
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000418Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000419
420.. attribute:: date.min
421
422 The earliest representable date, ``date(MINYEAR, 1, 1)``.
423
424
425.. attribute:: date.max
426
427 The latest representable date, ``date(MAXYEAR, 12, 31)``.
428
429
430.. attribute:: date.resolution
431
432 The smallest possible difference between non-equal date objects,
433 ``timedelta(days=1)``.
434
Georg Brandl116aa622007-08-15 14:28:22 +0000435
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000436Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000437
438.. attribute:: date.year
439
440 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
441
442
443.. attribute:: date.month
444
445 Between 1 and 12 inclusive.
446
447
448.. attribute:: date.day
449
450 Between 1 and the number of days in the given month of the given year.
451
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000452
Georg Brandl116aa622007-08-15 14:28:22 +0000453Supported operations:
454
455+-------------------------------+----------------------------------------------+
456| Operation | Result |
457+===============================+==============================================+
458| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
459| | from *date1*. (1) |
460+-------------------------------+----------------------------------------------+
461| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
462| | timedelta == date1``. (2) |
463+-------------------------------+----------------------------------------------+
464| ``timedelta = date1 - date2`` | \(3) |
465+-------------------------------+----------------------------------------------+
466| ``date1 < date2`` | *date1* is considered less than *date2* when |
467| | *date1* precedes *date2* in time. (4) |
468+-------------------------------+----------------------------------------------+
469
470Notes:
471
472(1)
473 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
474 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
475 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
476 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
477 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
478
479(2)
480 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
481 isolation can overflow in cases where date1 - timedelta does not.
482 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
483
484(3)
485 This is exact, and cannot overflow. timedelta.seconds and
486 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
487
488(4)
489 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
490 date2.toordinal()``. In order to stop comparison from falling back to the
491 default scheme of comparing object addresses, date comparison normally raises
492 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
493 However, ``NotImplemented`` is returned instead if the other comparand has a
494 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
495 chance at implementing mixed-type comparison. If not, when a :class:`date`
496 object is compared to an object of a different type, :exc:`TypeError` is raised
497 unless the comparison is ``==`` or ``!=``. The latter cases return
498 :const:`False` or :const:`True`, respectively.
499
500Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
501objects are considered to be true.
502
503Instance methods:
504
Georg Brandl116aa622007-08-15 14:28:22 +0000505.. method:: date.replace(year, month, day)
506
Senthil Kumarana6bac952011-07-04 11:28:30 -0700507 Return a date with the same value, except for those parameters given new
508 values by whichever keyword arguments are specified. For example, if ``d ==
509 date(2002, 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000510
511
512.. method:: date.timetuple()
513
514 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
515 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
516 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000517 d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1,
518 1).toordinal() + 1`` is the day number within the current year starting with
519 ``1`` for January 1st.
Georg Brandl116aa622007-08-15 14:28:22 +0000520
521
522.. method:: date.toordinal()
523
524 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
525 has ordinal 1. For any :class:`date` object *d*,
526 ``date.fromordinal(d.toordinal()) == d``.
527
528
529.. method:: date.weekday()
530
531 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
532 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
533 :meth:`isoweekday`.
534
535
536.. method:: date.isoweekday()
537
538 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
539 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
540 :meth:`weekday`, :meth:`isocalendar`.
541
542
543.. method:: date.isocalendar()
544
545 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
546
547 The ISO calendar is a widely used variant of the Gregorian calendar. See
Mark Dickinsonf964ac22009-11-03 16:29:10 +0000548 http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
549 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000550
551 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
552 Monday and ends on a Sunday. The first week of an ISO year is the first
553 (Gregorian) calendar week of a year containing a Thursday. This is called week
554 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
555
556 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
557 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
558 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
559 4).isocalendar() == (2004, 1, 7)``.
560
561
562.. method:: date.isoformat()
563
564 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
565 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
566
567
568.. method:: date.__str__()
569
570 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
571
572
573.. method:: date.ctime()
574
575 Return a string representing the date, for example ``date(2002, 12,
576 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
577 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
Georg Brandl60203b42010-10-06 10:11:56 +0000578 :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +0000579 :meth:`date.ctime` does not invoke) conforms to the C standard.
580
581
582.. method:: date.strftime(format)
583
584 Return a string representing the date, controlled by an explicit format string.
585 Format codes referring to hours, minutes or seconds will see 0 values. See
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000586 section :ref:`strftime-strptime-behavior`.
587
Georg Brandl116aa622007-08-15 14:28:22 +0000588
Christian Heimes895627f2007-12-08 17:28:33 +0000589Example of counting days to an event::
590
591 >>> import time
592 >>> from datetime import date
593 >>> today = date.today()
594 >>> today
595 datetime.date(2007, 12, 5)
596 >>> today == date.fromtimestamp(time.time())
597 True
598 >>> my_birthday = date(today.year, 6, 24)
599 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000600 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000601 >>> my_birthday
602 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000603 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000604 >>> time_to_birthday.days
605 202
606
Christian Heimesfe337bf2008-03-23 21:54:12 +0000607Example of working with :class:`date`:
608
609.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000610
611 >>> from datetime import date
612 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
613 >>> d
614 datetime.date(2002, 3, 11)
615 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000616 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000617 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000618 2002 # year
619 3 # month
620 11 # day
621 0
622 0
623 0
624 0 # weekday (0 = Monday)
625 70 # 70th day in the year
626 -1
627 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000628 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000629 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000630 2002 # ISO year
631 11 # ISO week number
632 1 # ISO day number ( 1 = Monday )
633 >>> d.isoformat()
634 '2002-03-11'
635 >>> d.strftime("%d/%m/%y")
636 '11/03/02'
637 >>> d.strftime("%A %d. %B %Y")
638 'Monday 11. March 2002'
639
Georg Brandl116aa622007-08-15 14:28:22 +0000640
641.. _datetime-datetime:
642
643:class:`datetime` Objects
644-------------------------
645
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300646A :class:`.datetime` object is a single object containing all the information
647from a :class:`date` object and a :class:`.time` object. Like a :class:`date`
648object, :class:`.datetime` assumes the current Gregorian calendar extended in
649both directions; like a time object, :class:`.datetime` assumes there are exactly
Georg Brandl116aa622007-08-15 14:28:22 +00006503600\*24 seconds in every day.
651
652Constructor:
653
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000654.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000655
656 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000657 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
658 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000659
660 * ``MINYEAR <= year <= MAXYEAR``
661 * ``1 <= month <= 12``
662 * ``1 <= day <= number of days in the given month and year``
663 * ``0 <= hour < 24``
664 * ``0 <= minute < 60``
665 * ``0 <= second < 60``
666 * ``0 <= microsecond < 1000000``
667
668 If an argument outside those ranges is given, :exc:`ValueError` is raised.
669
670Other constructors, all class methods:
671
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000672.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000673
674 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
675 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
676 :meth:`fromtimestamp`.
677
678
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000679.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000680
681 Return the current local date and time. If optional argument *tz* is ``None``
682 or not specified, this is like :meth:`today`, but, if possible, supplies more
683 precision than can be gotten from going through a :func:`time.time` timestamp
684 (for example, this may be possible on platforms supplying the C
Georg Brandl60203b42010-10-06 10:11:56 +0000685 :c:func:`gettimeofday` function).
Georg Brandl116aa622007-08-15 14:28:22 +0000686
687 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
688 current date and time are converted to *tz*'s time zone. In this case the
689 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
690 See also :meth:`today`, :meth:`utcnow`.
691
692
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000693.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000694
695 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
696 :meth:`now`, but returns the current UTC date and time, as a naive
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300697 :class:`.datetime` object. An aware current UTC datetime can be obtained by
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000698 calling ``datetime.now(timezone.utc)``. See also :meth:`now`.
Georg Brandl116aa622007-08-15 14:28:22 +0000699
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000700.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000701
702 Return the local date and time corresponding to the POSIX timestamp, such as is
703 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
704 specified, the timestamp is converted to the platform's local date and time, and
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300705 the returned :class:`.datetime` object is naive.
Georg Brandl116aa622007-08-15 14:28:22 +0000706
707 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
708 timestamp is converted to *tz*'s time zone. In this case the result is
709 equivalent to
710 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
711
712 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
Georg Brandl60203b42010-10-06 10:11:56 +0000713 the range of values supported by the platform C :c:func:`localtime` or
714 :c:func:`gmtime` functions. It's common for this to be restricted to years in
Georg Brandl116aa622007-08-15 14:28:22 +0000715 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
716 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
717 and then it's possible to have two timestamps differing by a second that yield
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300718 identical :class:`.datetime` objects. See also :meth:`utcfromtimestamp`.
Georg Brandl116aa622007-08-15 14:28:22 +0000719
Victor Stinner5d272cc2012-03-13 13:35:55 +0100720 .. versionchanged:: 3.3
721 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
722 is out of the range of values supported by the platform C
723 :c:func:`localtime` or :c:func:`gmtime` functions
724
Georg Brandl116aa622007-08-15 14:28:22 +0000725
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000726.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000727
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300728 Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with
Georg Brandl116aa622007-08-15 14:28:22 +0000729 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
Georg Brandl60203b42010-10-06 10:11:56 +0000730 out of the range of values supported by the platform C :c:func:`gmtime` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000731 It's common for this to be restricted to years in 1970 through 2038. See also
732 :meth:`fromtimestamp`.
733
Alexander Belopolsky54afa552011-04-25 13:00:40 -0400734 On the POSIX compliant platforms, ``utcfromtimestamp(timestamp)``
735 is equivalent to the following expression::
736
737 datetime(1970, 1, 1) + timedelta(seconds=timestamp)
738
739 There is no method to obtain the timestamp from a :class:`datetime`
740 instance, but POSIX timestamp corresponding to a :class:`datetime`
741 instance ``dt`` can be easily calculated as follows. For a naive
742 ``dt``::
743
744 timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
745
746 And for an aware ``dt``::
747
748 timestamp = (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)) / timedelta(seconds=1)
749
Victor Stinner5d272cc2012-03-13 13:35:55 +0100750 .. versionchanged:: 3.3
751 Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp
752 is out of the range of values supported by the platform C
753 :c:func:`gmtime` function.
754
Georg Brandl116aa622007-08-15 14:28:22 +0000755
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000756.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000757
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300758 Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal,
Georg Brandl116aa622007-08-15 14:28:22 +0000759 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
760 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
761 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
762
763
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000764.. classmethod:: datetime.combine(date, time)
Georg Brandl116aa622007-08-15 14:28:22 +0000765
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300766 Return a new :class:`.datetime` object whose date components are equal to the
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800767 given :class:`date` object's, and whose time components and :attr:`tzinfo`
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300768 attributes are equal to the given :class:`.time` object's. For any
769 :class:`.datetime` object *d*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800770 ``d == datetime.combine(d.date(), d.timetz())``. If date is a
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300771 :class:`.datetime` object, its time components and :attr:`tzinfo` attributes
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800772 are ignored.
Georg Brandl116aa622007-08-15 14:28:22 +0000773
774
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000775.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000776
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300777 Return a :class:`.datetime` corresponding to *date_string*, parsed according to
Georg Brandl116aa622007-08-15 14:28:22 +0000778 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
779 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
780 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 +0000781 time tuple. See section :ref:`strftime-strptime-behavior`.
782
Georg Brandl116aa622007-08-15 14:28:22 +0000783
Georg Brandl116aa622007-08-15 14:28:22 +0000784
785Class attributes:
786
Georg Brandl116aa622007-08-15 14:28:22 +0000787.. attribute:: datetime.min
788
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300789 The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1,
Georg Brandl116aa622007-08-15 14:28:22 +0000790 tzinfo=None)``.
791
792
793.. attribute:: datetime.max
794
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300795 The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
Georg Brandl116aa622007-08-15 14:28:22 +0000796 59, 999999, tzinfo=None)``.
797
798
799.. attribute:: datetime.resolution
800
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300801 The smallest possible difference between non-equal :class:`.datetime` objects,
Georg Brandl116aa622007-08-15 14:28:22 +0000802 ``timedelta(microseconds=1)``.
803
Georg Brandl116aa622007-08-15 14:28:22 +0000804
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000805Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000806
807.. attribute:: datetime.year
808
809 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
810
811
812.. attribute:: datetime.month
813
814 Between 1 and 12 inclusive.
815
816
817.. attribute:: datetime.day
818
819 Between 1 and the number of days in the given month of the given year.
820
821
822.. attribute:: datetime.hour
823
824 In ``range(24)``.
825
826
827.. attribute:: datetime.minute
828
829 In ``range(60)``.
830
831
832.. attribute:: datetime.second
833
834 In ``range(60)``.
835
836
837.. attribute:: datetime.microsecond
838
839 In ``range(1000000)``.
840
841
842.. attribute:: datetime.tzinfo
843
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300844 The object passed as the *tzinfo* argument to the :class:`.datetime` constructor,
Georg Brandl116aa622007-08-15 14:28:22 +0000845 or ``None`` if none was passed.
846
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000847
Georg Brandl116aa622007-08-15 14:28:22 +0000848Supported operations:
849
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300850+---------------------------------------+--------------------------------+
851| Operation | Result |
852+=======================================+================================+
853| ``datetime2 = datetime1 + timedelta`` | \(1) |
854+---------------------------------------+--------------------------------+
855| ``datetime2 = datetime1 - timedelta`` | \(2) |
856+---------------------------------------+--------------------------------+
857| ``timedelta = datetime1 - datetime2`` | \(3) |
858+---------------------------------------+--------------------------------+
859| ``datetime1 < datetime2`` | Compares :class:`.datetime` to |
860| | :class:`.datetime`. (4) |
861+---------------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000862
863(1)
864 datetime2 is a duration of timedelta removed from datetime1, moving forward in
865 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
Senthil Kumarana6bac952011-07-04 11:28:30 -0700866 result has the same :attr:`tzinfo` attribute as the input datetime, and
867 datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
868 datetime2.year would be smaller than :const:`MINYEAR` or larger than
869 :const:`MAXYEAR`. Note that no time zone adjustments are done even if the
870 input is an aware object.
Georg Brandl116aa622007-08-15 14:28:22 +0000871
872(2)
873 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
Senthil Kumarana6bac952011-07-04 11:28:30 -0700874 addition, the result has the same :attr:`tzinfo` attribute as the input
875 datetime, and no time zone adjustments are done even if the input is aware.
876 This isn't quite equivalent to datetime1 + (-timedelta), because -timedelta
877 in isolation can overflow in cases where datetime1 - timedelta does not.
Georg Brandl116aa622007-08-15 14:28:22 +0000878
879(3)
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300880 Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if
Georg Brandl116aa622007-08-15 14:28:22 +0000881 both operands are naive, or if both are aware. If one is aware and the other is
882 naive, :exc:`TypeError` is raised.
883
Senthil Kumarana6bac952011-07-04 11:28:30 -0700884 If both are naive, or both are aware and have the same :attr:`tzinfo` attribute,
885 the :attr:`tzinfo` attributes are ignored, and the result is a :class:`timedelta`
Georg Brandl116aa622007-08-15 14:28:22 +0000886 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
887 are done in this case.
888
Senthil Kumarana6bac952011-07-04 11:28:30 -0700889 If both are aware and have different :attr:`tzinfo` attributes, ``a-b`` acts
890 as if *a* and *b* were first converted to naive UTC datetimes first. The
891 result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
892 - b.utcoffset())`` except that the implementation never overflows.
Georg Brandl116aa622007-08-15 14:28:22 +0000893
894(4)
895 *datetime1* is considered less than *datetime2* when *datetime1* precedes
896 *datetime2* in time.
897
898 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
Senthil Kumarana6bac952011-07-04 11:28:30 -0700899 If both comparands are aware, and have the same :attr:`tzinfo` attribute, the
900 common :attr:`tzinfo` attribute is ignored and the base datetimes are
901 compared. If both comparands are aware and have different :attr:`tzinfo`
902 attributes, the comparands are first adjusted by subtracting their UTC
903 offsets (obtained from ``self.utcoffset()``).
Georg Brandl116aa622007-08-15 14:28:22 +0000904
905 .. note::
906
907 In order to stop comparison from falling back to the default scheme of comparing
908 object addresses, datetime comparison normally raises :exc:`TypeError` if the
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300909 other comparand isn't also a :class:`.datetime` object. However,
Georg Brandl116aa622007-08-15 14:28:22 +0000910 ``NotImplemented`` is returned instead if the other comparand has a
911 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300912 chance at implementing mixed-type comparison. If not, when a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +0000913 object is compared to an object of a different type, :exc:`TypeError` is raised
914 unless the comparison is ``==`` or ``!=``. The latter cases return
915 :const:`False` or :const:`True`, respectively.
916
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300917:class:`.datetime` objects can be used as dictionary keys. In Boolean contexts,
918all :class:`.datetime` objects are considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +0000919
920Instance methods:
921
Georg Brandl116aa622007-08-15 14:28:22 +0000922.. method:: datetime.date()
923
924 Return :class:`date` object with same year, month and day.
925
926
927.. method:: datetime.time()
928
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300929 Return :class:`.time` object with same hour, minute, second and microsecond.
Georg Brandl116aa622007-08-15 14:28:22 +0000930 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
931
932
933.. method:: datetime.timetz()
934
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300935 Return :class:`.time` object with same hour, minute, second, microsecond, and
Senthil Kumarana6bac952011-07-04 11:28:30 -0700936 tzinfo attributes. See also method :meth:`time`.
Georg Brandl116aa622007-08-15 14:28:22 +0000937
938
939.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
940
Senthil Kumarana6bac952011-07-04 11:28:30 -0700941 Return a datetime with the same attributes, except for those attributes given
942 new values by whichever keyword arguments are specified. Note that
943 ``tzinfo=None`` can be specified to create a naive datetime from an aware
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800944 datetime with no conversion of date and time data.
Georg Brandl116aa622007-08-15 14:28:22 +0000945
946
947.. method:: datetime.astimezone(tz)
948
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300949 Return a :class:`.datetime` object with new :attr:`tzinfo` attribute *tz*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800950 adjusting the date and time data so the result is the same UTC time as
Senthil Kumarana6bac952011-07-04 11:28:30 -0700951 *self*, but in *tz*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +0000952
953 *tz* must be an instance of a :class:`tzinfo` subclass, and its
954 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
955 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
956 not return ``None``).
957
958 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800959 adjustment of date or time data is performed. Else the result is local
Senthil Kumarana6bac952011-07-04 11:28:30 -0700960 time in time zone *tz*, representing the same UTC time as *self*: after
961 ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800962 the same date and time data as ``dt - dt.utcoffset()``. The discussion
Senthil Kumarana6bac952011-07-04 11:28:30 -0700963 of class :class:`tzinfo` explains the cases at Daylight Saving Time transition
964 boundaries where this cannot be achieved (an issue only if *tz* models both
965 standard and daylight time).
Georg Brandl116aa622007-08-15 14:28:22 +0000966
967 If you merely want to attach a time zone object *tz* to a datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800968 adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you
Georg Brandl116aa622007-08-15 14:28:22 +0000969 merely want to remove the time zone object from an aware datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800970 conversion of date and time data, use ``dt.replace(tzinfo=None)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000971
972 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
973 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
974 Ignoring error cases, :meth:`astimezone` acts like::
975
976 def astimezone(self, tz):
977 if self.tzinfo is tz:
978 return self
979 # Convert self to UTC, and attach the new time zone object.
980 utc = (self - self.utcoffset()).replace(tzinfo=tz)
981 # Convert from UTC to tz's local time.
982 return tz.fromutc(utc)
983
984
985.. method:: datetime.utcoffset()
986
987 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
988 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
989 return ``None``, or a :class:`timedelta` object representing a whole number of
990 minutes with magnitude less than one day.
991
992
993.. method:: datetime.dst()
994
995 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
996 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
997 ``None``, or a :class:`timedelta` object representing a whole number of minutes
998 with magnitude less than one day.
999
1000
1001.. method:: datetime.tzname()
1002
1003 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1004 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
1005 ``None`` or a string object,
1006
1007
1008.. method:: datetime.timetuple()
1009
1010 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
1011 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
Alexander Belopolsky64912482010-06-08 18:59:20 +00001012 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
1013 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
1014 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
1015 of the result is set according to the :meth:`dst` method: :attr:`tzinfo` is
Georg Brandl682d7e02010-10-06 10:26:05 +00001016 ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
Alexander Belopolsky64912482010-06-08 18:59:20 +00001017 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
Alexander Belopolskyda62f2f2010-06-09 17:11:01 +00001018 else :attr:`tm_isdst` is set to ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +00001019
1020
1021.. method:: datetime.utctimetuple()
1022
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001023 If :class:`.datetime` instance *d* is naive, this is the same as
Georg Brandl116aa622007-08-15 14:28:22 +00001024 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
1025 ``d.dst()`` returns. DST is never in effect for a UTC time.
1026
1027 If *d* is aware, *d* is normalized to UTC time, by subtracting
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00001028 ``d.utcoffset()``, and a :class:`time.struct_time` for the
1029 normalized time is returned. :attr:`tm_isdst` is forced to 0. Note
1030 that an :exc:`OverflowError` may be raised if *d*.year was
1031 ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
Georg Brandl116aa622007-08-15 14:28:22 +00001032 boundary.
1033
1034
1035.. method:: datetime.toordinal()
1036
1037 Return the proleptic Gregorian ordinal of the date. The same as
1038 ``self.date().toordinal()``.
1039
1040
1041.. method:: datetime.weekday()
1042
1043 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
1044 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
1045
1046
1047.. method:: datetime.isoweekday()
1048
1049 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
1050 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
1051 :meth:`isocalendar`.
1052
1053
1054.. method:: datetime.isocalendar()
1055
1056 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
1057 ``self.date().isocalendar()``.
1058
1059
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001060.. method:: datetime.isoformat(sep='T')
Georg Brandl116aa622007-08-15 14:28:22 +00001061
1062 Return a string representing the date and time in ISO 8601 format,
1063 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
1064 YYYY-MM-DDTHH:MM:SS
1065
1066 If :meth:`utcoffset` does not return ``None``, a 6-character string is
1067 appended, giving the UTC offset in (signed) hours and minutes:
1068 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
1069 YYYY-MM-DDTHH:MM:SS+HH:MM
1070
1071 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +00001072 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +00001073
1074 >>> from datetime import tzinfo, timedelta, datetime
1075 >>> class TZ(tzinfo):
1076 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1077 ...
1078 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1079 '2002-12-25 00:00:00-06:39'
1080
1081
1082.. method:: datetime.__str__()
1083
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001084 For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to
Georg Brandl116aa622007-08-15 14:28:22 +00001085 ``d.isoformat(' ')``.
1086
1087
1088.. method:: datetime.ctime()
1089
1090 Return a string representing the date and time, for example ``datetime(2002, 12,
1091 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1092 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
Georg Brandl60203b42010-10-06 10:11:56 +00001093 native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +00001094 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1095
1096
1097.. method:: datetime.strftime(format)
1098
1099 Return a string representing the date and time, controlled by an explicit format
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001100 string. See section :ref:`strftime-strptime-behavior`.
1101
Georg Brandl116aa622007-08-15 14:28:22 +00001102
Christian Heimesfe337bf2008-03-23 21:54:12 +00001103Examples of working with datetime objects:
1104
1105.. doctest::
1106
Christian Heimes895627f2007-12-08 17:28:33 +00001107 >>> from datetime import datetime, date, time
1108 >>> # Using datetime.combine()
1109 >>> d = date(2005, 7, 14)
1110 >>> t = time(12, 30)
1111 >>> datetime.combine(d, t)
1112 datetime.datetime(2005, 7, 14, 12, 30)
1113 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001114 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001115 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001116 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001117 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1118 >>> # Using datetime.strptime()
1119 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1120 >>> dt
1121 datetime.datetime(2006, 11, 21, 16, 30)
1122 >>> # Using datetime.timetuple() to get tuple of all attributes
1123 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001124 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001125 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001126 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001127 2006 # year
1128 11 # month
1129 21 # day
1130 16 # hour
1131 30 # minute
1132 0 # second
1133 1 # weekday (0 = Monday)
1134 325 # number of days since 1st January
1135 -1 # dst - method tzinfo.dst() returned None
1136 >>> # Date in ISO format
1137 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001138 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001139 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001140 ...
1141 2006 # ISO year
1142 47 # ISO week
1143 2 # ISO weekday
1144 >>> # Formatting datetime
1145 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1146 'Tuesday, 21. November 2006 04:30PM'
1147
Christian Heimesfe337bf2008-03-23 21:54:12 +00001148Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001149
1150 >>> from datetime import timedelta, datetime, tzinfo
1151 >>> class GMT1(tzinfo):
1152 ... def __init__(self): # DST starts last Sunday in March
1153 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1154 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001155 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001156 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1157 ... def utcoffset(self, dt):
1158 ... return timedelta(hours=1) + self.dst(dt)
Georg Brandl48310cd2009-01-03 21:18:54 +00001159 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001160 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1161 ... return timedelta(hours=1)
1162 ... else:
1163 ... return timedelta(0)
1164 ... def tzname(self,dt):
1165 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001166 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001167 >>> class GMT2(tzinfo):
1168 ... def __init__(self):
Georg Brandl48310cd2009-01-03 21:18:54 +00001169 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001170 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001171 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001172 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1173 ... def utcoffset(self, dt):
1174 ... return timedelta(hours=1) + self.dst(dt)
1175 ... def dst(self, dt):
1176 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1177 ... return timedelta(hours=2)
1178 ... else:
1179 ... return timedelta(0)
1180 ... def tzname(self,dt):
1181 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001182 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001183 >>> gmt1 = GMT1()
1184 >>> # Daylight Saving Time
1185 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1186 >>> dt1.dst()
1187 datetime.timedelta(0)
1188 >>> dt1.utcoffset()
1189 datetime.timedelta(0, 3600)
1190 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1191 >>> dt2.dst()
1192 datetime.timedelta(0, 3600)
1193 >>> dt2.utcoffset()
1194 datetime.timedelta(0, 7200)
1195 >>> # Convert datetime to another time zone
1196 >>> dt3 = dt2.astimezone(GMT2())
1197 >>> dt3 # doctest: +ELLIPSIS
1198 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1199 >>> dt2 # doctest: +ELLIPSIS
1200 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1201 >>> dt2.utctimetuple() == dt3.utctimetuple()
1202 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001203
Christian Heimes895627f2007-12-08 17:28:33 +00001204
Georg Brandl116aa622007-08-15 14:28:22 +00001205
1206.. _datetime-time:
1207
1208:class:`time` Objects
1209---------------------
1210
1211A time object represents a (local) time of day, independent of any particular
1212day, and subject to adjustment via a :class:`tzinfo` object.
1213
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001214.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001215
1216 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001217 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001218 following ranges:
1219
1220 * ``0 <= hour < 24``
1221 * ``0 <= minute < 60``
1222 * ``0 <= second < 60``
1223 * ``0 <= microsecond < 1000000``.
1224
1225 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1226 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1227
1228Class attributes:
1229
1230
1231.. attribute:: time.min
1232
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001233 The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001234
1235
1236.. attribute:: time.max
1237
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001238 The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001239
1240
1241.. attribute:: time.resolution
1242
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001243 The smallest possible difference between non-equal :class:`.time` objects,
1244 ``timedelta(microseconds=1)``, although note that arithmetic on
1245 :class:`.time` objects is not supported.
Georg Brandl116aa622007-08-15 14:28:22 +00001246
Georg Brandl116aa622007-08-15 14:28:22 +00001247
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001248Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001249
1250.. attribute:: time.hour
1251
1252 In ``range(24)``.
1253
1254
1255.. attribute:: time.minute
1256
1257 In ``range(60)``.
1258
1259
1260.. attribute:: time.second
1261
1262 In ``range(60)``.
1263
1264
1265.. attribute:: time.microsecond
1266
1267 In ``range(1000000)``.
1268
1269
1270.. attribute:: time.tzinfo
1271
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001272 The object passed as the tzinfo argument to the :class:`.time` constructor, or
Georg Brandl116aa622007-08-15 14:28:22 +00001273 ``None`` if none was passed.
1274
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001275
Georg Brandl116aa622007-08-15 14:28:22 +00001276Supported operations:
1277
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001278* comparison of :class:`.time` to :class:`.time`, where *a* is considered less
Georg Brandl116aa622007-08-15 14:28:22 +00001279 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1280 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
Senthil Kumarana6bac952011-07-04 11:28:30 -07001281 the same :attr:`tzinfo` attribute, the common :attr:`tzinfo` attribute is
1282 ignored and the base times are compared. If both comparands are aware and
1283 have different :attr:`tzinfo` attributes, the comparands are first adjusted by
1284 subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
1285 to stop mixed-type comparisons from falling back to the default comparison by
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001286 object address, when a :class:`.time` object is compared to an object of a
Senthil Kumaran3aac1792011-07-04 11:43:51 -07001287 different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
Senthil Kumarana6bac952011-07-04 11:28:30 -07001288 ``!=``. The latter cases return :const:`False` or :const:`True`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +00001289
1290* hash, use as dict key
1291
1292* efficient pickling
1293
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001294* in Boolean contexts, a :class:`.time` object is considered to be true if and
Georg Brandl116aa622007-08-15 14:28:22 +00001295 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1296 ``0`` if that's ``None``), the result is non-zero.
1297
Georg Brandl116aa622007-08-15 14:28:22 +00001298
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001299Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001300
1301.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1302
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001303 Return a :class:`.time` with the same value, except for those attributes given
Senthil Kumarana6bac952011-07-04 11:28:30 -07001304 new values by whichever keyword arguments are specified. Note that
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001305 ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
1306 aware :class:`.time`, without conversion of the time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001307
1308
1309.. method:: time.isoformat()
1310
1311 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1312 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1313 6-character string is appended, giving the UTC offset in (signed) hours and
1314 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1315
1316
1317.. method:: time.__str__()
1318
1319 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1320
1321
1322.. method:: time.strftime(format)
1323
1324 Return a string representing the time, controlled by an explicit format string.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001325 See section :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001326
1327
1328.. method:: time.utcoffset()
1329
1330 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1331 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1332 return ``None`` or a :class:`timedelta` object representing a whole number of
1333 minutes with magnitude less than one day.
1334
1335
1336.. method:: time.dst()
1337
1338 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1339 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1340 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1341 with magnitude less than one day.
1342
1343
1344.. method:: time.tzname()
1345
1346 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1347 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1348 return ``None`` or a string object.
1349
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001350
Christian Heimesfe337bf2008-03-23 21:54:12 +00001351Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001352
Christian Heimes895627f2007-12-08 17:28:33 +00001353 >>> from datetime import time, tzinfo
1354 >>> class GMT1(tzinfo):
1355 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001356 ... return timedelta(hours=1)
1357 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001358 ... return timedelta(0)
1359 ... def tzname(self,dt):
1360 ... return "Europe/Prague"
1361 ...
1362 >>> t = time(12, 10, 30, tzinfo=GMT1())
1363 >>> t # doctest: +ELLIPSIS
1364 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1365 >>> gmt = GMT1()
1366 >>> t.isoformat()
1367 '12:10:30+01:00'
1368 >>> t.dst()
1369 datetime.timedelta(0)
1370 >>> t.tzname()
1371 'Europe/Prague'
1372 >>> t.strftime("%H:%M:%S %Z")
1373 '12:10:30 Europe/Prague'
1374
Georg Brandl116aa622007-08-15 14:28:22 +00001375
1376.. _datetime-tzinfo:
1377
1378:class:`tzinfo` Objects
1379-----------------------
1380
Brett Cannone1327f72009-01-29 04:10:21 +00001381:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001382instantiated directly. You need to derive a concrete subclass, and (at least)
1383supply implementations of the standard :class:`tzinfo` methods needed by the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001384:class:`.datetime` methods you use. The :mod:`datetime` module supplies
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001385a simple concrete subclass of :class:`tzinfo` :class:`timezone` which can reprsent
1386timezones with fixed offset from UTC such as UTC itself or North American EST and
1387EDT.
Georg Brandl116aa622007-08-15 14:28:22 +00001388
1389An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001390constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
Senthil Kumarana6bac952011-07-04 11:28:30 -07001391view their attributes as being in local time, and the :class:`tzinfo` object
Georg Brandl116aa622007-08-15 14:28:22 +00001392supports methods revealing offset of local time from UTC, the name of the time
1393zone, and DST offset, all relative to a date or time object passed to them.
1394
1395Special requirement for pickling: A :class:`tzinfo` subclass must have an
1396:meth:`__init__` method that can be called with no arguments, else it can be
1397pickled but possibly not unpickled again. This is a technical requirement that
1398may be relaxed in the future.
1399
1400A concrete subclass of :class:`tzinfo` may need to implement the following
1401methods. Exactly which methods are needed depends on the uses made of aware
1402:mod:`datetime` objects. If in doubt, simply implement all of them.
1403
1404
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001405.. method:: tzinfo.utcoffset(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001406
1407 Return offset of local time from UTC, in minutes east of UTC. If local time is
1408 west of UTC, this should be negative. Note that this is intended to be the
1409 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1410 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1411 the UTC offset isn't known, return ``None``. Else the value returned must be a
1412 :class:`timedelta` object specifying a whole number of minutes in the range
1413 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1414 than one day). Most implementations of :meth:`utcoffset` will probably look
1415 like one of these two::
1416
1417 return CONSTANT # fixed-offset class
1418 return CONSTANT + self.dst(dt) # daylight-aware class
1419
1420 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1421 ``None`` either.
1422
1423 The default implementation of :meth:`utcoffset` raises
1424 :exc:`NotImplementedError`.
1425
1426
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001427.. method:: tzinfo.dst(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001428
1429 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1430 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1431 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1432 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1433 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1434 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1435 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -07001436 attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
1437 should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
1438 DST changes when crossing time zones.
Georg Brandl116aa622007-08-15 14:28:22 +00001439
1440 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1441 daylight times must be consistent in this sense:
1442
1443 ``tz.utcoffset(dt) - tz.dst(dt)``
1444
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001445 must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo ==
Georg Brandl116aa622007-08-15 14:28:22 +00001446 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1447 zone's "standard offset", which should not depend on the date or the time, but
1448 only on geographic location. The implementation of :meth:`datetime.astimezone`
1449 relies on this, but cannot detect violations; it's the programmer's
1450 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1451 this, it may be able to override the default implementation of
1452 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1453
1454 Most implementations of :meth:`dst` will probably look like one of these two::
1455
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001456 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001457 # a fixed-offset class: doesn't account for DST
1458 return timedelta(0)
1459
1460 or ::
1461
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001462 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001463 # Code to set dston and dstoff to the time zone's DST
1464 # transition times based on the input dt.year, and expressed
1465 # in standard local time. Then
1466
1467 if dston <= dt.replace(tzinfo=None) < dstoff:
1468 return timedelta(hours=1)
1469 else:
1470 return timedelta(0)
1471
1472 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1473
1474
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001475.. method:: tzinfo.tzname(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001476
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001477 Return the time zone name corresponding to the :class:`.datetime` object *dt*, as
Georg Brandl116aa622007-08-15 14:28:22 +00001478 a string. Nothing about string names is defined by the :mod:`datetime` module,
1479 and there's no requirement that it mean anything in particular. For example,
1480 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1481 valid replies. Return ``None`` if a string name isn't known. Note that this is
1482 a method rather than a fixed string primarily because some :class:`tzinfo`
1483 subclasses will wish to return different names depending on the specific value
1484 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1485 daylight time.
1486
1487 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1488
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001489
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001490These methods are called by a :class:`.datetime` or :class:`.time` object, in
1491response to their methods of the same names. A :class:`.datetime` object passes
1492itself as the argument, and a :class:`.time` object passes ``None`` as the
Georg Brandl116aa622007-08-15 14:28:22 +00001493argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001494accept a *dt* argument of ``None``, or of class :class:`.datetime`.
Georg Brandl116aa622007-08-15 14:28:22 +00001495
1496When ``None`` is passed, it's up to the class designer to decide the best
1497response. For example, returning ``None`` is appropriate if the class wishes to
1498say that time objects don't participate in the :class:`tzinfo` protocols. It
1499may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1500there is no other convention for discovering the standard offset.
1501
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001502When a :class:`.datetime` object is passed in response to a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +00001503method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1504rely on this, unless user code calls :class:`tzinfo` methods directly. The
1505intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1506time, and not need worry about objects in other timezones.
1507
1508There is one more :class:`tzinfo` method that a subclass may wish to override:
1509
1510
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001511.. method:: tzinfo.fromutc(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001512
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001513 This is called from the default :class:`datetime.astimezone()`
1514 implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s
1515 date and time data are to be viewed as expressing a UTC time. The purpose
1516 of :meth:`fromutc` is to adjust the date and time data, returning an
Senthil Kumarana6bac952011-07-04 11:28:30 -07001517 equivalent datetime in *self*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00001518
1519 Most :class:`tzinfo` subclasses should be able to inherit the default
1520 :meth:`fromutc` implementation without problems. It's strong enough to handle
1521 fixed-offset time zones, and time zones accounting for both standard and
1522 daylight time, and the latter even if the DST transition times differ in
1523 different years. An example of a time zone the default :meth:`fromutc`
1524 implementation may not handle correctly in all cases is one where the standard
1525 offset (from UTC) depends on the specific date and time passed, which can happen
1526 for political reasons. The default implementations of :meth:`astimezone` and
1527 :meth:`fromutc` may not produce the result you want if the result is one of the
1528 hours straddling the moment the standard offset changes.
1529
1530 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1531 like::
1532
1533 def fromutc(self, dt):
1534 # raise ValueError error if dt.tzinfo is not self
1535 dtoff = dt.utcoffset()
1536 dtdst = dt.dst()
1537 # raise ValueError if dtoff is None or dtdst is None
1538 delta = dtoff - dtdst # this is self's standard offset
1539 if delta:
1540 dt += delta # convert to standard local time
1541 dtdst = dt.dst()
1542 # raise ValueError if dtdst is None
1543 if dtdst:
1544 return dt + dtdst
1545 else:
1546 return dt
1547
1548Example :class:`tzinfo` classes:
1549
1550.. literalinclude:: ../includes/tzinfo-examples.py
1551
1552
1553Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1554subclass accounting for both standard and daylight time, at the DST transition
1555points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00001556minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
15571:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001558
1559 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1560 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1561 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1562
1563 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1564
1565 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1566
1567When DST starts (the "start" line), the local wall clock leaps from 1:59 to
15683:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1569``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1570begins. In order for :meth:`astimezone` to make this guarantee, the
1571:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1572Eastern) to be in daylight time.
1573
1574When DST ends (the "end" line), there's a potentially worse problem: there's an
1575hour that can't be spelled unambiguously in local wall time: the last hour of
1576daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1577daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1578to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1579:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1580hours into the same local hour then. In the Eastern example, UTC times of the
1581form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1582:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1583consider times in the "repeated hour" to be in standard time. This is easily
1584arranged, as in the example, by expressing DST switch times in the time zone's
1585standard local time.
1586
1587Applications that can't bear such ambiguities should avoid using hybrid
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001588:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`,
1589or any other fixed-offset :class:`tzinfo` subclass (such as a class representing
1590only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
1591
1592
1593.. _datetime-timezone:
1594
1595:class:`timezone` Objects
1596--------------------------
1597
Alexander Belopolsky6d3c9a62011-05-04 10:28:26 -04001598The :class:`timezone` class is a subclass of :class:`tzinfo`, each
1599instance of which represents a timezone defined by a fixed offset from
1600UTC. Note that objects of this class cannot be used to represent
1601timezone information in the locations where different offsets are used
1602in different days of the year or where historical changes have been
1603made to civil time.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001604
1605
1606.. class:: timezone(offset[, name])
1607
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001608 The *offset* argument must be specified as a :class:`timedelta`
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001609 object representing the difference between the local time and UTC. It must
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001610 be strictly between ``-timedelta(hours=24)`` and
1611 ``timedelta(hours=24)`` and represent a whole number of minutes,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001612 otherwise :exc:`ValueError` is raised.
1613
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001614 The *name* argument is optional. If specified it must be a string that
1615 is used as the value returned by the ``tzname(dt)`` method. Otherwise,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001616 ``tzname(dt)`` returns a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001617 *offset*, HH and MM are two digits of ``offset.hours`` and
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001618 ``offset.minutes`` respectively.
1619
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001620.. method:: timezone.utcoffset(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001621
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001622 Return the fixed value specified when the :class:`timezone` instance is
1623 constructed. The *dt* argument is ignored. The return value is a
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001624 :class:`timedelta` instance equal to the difference between the
1625 local time and UTC.
1626
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001627.. method:: timezone.tzname(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001628
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001629 Return the fixed value specified when the :class:`timezone` instance is
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001630 constructed or a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001631 *offset*, HH and MM are two digits of ``offset.hours`` and
1632 ``offset.minutes`` respectively.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001633
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001634.. method:: timezone.dst(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001635
1636 Always returns ``None``.
1637
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001638.. method:: timezone.fromutc(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001639
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001640 Return ``dt + offset``. The *dt* argument must be an aware
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001641 :class:`.datetime` instance, with ``tzinfo`` set to ``self``.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001642
1643Class attributes:
1644
1645.. attribute:: timezone.utc
1646
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001647 The UTC timezone, ``timezone(timedelta(0))``.
Georg Brandl48310cd2009-01-03 21:18:54 +00001648
Georg Brandl116aa622007-08-15 14:28:22 +00001649
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001650.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00001651
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001652:meth:`strftime` and :meth:`strptime` Behavior
1653----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001654
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001655:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
Georg Brandl116aa622007-08-15 14:28:22 +00001656``strftime(format)`` method, to create a string representing the time under the
1657control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1658acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1659although not all objects support a :meth:`timetuple` method.
1660
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001661Conversely, the :meth:`datetime.strptime` class method creates a
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001662:class:`.datetime` object from a string representing a date and time and a
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001663corresponding format string. ``datetime.strptime(date_string, format)`` is
1664equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1665
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001666For :class:`.time` objects, the format codes for year, month, and day should not
Georg Brandl116aa622007-08-15 14:28:22 +00001667be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001668is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00001669
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001670For :class:`date` objects, the format codes for hours, minutes, seconds, and
1671microseconds should not be used, as :class:`date` objects have no such
1672values. If they're used anyway, ``0`` is substituted for them.
1673
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001674For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1675strings.
1676
1677For an aware object:
1678
1679``%z``
1680 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1681 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1682 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1683 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1684 replaced with the string ``'-0330'``.
1685
1686``%Z``
1687 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1688 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl116aa622007-08-15 14:28:22 +00001689
Georg Brandl116aa622007-08-15 14:28:22 +00001690The full set of format codes supported varies across platforms, because Python
1691calls the platform C library's :func:`strftime` function, and platform
Georg Brandl48310cd2009-01-03 21:18:54 +00001692variations are common.
Christian Heimes895627f2007-12-08 17:28:33 +00001693
1694The following is a list of all the format codes that the C standard (1989
1695version) requires, and these work on all platforms with a standard C
1696implementation. Note that the 1999 version of the C standard added additional
1697format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001698
Christian Heimes895627f2007-12-08 17:28:33 +00001699+-----------+--------------------------------+-------+
1700| Directive | Meaning | Notes |
1701+===========+================================+=======+
1702| ``%a`` | Locale's abbreviated weekday | |
1703| | name. | |
1704+-----------+--------------------------------+-------+
1705| ``%A`` | Locale's full weekday name. | |
1706+-----------+--------------------------------+-------+
1707| ``%b`` | Locale's abbreviated month | |
1708| | name. | |
1709+-----------+--------------------------------+-------+
1710| ``%B`` | Locale's full month name. | |
1711+-----------+--------------------------------+-------+
1712| ``%c`` | Locale's appropriate date and | |
1713| | time representation. | |
1714+-----------+--------------------------------+-------+
1715| ``%d`` | Day of the month as a decimal | |
1716| | number [01,31]. | |
1717+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001718| ``%f`` | Microsecond as a decimal | \(1) |
1719| | number [0,999999], zero-padded | |
1720| | on the left | |
1721+-----------+--------------------------------+-------+
Christian Heimes895627f2007-12-08 17:28:33 +00001722| ``%H`` | Hour (24-hour clock) as a | |
1723| | decimal number [00,23]. | |
1724+-----------+--------------------------------+-------+
1725| ``%I`` | Hour (12-hour clock) as a | |
1726| | decimal number [01,12]. | |
1727+-----------+--------------------------------+-------+
1728| ``%j`` | Day of the year as a decimal | |
1729| | number [001,366]. | |
1730+-----------+--------------------------------+-------+
1731| ``%m`` | Month as a decimal number | |
1732| | [01,12]. | |
1733+-----------+--------------------------------+-------+
1734| ``%M`` | Minute as a decimal number | |
1735| | [00,59]. | |
1736+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001737| ``%p`` | Locale's equivalent of either | \(2) |
Christian Heimes895627f2007-12-08 17:28:33 +00001738| | AM or PM. | |
1739+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001740| ``%S`` | Second as a decimal number | \(3) |
Alexander Belopolsky9971e002011-01-10 22:56:14 +00001741| | [00,59]. | |
Christian Heimes895627f2007-12-08 17:28:33 +00001742+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001743| ``%U`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001744| | (Sunday as the first day of | |
1745| | the week) as a decimal number | |
1746| | [00,53]. All days in a new | |
1747| | year preceding the first | |
1748| | Sunday are considered to be in | |
1749| | week 0. | |
1750+-----------+--------------------------------+-------+
1751| ``%w`` | Weekday as a decimal number | |
1752| | [0(Sunday),6]. | |
1753+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001754| ``%W`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001755| | (Monday as the first day of | |
1756| | the week) as a decimal number | |
1757| | [00,53]. All days in a new | |
1758| | year preceding the first | |
1759| | Monday are considered to be in | |
1760| | week 0. | |
1761+-----------+--------------------------------+-------+
1762| ``%x`` | Locale's appropriate date | |
1763| | representation. | |
1764+-----------+--------------------------------+-------+
1765| ``%X`` | Locale's appropriate time | |
1766| | representation. | |
1767+-----------+--------------------------------+-------+
1768| ``%y`` | Year without century as a | |
1769| | decimal number [00,99]. | |
1770+-----------+--------------------------------+-------+
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001771| ``%Y`` | Year with century as a decimal | \(5) |
Alexander Belopolsky89da3492011-05-02 13:14:24 -04001772| | number [0001,9999]. | |
Christian Heimes895627f2007-12-08 17:28:33 +00001773+-----------+--------------------------------+-------+
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001774| ``%z`` | UTC offset in the form +HHMM | \(6) |
Christian Heimes895627f2007-12-08 17:28:33 +00001775| | or -HHMM (empty string if the | |
1776| | the object is naive). | |
1777+-----------+--------------------------------+-------+
1778| ``%Z`` | Time zone name (empty string | |
1779| | if the object is naive). | |
1780+-----------+--------------------------------+-------+
1781| ``%%`` | A literal ``'%'`` character. | |
1782+-----------+--------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001783
Christian Heimes895627f2007-12-08 17:28:33 +00001784Notes:
1785
1786(1)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001787 When used with the :meth:`strptime` method, the ``%f`` directive
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001788 accepts from one to six digits and zero pads on the right. ``%f`` is
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001789 an extension to the set of format characters in the C standard (but
1790 implemented separately in datetime objects, and therefore always
1791 available).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001792
1793(2)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001794 When used with the :meth:`strptime` method, the ``%p`` directive only affects
Christian Heimes895627f2007-12-08 17:28:33 +00001795 the output hour field if the ``%I`` directive is used to parse the hour.
1796
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001797(3)
Alexander Belopolsky9971e002011-01-10 22:56:14 +00001798 Unlike :mod:`time` module, :mod:`datetime` module does not support
1799 leap seconds.
Christian Heimes895627f2007-12-08 17:28:33 +00001800
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001801(4)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001802 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in
Christian Heimes895627f2007-12-08 17:28:33 +00001803 calculations when the day of the week and the year are specified.
1804
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001805(5)
Alexander Belopolsky89da3492011-05-02 13:14:24 -04001806 The :meth:`strptime` method can
Alexander Belopolsky5fc850b2011-01-10 23:31:51 +00001807 parse years in the full [1, 9999] range, but years < 1000 must be
1808 zero-filled to 4-digit width.
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001809
1810 .. versionchanged:: 3.2
1811 In previous versions, :meth:`strftime` method was restricted to
1812 years >= 1900.
1813
Alexander Belopolsky5611a1c2011-05-02 14:14:48 -04001814 .. versionchanged:: 3.3
1815 In version 3.2, :meth:`strftime` method was restricted to
1816 years >= 1000.
1817
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001818(6)
Christian Heimes895627f2007-12-08 17:28:33 +00001819 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1820 ``%z`` is replaced with the string ``'-0330'``.
Alexander Belopolskyca94f552010-06-17 18:30:34 +00001821
Georg Brandl67b21b72010-08-17 15:07:14 +00001822.. versionchanged:: 3.2
1823 When the ``%z`` directive is provided to the :meth:`strptime` method, an
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001824 aware :class:`.datetime` object will be produced. The ``tzinfo`` of the
Georg Brandl67b21b72010-08-17 15:07:14 +00001825 result will be set to a :class:`timezone` instance.