blob: 112a62c70b1f2417bdb2c976734b04a8be91ec2f [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
R David Murray9075d8b2012-05-14 22:14:46 -040018There are two kinds of date and time objects: "naive" and "aware".
19
20An aware object has sufficient knowledge of applicable algorithmic and
21political time adjustments, such as time zone and daylight saving time
22information, to locate itself relative to other aware objects. An aware object
23is used to represent a specific moment in time that is not open to
24interpretation [#]_.
25
26A naive object does not contain enough information to unambiguously locate
27itself relative to other date/time objects. Whether a naive object represents
28Coordinated Universal Time (UTC),
Georg Brandl116aa622007-08-15 14:28:22 +000029local time, or time in some other timezone is purely up to the program, just
30like it's up to the program whether a particular number represents metres,
R David Murray9075d8b2012-05-14 22:14:46 -040031miles, or mass. Naive objects are easy to understand and to
Georg Brandl116aa622007-08-15 14:28:22 +000032work with, at the cost of ignoring some aspects of reality.
33
R David Murray9075d8b2012-05-14 22:14:46 -040034For applications requiring aware objects, :class:`.datetime` and :class:`.time` objects
Senthil Kumaran023c6f72011-07-17 19:01:14 +080035have an optional time zone information attribute, :attr:`tzinfo`, that can be
36set to an instance of a subclass of the abstract :class:`tzinfo` class. These
Georg Brandl116aa622007-08-15 14:28:22 +000037:class:`tzinfo` objects capture information about the offset from UTC time, the
Alexander Belopolsky4e749a12010-06-14 14:15:50 +000038time zone name, and whether Daylight Saving Time is in effect. Note that only
39one concrete :class:`tzinfo` class, the :class:`timezone` class, is supplied by the
Georg Brandl75546062011-09-17 20:20:04 +020040:mod:`datetime` module. The :class:`timezone` class can represent simple
Alexander Belopolsky4e749a12010-06-14 14:15:50 +000041timezones with fixed offset from UTC such as UTC itself or North American EST and
R David Murray9075d8b2012-05-14 22:14:46 -040042EDT timezones. Supporting timezones at deeper levels of detail is
43up to the application. The rules for time adjustment across the
Alexander Belopolsky4e749a12010-06-14 14:15:50 +000044world are more political than rational, change frequently, and there is no
45standard suitable for every application aside from UTC.
Georg Brandl116aa622007-08-15 14:28:22 +000046
47The :mod:`datetime` module exports the following constants:
48
Georg Brandl116aa622007-08-15 14:28:22 +000049.. data:: MINYEAR
50
Ezio Melotti35ec7f72011-10-02 12:44:50 +030051 The smallest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl116aa622007-08-15 14:28:22 +000052 :const:`MINYEAR` is ``1``.
53
54
55.. data:: MAXYEAR
56
Ezio Melotti35ec7f72011-10-02 12:44:50 +030057 The largest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl116aa622007-08-15 14:28:22 +000058 :const:`MAXYEAR` is ``9999``.
59
60
61.. seealso::
62
63 Module :mod:`calendar`
64 General calendar related functions.
65
66 Module :mod:`time`
67 Time access and conversions.
68
69
70Available Types
71---------------
72
Georg Brandl116aa622007-08-15 14:28:22 +000073.. class:: date
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000074 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000075
76 An idealized naive date, assuming the current Gregorian calendar always was, and
77 always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and
78 :attr:`day`.
79
80
81.. class:: time
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000082 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000083
84 An idealized time, independent of any particular day, assuming that every day
85 has exactly 24\*60\*60 seconds (there is no notion of "leap seconds" here).
86 Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
87 and :attr:`tzinfo`.
88
89
90.. class:: datetime
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000091 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000092
93 A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`,
94 :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
95 and :attr:`tzinfo`.
96
97
98.. class:: timedelta
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000099 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000100
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300101 A duration expressing the difference between two :class:`date`, :class:`.time`,
102 or :class:`.datetime` instances to microsecond resolution.
Georg Brandl116aa622007-08-15 14:28:22 +0000103
104
105.. class:: tzinfo
106
107 An abstract base class for time zone information objects. These are used by the
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300108 :class:`.datetime` and :class:`.time` classes to provide a customizable notion of
Georg Brandl116aa622007-08-15 14:28:22 +0000109 time adjustment (for example, to account for time zone and/or daylight saving
110 time).
111
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000112.. class:: timezone
113
114 A class that implements the :class:`tzinfo` abstract base class as a
115 fixed offset from the UTC.
116
117 .. versionadded:: 3.2
118
119
Georg Brandl116aa622007-08-15 14:28:22 +0000120Objects of these types are immutable.
121
122Objects of the :class:`date` type are always naive.
123
R David Murray9075d8b2012-05-14 22:14:46 -0400124An object of type :class:`.time` or :class:`.datetime` may be naive or aware.
125A :class:`.datetime` object *d* is aware if ``d.tzinfo`` is not ``None`` and
126``d.tzinfo.utcoffset(d)`` does not return ``None``. If ``d.tzinfo`` is
127``None``, or if ``d.tzinfo`` is not ``None`` but ``d.tzinfo.utcoffset(d)``
128returns ``None``, *d* is naive. A :class:`.time` object *t* is aware
129if ``t.tzinfo`` is not ``None`` and ``t.tzinfo.utcoffset(None)`` does not return
130``None``. Otherwise, *t* is naive.
Georg Brandl116aa622007-08-15 14:28:22 +0000131
132The distinction between naive and aware doesn't apply to :class:`timedelta`
133objects.
134
135Subclass relationships::
136
137 object
138 timedelta
139 tzinfo
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000140 timezone
Georg Brandl116aa622007-08-15 14:28:22 +0000141 time
142 date
143 datetime
144
145
146.. _datetime-timedelta:
147
148:class:`timedelta` Objects
149--------------------------
150
151A :class:`timedelta` object represents a duration, the difference between two
152dates or times.
153
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000154.. class:: timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000155
Georg Brandl5c106642007-11-29 17:41:05 +0000156 All arguments are optional and default to ``0``. Arguments may be integers
Georg Brandl116aa622007-08-15 14:28:22 +0000157 or floats, and may be positive or negative.
158
159 Only *days*, *seconds* and *microseconds* are stored internally. Arguments are
160 converted to those units:
161
162 * A millisecond is converted to 1000 microseconds.
163 * A minute is converted to 60 seconds.
164 * An hour is converted to 3600 seconds.
165 * A week is converted to 7 days.
166
167 and days, seconds and microseconds are then normalized so that the
168 representation is unique, with
169
170 * ``0 <= microseconds < 1000000``
171 * ``0 <= seconds < 3600*24`` (the number of seconds in one day)
172 * ``-999999999 <= days <= 999999999``
173
174 If any argument is a float and there are fractional microseconds, the fractional
175 microseconds left over from all arguments are combined and their sum is rounded
176 to the nearest microsecond. If no argument is a float, the conversion and
177 normalization processes are exact (no information is lost).
178
179 If the normalized value of days lies outside the indicated range,
180 :exc:`OverflowError` is raised.
181
182 Note that normalization of negative values may be surprising at first. For
Christian Heimesfe337bf2008-03-23 21:54:12 +0000183 example,
Georg Brandl116aa622007-08-15 14:28:22 +0000184
Christian Heimes895627f2007-12-08 17:28:33 +0000185 >>> from datetime import timedelta
Georg Brandl116aa622007-08-15 14:28:22 +0000186 >>> d = timedelta(microseconds=-1)
187 >>> (d.days, d.seconds, d.microseconds)
188 (-1, 86399, 999999)
189
Georg Brandl116aa622007-08-15 14:28:22 +0000190
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000191Class attributes are:
Georg Brandl116aa622007-08-15 14:28:22 +0000192
193.. attribute:: timedelta.min
194
195 The most negative :class:`timedelta` object, ``timedelta(-999999999)``.
196
197
198.. attribute:: timedelta.max
199
200 The most positive :class:`timedelta` object, ``timedelta(days=999999999,
201 hours=23, minutes=59, seconds=59, microseconds=999999)``.
202
203
204.. attribute:: timedelta.resolution
205
206 The smallest possible difference between non-equal :class:`timedelta` objects,
207 ``timedelta(microseconds=1)``.
208
209Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``.
210``-timedelta.max`` is not representable as a :class:`timedelta` object.
211
212Instance attributes (read-only):
213
214+------------------+--------------------------------------------+
215| Attribute | Value |
216+==================+============================================+
217| ``days`` | Between -999999999 and 999999999 inclusive |
218+------------------+--------------------------------------------+
219| ``seconds`` | Between 0 and 86399 inclusive |
220+------------------+--------------------------------------------+
221| ``microseconds`` | Between 0 and 999999 inclusive |
222+------------------+--------------------------------------------+
223
224Supported operations:
225
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000226.. XXX this table is too wide!
Georg Brandl116aa622007-08-15 14:28:22 +0000227
228+--------------------------------+-----------------------------------------------+
229| Operation | Result |
230+================================+===============================================+
231| ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == |
232| | *t3* and *t1*-*t3* == *t2* are true. (1) |
233+--------------------------------+-----------------------------------------------+
234| ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* |
235| | == *t2* - *t3* and *t2* == *t1* + *t3* are |
236| | true. (1) |
237+--------------------------------+-----------------------------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000238| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer. |
Georg Brandl116aa622007-08-15 14:28:22 +0000239| | Afterwards *t1* // i == *t2* is true, |
240| | provided ``i != 0``. |
241+--------------------------------+-----------------------------------------------+
242| | In general, *t1* \* i == *t1* \* (i-1) + *t1* |
243| | is true. (1) |
244+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000245| ``t1 = t2 * f or t1 = f * t2`` | Delta multiplied by a float. The result is |
246| | rounded to the nearest multiple of |
247| | timedelta.resolution using round-half-to-even.|
248+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000249| ``f = t2 / t3`` | Division (3) of *t2* by *t3*. Returns a |
250| | :class:`float` object. |
251+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000252| ``t1 = t2 / f or t1 = t2 / i`` | Delta divided by a float or an int. The result|
253| | is rounded to the nearest multiple of |
254| | timedelta.resolution using round-half-to-even.|
255+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000256| ``t1 = t2 // i`` or | The floor is computed and the remainder (if |
257| ``t1 = t2 // t3`` | any) is thrown away. In the second case, an |
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000258| | integer is returned. (3) |
Mark Dickinson7c186e22010-04-20 22:32:49 +0000259+--------------------------------+-----------------------------------------------+
260| ``t1 = t2 % t3`` | The remainder is computed as a |
261| | :class:`timedelta` object. (3) |
262+--------------------------------+-----------------------------------------------+
263| ``q, r = divmod(t1, t2)`` | Computes the quotient and the remainder: |
264| | ``q = t1 // t2`` (3) and ``r = t1 % t2``. |
265| | q is an integer and r is a :class:`timedelta` |
266| | object. |
Georg Brandl116aa622007-08-15 14:28:22 +0000267+--------------------------------+-----------------------------------------------+
268| ``+t1`` | Returns a :class:`timedelta` object with the |
269| | same value. (2) |
270+--------------------------------+-----------------------------------------------+
271| ``-t1`` | equivalent to :class:`timedelta`\ |
272| | (-*t1.days*, -*t1.seconds*, |
273| | -*t1.microseconds*), and to *t1*\* -1. (1)(4) |
274+--------------------------------+-----------------------------------------------+
Georg Brandl495f7b52009-10-27 15:28:25 +0000275| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, and|
Georg Brandl116aa622007-08-15 14:28:22 +0000276| | to -*t* when ``t.days < 0``. (2) |
277+--------------------------------+-----------------------------------------------+
Georg Brandlf55c3152010-07-31 11:40:07 +0000278| ``str(t)`` | Returns a string in the form |
279| | ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D |
280| | is negative for negative ``t``. (5) |
281+--------------------------------+-----------------------------------------------+
282| ``repr(t)`` | Returns a string in the form |
283| | ``datetime.timedelta(D[, S[, U]])``, where D |
284| | is negative for negative ``t``. (5) |
285+--------------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000286
287Notes:
288
289(1)
290 This is exact, but may overflow.
291
292(2)
293 This is exact, and cannot overflow.
294
295(3)
296 Division by 0 raises :exc:`ZeroDivisionError`.
297
298(4)
299 -*timedelta.max* is not representable as a :class:`timedelta` object.
300
Georg Brandlf55c3152010-07-31 11:40:07 +0000301(5)
302 String representations of :class:`timedelta` objects are normalized
303 similarly to their internal representation. This leads to somewhat
304 unusual results for negative timedeltas. For example:
305
306 >>> timedelta(hours=-5)
307 datetime.timedelta(-1, 68400)
308 >>> print(_)
309 -1 day, 19:00:00
310
Georg Brandl116aa622007-08-15 14:28:22 +0000311In addition to the operations listed above :class:`timedelta` objects support
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300312certain additions and subtractions with :class:`date` and :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +0000313objects (see below).
314
Georg Brandl67b21b72010-08-17 15:07:14 +0000315.. versionchanged:: 3.2
316 Floor division and true division of a :class:`timedelta` object by another
317 :class:`timedelta` object are now supported, as are remainder operations and
318 the :func:`divmod` function. True division and multiplication of a
319 :class:`timedelta` object by a :class:`float` object are now supported.
Mark Dickinson7c186e22010-04-20 22:32:49 +0000320
321
Georg Brandl116aa622007-08-15 14:28:22 +0000322Comparisons of :class:`timedelta` objects are supported with the
323:class:`timedelta` object representing the smaller duration considered to be the
324smaller timedelta. In order to stop mixed-type comparisons from falling back to
325the default comparison by object address, when a :class:`timedelta` object is
326compared to an object of a different type, :exc:`TypeError` is raised unless the
327comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
328:const:`True`, respectively.
329
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000330:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl116aa622007-08-15 14:28:22 +0000331efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
332considered to be true if and only if it isn't equal to ``timedelta(0)``.
333
Antoine Pitroube6859d2009-11-25 23:02:32 +0000334Instance methods:
335
336.. method:: timedelta.total_seconds()
337
338 Return the total number of seconds contained in the duration. Equivalent to
Mark Dickinson0381e3f2010-05-08 14:35:02 +0000339 ``td / timedelta(seconds=1)``.
340
341 Note that for very large time intervals (greater than 270 years on
342 most platforms) this method will lose microsecond accuracy.
Antoine Pitroube6859d2009-11-25 23:02:32 +0000343
344 .. versionadded:: 3.2
345
346
Christian Heimesfe337bf2008-03-23 21:54:12 +0000347Example usage:
Georg Brandl48310cd2009-01-03 21:18:54 +0000348
Christian Heimes895627f2007-12-08 17:28:33 +0000349 >>> from datetime import timedelta
350 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000351 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Christian Heimes895627f2007-12-08 17:28:33 +0000352 ... minutes=50, seconds=600) # adds up to 365 days
Antoine Pitroube6859d2009-11-25 23:02:32 +0000353 >>> year.total_seconds()
354 31536000.0
Christian Heimes895627f2007-12-08 17:28:33 +0000355 >>> year == another_year
356 True
357 >>> ten_years = 10 * year
358 >>> ten_years, ten_years.days // 365
359 (datetime.timedelta(3650), 10)
360 >>> nine_years = ten_years - year
361 >>> nine_years, nine_years.days // 365
362 (datetime.timedelta(3285), 9)
363 >>> three_years = nine_years // 3;
364 >>> three_years, three_years.days // 365
365 (datetime.timedelta(1095), 3)
366 >>> abs(three_years - ten_years) == 2 * three_years + year
367 True
368
Georg Brandl116aa622007-08-15 14:28:22 +0000369
370.. _datetime-date:
371
372:class:`date` Objects
373---------------------
374
375A :class:`date` object represents a date (year, month and day) in an idealized
376calendar, the current Gregorian calendar indefinitely extended in both
377directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
378called day number 2, and so on. This matches the definition of the "proleptic
379Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
380where it's the base calendar for all computations. See the book for algorithms
381for converting between proleptic Gregorian ordinals and many other calendar
382systems.
383
384
385.. class:: date(year, month, day)
386
Georg Brandl5c106642007-11-29 17:41:05 +0000387 All arguments are required. Arguments may be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000388 ranges:
389
390 * ``MINYEAR <= year <= MAXYEAR``
391 * ``1 <= month <= 12``
392 * ``1 <= day <= number of days in the given month and year``
393
394 If an argument outside those ranges is given, :exc:`ValueError` is raised.
395
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000396
Georg Brandl116aa622007-08-15 14:28:22 +0000397Other constructors, all class methods:
398
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000399.. classmethod:: date.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000400
401 Return the current local date. This is equivalent to
402 ``date.fromtimestamp(time.time())``.
403
404
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000405.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000406
407 Return the local date corresponding to the POSIX timestamp, such as is returned
408 by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out
Georg Brandl60203b42010-10-06 10:11:56 +0000409 of the range of values supported by the platform C :c:func:`localtime` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000410 It's common for this to be restricted to years from 1970 through 2038. Note
411 that on non-POSIX systems that include leap seconds in their notion of a
412 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
413
414
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000415.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000416
417 Return the date corresponding to the proleptic Gregorian ordinal, where January
418 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
419 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
420 d``.
421
Georg Brandl116aa622007-08-15 14:28:22 +0000422
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000423Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000424
425.. attribute:: date.min
426
427 The earliest representable date, ``date(MINYEAR, 1, 1)``.
428
429
430.. attribute:: date.max
431
432 The latest representable date, ``date(MAXYEAR, 12, 31)``.
433
434
435.. attribute:: date.resolution
436
437 The smallest possible difference between non-equal date objects,
438 ``timedelta(days=1)``.
439
Georg Brandl116aa622007-08-15 14:28:22 +0000440
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000441Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000442
443.. attribute:: date.year
444
445 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
446
447
448.. attribute:: date.month
449
450 Between 1 and 12 inclusive.
451
452
453.. attribute:: date.day
454
455 Between 1 and the number of days in the given month of the given year.
456
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000457
Georg Brandl116aa622007-08-15 14:28:22 +0000458Supported operations:
459
460+-------------------------------+----------------------------------------------+
461| Operation | Result |
462+===============================+==============================================+
463| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
464| | from *date1*. (1) |
465+-------------------------------+----------------------------------------------+
466| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
467| | timedelta == date1``. (2) |
468+-------------------------------+----------------------------------------------+
469| ``timedelta = date1 - date2`` | \(3) |
470+-------------------------------+----------------------------------------------+
471| ``date1 < date2`` | *date1* is considered less than *date2* when |
472| | *date1* precedes *date2* in time. (4) |
473+-------------------------------+----------------------------------------------+
474
475Notes:
476
477(1)
478 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
479 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
480 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
481 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
482 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
483
484(2)
485 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
486 isolation can overflow in cases where date1 - timedelta does not.
487 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
488
489(3)
490 This is exact, and cannot overflow. timedelta.seconds and
491 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
492
493(4)
494 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
495 date2.toordinal()``. In order to stop comparison from falling back to the
496 default scheme of comparing object addresses, date comparison normally raises
497 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
498 However, ``NotImplemented`` is returned instead if the other comparand has a
499 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
500 chance at implementing mixed-type comparison. If not, when a :class:`date`
501 object is compared to an object of a different type, :exc:`TypeError` is raised
502 unless the comparison is ``==`` or ``!=``. The latter cases return
503 :const:`False` or :const:`True`, respectively.
504
505Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
506objects are considered to be true.
507
508Instance methods:
509
Georg Brandl116aa622007-08-15 14:28:22 +0000510.. method:: date.replace(year, month, day)
511
Senthil Kumarana6bac952011-07-04 11:28:30 -0700512 Return a date with the same value, except for those parameters given new
513 values by whichever keyword arguments are specified. For example, if ``d ==
514 date(2002, 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000515
516
517.. method:: date.timetuple()
518
519 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
520 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
521 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000522 d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1,
523 1).toordinal() + 1`` is the day number within the current year starting with
524 ``1`` for January 1st.
Georg Brandl116aa622007-08-15 14:28:22 +0000525
526
527.. method:: date.toordinal()
528
529 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
530 has ordinal 1. For any :class:`date` object *d*,
531 ``date.fromordinal(d.toordinal()) == d``.
532
533
534.. method:: date.weekday()
535
536 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
537 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
538 :meth:`isoweekday`.
539
540
541.. method:: date.isoweekday()
542
543 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
544 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
545 :meth:`weekday`, :meth:`isocalendar`.
546
547
548.. method:: date.isocalendar()
549
550 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
551
552 The ISO calendar is a widely used variant of the Gregorian calendar. See
Mark Dickinsonf964ac22009-11-03 16:29:10 +0000553 http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
554 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000555
556 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
557 Monday and ends on a Sunday. The first week of an ISO year is the first
558 (Gregorian) calendar week of a year containing a Thursday. This is called week
559 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
560
561 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
562 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
563 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
564 4).isocalendar() == (2004, 1, 7)``.
565
566
567.. method:: date.isoformat()
568
569 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
570 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
571
572
573.. method:: date.__str__()
574
575 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
576
577
578.. method:: date.ctime()
579
580 Return a string representing the date, for example ``date(2002, 12,
581 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
582 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
Georg Brandl60203b42010-10-06 10:11:56 +0000583 :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +0000584 :meth:`date.ctime` does not invoke) conforms to the C standard.
585
586
587.. method:: date.strftime(format)
588
589 Return a string representing the date, controlled by an explicit format string.
590 Format codes referring to hours, minutes or seconds will see 0 values. See
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000591 section :ref:`strftime-strptime-behavior`.
592
Georg Brandl116aa622007-08-15 14:28:22 +0000593
Christian Heimes895627f2007-12-08 17:28:33 +0000594Example of counting days to an event::
595
596 >>> import time
597 >>> from datetime import date
598 >>> today = date.today()
599 >>> today
600 datetime.date(2007, 12, 5)
601 >>> today == date.fromtimestamp(time.time())
602 True
603 >>> my_birthday = date(today.year, 6, 24)
604 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000605 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000606 >>> my_birthday
607 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000608 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000609 >>> time_to_birthday.days
610 202
611
Christian Heimesfe337bf2008-03-23 21:54:12 +0000612Example of working with :class:`date`:
613
614.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000615
616 >>> from datetime import date
617 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
618 >>> d
619 datetime.date(2002, 3, 11)
620 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000621 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000622 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000623 2002 # year
624 3 # month
625 11 # day
626 0
627 0
628 0
629 0 # weekday (0 = Monday)
630 70 # 70th day in the year
631 -1
632 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000633 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000634 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000635 2002 # ISO year
636 11 # ISO week number
637 1 # ISO day number ( 1 = Monday )
638 >>> d.isoformat()
639 '2002-03-11'
640 >>> d.strftime("%d/%m/%y")
641 '11/03/02'
642 >>> d.strftime("%A %d. %B %Y")
643 'Monday 11. March 2002'
644
Georg Brandl116aa622007-08-15 14:28:22 +0000645
646.. _datetime-datetime:
647
648:class:`datetime` Objects
649-------------------------
650
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300651A :class:`.datetime` object is a single object containing all the information
652from a :class:`date` object and a :class:`.time` object. Like a :class:`date`
653object, :class:`.datetime` assumes the current Gregorian calendar extended in
654both directions; like a time object, :class:`.datetime` assumes there are exactly
Georg Brandl116aa622007-08-15 14:28:22 +00006553600\*24 seconds in every day.
656
657Constructor:
658
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000659.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000660
661 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000662 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
663 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000664
665 * ``MINYEAR <= year <= MAXYEAR``
666 * ``1 <= month <= 12``
667 * ``1 <= day <= number of days in the given month and year``
668 * ``0 <= hour < 24``
669 * ``0 <= minute < 60``
670 * ``0 <= second < 60``
671 * ``0 <= microsecond < 1000000``
672
673 If an argument outside those ranges is given, :exc:`ValueError` is raised.
674
675Other constructors, all class methods:
676
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000677.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000678
679 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
680 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
681 :meth:`fromtimestamp`.
682
683
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000684.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000685
686 Return the current local date and time. If optional argument *tz* is ``None``
687 or not specified, this is like :meth:`today`, but, if possible, supplies more
688 precision than can be gotten from going through a :func:`time.time` timestamp
689 (for example, this may be possible on platforms supplying the C
Georg Brandl60203b42010-10-06 10:11:56 +0000690 :c:func:`gettimeofday` function).
Georg Brandl116aa622007-08-15 14:28:22 +0000691
692 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
693 current date and time are converted to *tz*'s time zone. In this case the
694 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
695 See also :meth:`today`, :meth:`utcnow`.
696
697
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000698.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000699
700 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
701 :meth:`now`, but returns the current UTC date and time, as a naive
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300702 :class:`.datetime` object. An aware current UTC datetime can be obtained by
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000703 calling ``datetime.now(timezone.utc)``. See also :meth:`now`.
Georg Brandl116aa622007-08-15 14:28:22 +0000704
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000705.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000706
707 Return the local date and time corresponding to the POSIX timestamp, such as is
708 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
709 specified, the timestamp is converted to the platform's local date and time, and
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300710 the returned :class:`.datetime` object is naive.
Georg Brandl116aa622007-08-15 14:28:22 +0000711
712 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
713 timestamp is converted to *tz*'s time zone. In this case the result is
714 equivalent to
715 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
716
717 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
Georg Brandl60203b42010-10-06 10:11:56 +0000718 the range of values supported by the platform C :c:func:`localtime` or
719 :c:func:`gmtime` functions. It's common for this to be restricted to years in
Georg Brandl116aa622007-08-15 14:28:22 +0000720 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
721 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
722 and then it's possible to have two timestamps differing by a second that yield
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300723 identical :class:`.datetime` objects. See also :meth:`utcfromtimestamp`.
Georg Brandl116aa622007-08-15 14:28:22 +0000724
725
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
734
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000735.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000736
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300737 Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal,
Georg Brandl116aa622007-08-15 14:28:22 +0000738 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
739 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
740 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
741
742
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000743.. classmethod:: datetime.combine(date, time)
Georg Brandl116aa622007-08-15 14:28:22 +0000744
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300745 Return a new :class:`.datetime` object whose date components are equal to the
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800746 given :class:`date` object's, and whose time components and :attr:`tzinfo`
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300747 attributes are equal to the given :class:`.time` object's. For any
748 :class:`.datetime` object *d*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800749 ``d == datetime.combine(d.date(), d.timetz())``. If date is a
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300750 :class:`.datetime` object, its time components and :attr:`tzinfo` attributes
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800751 are ignored.
Georg Brandl116aa622007-08-15 14:28:22 +0000752
753
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000754.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000755
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300756 Return a :class:`.datetime` corresponding to *date_string*, parsed according to
Georg Brandl116aa622007-08-15 14:28:22 +0000757 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
758 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
759 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 +0000760 time tuple. See section :ref:`strftime-strptime-behavior`.
761
Georg Brandl116aa622007-08-15 14:28:22 +0000762
Georg Brandl116aa622007-08-15 14:28:22 +0000763
764Class attributes:
765
Georg Brandl116aa622007-08-15 14:28:22 +0000766.. attribute:: datetime.min
767
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300768 The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1,
Georg Brandl116aa622007-08-15 14:28:22 +0000769 tzinfo=None)``.
770
771
772.. attribute:: datetime.max
773
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300774 The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
Georg Brandl116aa622007-08-15 14:28:22 +0000775 59, 999999, tzinfo=None)``.
776
777
778.. attribute:: datetime.resolution
779
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300780 The smallest possible difference between non-equal :class:`.datetime` objects,
Georg Brandl116aa622007-08-15 14:28:22 +0000781 ``timedelta(microseconds=1)``.
782
Georg Brandl116aa622007-08-15 14:28:22 +0000783
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000784Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000785
786.. attribute:: datetime.year
787
788 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
789
790
791.. attribute:: datetime.month
792
793 Between 1 and 12 inclusive.
794
795
796.. attribute:: datetime.day
797
798 Between 1 and the number of days in the given month of the given year.
799
800
801.. attribute:: datetime.hour
802
803 In ``range(24)``.
804
805
806.. attribute:: datetime.minute
807
808 In ``range(60)``.
809
810
811.. attribute:: datetime.second
812
813 In ``range(60)``.
814
815
816.. attribute:: datetime.microsecond
817
818 In ``range(1000000)``.
819
820
821.. attribute:: datetime.tzinfo
822
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300823 The object passed as the *tzinfo* argument to the :class:`.datetime` constructor,
Georg Brandl116aa622007-08-15 14:28:22 +0000824 or ``None`` if none was passed.
825
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000826
Georg Brandl116aa622007-08-15 14:28:22 +0000827Supported operations:
828
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300829+---------------------------------------+--------------------------------+
830| Operation | Result |
831+=======================================+================================+
832| ``datetime2 = datetime1 + timedelta`` | \(1) |
833+---------------------------------------+--------------------------------+
834| ``datetime2 = datetime1 - timedelta`` | \(2) |
835+---------------------------------------+--------------------------------+
836| ``timedelta = datetime1 - datetime2`` | \(3) |
837+---------------------------------------+--------------------------------+
838| ``datetime1 < datetime2`` | Compares :class:`.datetime` to |
839| | :class:`.datetime`. (4) |
840+---------------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000841
842(1)
843 datetime2 is a duration of timedelta removed from datetime1, moving forward in
844 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
Senthil Kumarana6bac952011-07-04 11:28:30 -0700845 result has the same :attr:`tzinfo` attribute as the input datetime, and
846 datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
847 datetime2.year would be smaller than :const:`MINYEAR` or larger than
848 :const:`MAXYEAR`. Note that no time zone adjustments are done even if the
849 input is an aware object.
Georg Brandl116aa622007-08-15 14:28:22 +0000850
851(2)
852 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
Senthil Kumarana6bac952011-07-04 11:28:30 -0700853 addition, the result has the same :attr:`tzinfo` attribute as the input
854 datetime, and no time zone adjustments are done even if the input is aware.
855 This isn't quite equivalent to datetime1 + (-timedelta), because -timedelta
856 in isolation can overflow in cases where datetime1 - timedelta does not.
Georg Brandl116aa622007-08-15 14:28:22 +0000857
858(3)
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300859 Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if
Georg Brandl116aa622007-08-15 14:28:22 +0000860 both operands are naive, or if both are aware. If one is aware and the other is
861 naive, :exc:`TypeError` is raised.
862
Senthil Kumarana6bac952011-07-04 11:28:30 -0700863 If both are naive, or both are aware and have the same :attr:`tzinfo` attribute,
864 the :attr:`tzinfo` attributes are ignored, and the result is a :class:`timedelta`
Georg Brandl116aa622007-08-15 14:28:22 +0000865 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
866 are done in this case.
867
Senthil Kumarana6bac952011-07-04 11:28:30 -0700868 If both are aware and have different :attr:`tzinfo` attributes, ``a-b`` acts
869 as if *a* and *b* were first converted to naive UTC datetimes first. The
870 result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
871 - b.utcoffset())`` except that the implementation never overflows.
Georg Brandl116aa622007-08-15 14:28:22 +0000872
873(4)
874 *datetime1* is considered less than *datetime2* when *datetime1* precedes
875 *datetime2* in time.
876
877 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
Senthil Kumarana6bac952011-07-04 11:28:30 -0700878 If both comparands are aware, and have the same :attr:`tzinfo` attribute, the
879 common :attr:`tzinfo` attribute is ignored and the base datetimes are
880 compared. If both comparands are aware and have different :attr:`tzinfo`
881 attributes, the comparands are first adjusted by subtracting their UTC
882 offsets (obtained from ``self.utcoffset()``).
Georg Brandl116aa622007-08-15 14:28:22 +0000883
884 .. note::
885
886 In order to stop comparison from falling back to the default scheme of comparing
887 object addresses, datetime comparison normally raises :exc:`TypeError` if the
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300888 other comparand isn't also a :class:`.datetime` object. However,
Georg Brandl116aa622007-08-15 14:28:22 +0000889 ``NotImplemented`` is returned instead if the other comparand has a
890 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300891 chance at implementing mixed-type comparison. If not, when a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +0000892 object is compared to an object of a different type, :exc:`TypeError` is raised
893 unless the comparison is ``==`` or ``!=``. The latter cases return
894 :const:`False` or :const:`True`, respectively.
895
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300896:class:`.datetime` objects can be used as dictionary keys. In Boolean contexts,
897all :class:`.datetime` objects are considered to be true.
Georg Brandl116aa622007-08-15 14:28:22 +0000898
899Instance methods:
900
Georg Brandl116aa622007-08-15 14:28:22 +0000901.. method:: datetime.date()
902
903 Return :class:`date` object with same year, month and day.
904
905
906.. method:: datetime.time()
907
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300908 Return :class:`.time` object with same hour, minute, second and microsecond.
Georg Brandl116aa622007-08-15 14:28:22 +0000909 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
910
911
912.. method:: datetime.timetz()
913
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300914 Return :class:`.time` object with same hour, minute, second, microsecond, and
Senthil Kumarana6bac952011-07-04 11:28:30 -0700915 tzinfo attributes. See also method :meth:`time`.
Georg Brandl116aa622007-08-15 14:28:22 +0000916
917
918.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
919
Senthil Kumarana6bac952011-07-04 11:28:30 -0700920 Return a datetime with the same attributes, except for those attributes given
921 new values by whichever keyword arguments are specified. Note that
922 ``tzinfo=None`` can be specified to create a naive datetime from an aware
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800923 datetime with no conversion of date and time data.
Georg Brandl116aa622007-08-15 14:28:22 +0000924
925
926.. method:: datetime.astimezone(tz)
927
Ezio Melotti35ec7f72011-10-02 12:44:50 +0300928 Return a :class:`.datetime` object with new :attr:`tzinfo` attribute *tz*,
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800929 adjusting the date and time data so the result is the same UTC time as
Senthil Kumarana6bac952011-07-04 11:28:30 -0700930 *self*, but in *tz*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +0000931
932 *tz* must be an instance of a :class:`tzinfo` subclass, and its
933 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
934 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
935 not return ``None``).
936
937 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800938 adjustment of date or time data is performed. Else the result is local
Senthil Kumarana6bac952011-07-04 11:28:30 -0700939 time in time zone *tz*, representing the same UTC time as *self*: after
940 ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800941 the same date and time data as ``dt - dt.utcoffset()``. The discussion
Senthil Kumarana6bac952011-07-04 11:28:30 -0700942 of class :class:`tzinfo` explains the cases at Daylight Saving Time transition
943 boundaries where this cannot be achieved (an issue only if *tz* models both
944 standard and daylight time).
Georg Brandl116aa622007-08-15 14:28:22 +0000945
946 If you merely want to attach a time zone object *tz* to a datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800947 adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you
Georg Brandl116aa622007-08-15 14:28:22 +0000948 merely want to remove the time zone object from an aware datetime *dt* without
Senthil Kumaran023c6f72011-07-17 19:01:14 +0800949 conversion of date and time data, use ``dt.replace(tzinfo=None)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000950
951 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
952 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
953 Ignoring error cases, :meth:`astimezone` acts like::
954
955 def astimezone(self, tz):
956 if self.tzinfo is tz:
957 return self
958 # Convert self to UTC, and attach the new time zone object.
959 utc = (self - self.utcoffset()).replace(tzinfo=tz)
960 # Convert from UTC to tz's local time.
961 return tz.fromutc(utc)
962
963
964.. method:: datetime.utcoffset()
965
966 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
967 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
968 return ``None``, or a :class:`timedelta` object representing a whole number of
969 minutes with magnitude less than one day.
970
971
972.. method:: datetime.dst()
973
974 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
975 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
976 ``None``, or a :class:`timedelta` object representing a whole number of minutes
977 with magnitude less than one day.
978
979
980.. method:: datetime.tzname()
981
982 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
983 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
984 ``None`` or a string object,
985
986
987.. method:: datetime.timetuple()
988
989 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
990 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000991 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
992 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
993 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
994 of the result is set according to the :meth:`dst` method: :attr:`tzinfo` is
Georg Brandl682d7e02010-10-06 10:26:05 +0000995 ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
Alexander Belopolsky64912482010-06-08 18:59:20 +0000996 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
Alexander Belopolskyda62f2f2010-06-09 17:11:01 +0000997 else :attr:`tm_isdst` is set to ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +0000998
999
1000.. method:: datetime.utctimetuple()
1001
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001002 If :class:`.datetime` instance *d* is naive, this is the same as
Georg Brandl116aa622007-08-15 14:28:22 +00001003 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
1004 ``d.dst()`` returns. DST is never in effect for a UTC time.
1005
1006 If *d* is aware, *d* is normalized to UTC time, by subtracting
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00001007 ``d.utcoffset()``, and a :class:`time.struct_time` for the
1008 normalized time is returned. :attr:`tm_isdst` is forced to 0. Note
1009 that an :exc:`OverflowError` may be raised if *d*.year was
1010 ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
Georg Brandl116aa622007-08-15 14:28:22 +00001011 boundary.
1012
1013
1014.. method:: datetime.toordinal()
1015
1016 Return the proleptic Gregorian ordinal of the date. The same as
1017 ``self.date().toordinal()``.
1018
1019
1020.. method:: datetime.weekday()
1021
1022 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
1023 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
1024
1025
1026.. method:: datetime.isoweekday()
1027
1028 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
1029 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
1030 :meth:`isocalendar`.
1031
1032
1033.. method:: datetime.isocalendar()
1034
1035 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
1036 ``self.date().isocalendar()``.
1037
1038
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001039.. method:: datetime.isoformat(sep='T')
Georg Brandl116aa622007-08-15 14:28:22 +00001040
1041 Return a string representing the date and time in ISO 8601 format,
1042 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
1043 YYYY-MM-DDTHH:MM:SS
1044
1045 If :meth:`utcoffset` does not return ``None``, a 6-character string is
1046 appended, giving the UTC offset in (signed) hours and minutes:
1047 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
1048 YYYY-MM-DDTHH:MM:SS+HH:MM
1049
1050 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +00001051 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +00001052
1053 >>> from datetime import tzinfo, timedelta, datetime
1054 >>> class TZ(tzinfo):
1055 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1056 ...
1057 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1058 '2002-12-25 00:00:00-06:39'
1059
1060
1061.. method:: datetime.__str__()
1062
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001063 For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to
Georg Brandl116aa622007-08-15 14:28:22 +00001064 ``d.isoformat(' ')``.
1065
1066
1067.. method:: datetime.ctime()
1068
1069 Return a string representing the date and time, for example ``datetime(2002, 12,
1070 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1071 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
Georg Brandl60203b42010-10-06 10:11:56 +00001072 native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +00001073 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1074
1075
1076.. method:: datetime.strftime(format)
1077
1078 Return a string representing the date and time, controlled by an explicit format
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001079 string. See section :ref:`strftime-strptime-behavior`.
1080
Georg Brandl116aa622007-08-15 14:28:22 +00001081
Christian Heimesfe337bf2008-03-23 21:54:12 +00001082Examples of working with datetime objects:
1083
1084.. doctest::
1085
Christian Heimes895627f2007-12-08 17:28:33 +00001086 >>> from datetime import datetime, date, time
1087 >>> # Using datetime.combine()
1088 >>> d = date(2005, 7, 14)
1089 >>> t = time(12, 30)
1090 >>> datetime.combine(d, t)
1091 datetime.datetime(2005, 7, 14, 12, 30)
1092 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001093 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001094 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001095 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001096 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1097 >>> # Using datetime.strptime()
1098 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1099 >>> dt
1100 datetime.datetime(2006, 11, 21, 16, 30)
1101 >>> # Using datetime.timetuple() to get tuple of all attributes
1102 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001103 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001104 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001105 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001106 2006 # year
1107 11 # month
1108 21 # day
1109 16 # hour
1110 30 # minute
1111 0 # second
1112 1 # weekday (0 = Monday)
1113 325 # number of days since 1st January
1114 -1 # dst - method tzinfo.dst() returned None
1115 >>> # Date in ISO format
1116 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001117 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001118 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001119 ...
1120 2006 # ISO year
1121 47 # ISO week
1122 2 # ISO weekday
1123 >>> # Formatting datetime
1124 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1125 'Tuesday, 21. November 2006 04:30PM'
1126
Christian Heimesfe337bf2008-03-23 21:54:12 +00001127Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001128
1129 >>> from datetime import timedelta, datetime, tzinfo
1130 >>> class GMT1(tzinfo):
1131 ... def __init__(self): # DST starts last Sunday in March
1132 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1133 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001134 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001135 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1136 ... def utcoffset(self, dt):
1137 ... return timedelta(hours=1) + self.dst(dt)
Georg Brandl48310cd2009-01-03 21:18:54 +00001138 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001139 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1140 ... return timedelta(hours=1)
1141 ... else:
1142 ... return timedelta(0)
1143 ... def tzname(self,dt):
1144 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001145 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001146 >>> class GMT2(tzinfo):
1147 ... def __init__(self):
Georg Brandl48310cd2009-01-03 21:18:54 +00001148 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001149 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001150 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001151 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1152 ... def utcoffset(self, dt):
1153 ... return timedelta(hours=1) + self.dst(dt)
1154 ... def dst(self, dt):
1155 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1156 ... return timedelta(hours=2)
1157 ... else:
1158 ... return timedelta(0)
1159 ... def tzname(self,dt):
1160 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001161 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001162 >>> gmt1 = GMT1()
1163 >>> # Daylight Saving Time
1164 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1165 >>> dt1.dst()
1166 datetime.timedelta(0)
1167 >>> dt1.utcoffset()
1168 datetime.timedelta(0, 3600)
1169 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1170 >>> dt2.dst()
1171 datetime.timedelta(0, 3600)
1172 >>> dt2.utcoffset()
1173 datetime.timedelta(0, 7200)
1174 >>> # Convert datetime to another time zone
1175 >>> dt3 = dt2.astimezone(GMT2())
1176 >>> dt3 # doctest: +ELLIPSIS
1177 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1178 >>> dt2 # doctest: +ELLIPSIS
1179 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1180 >>> dt2.utctimetuple() == dt3.utctimetuple()
1181 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001182
Christian Heimes895627f2007-12-08 17:28:33 +00001183
Georg Brandl116aa622007-08-15 14:28:22 +00001184
1185.. _datetime-time:
1186
1187:class:`time` Objects
1188---------------------
1189
1190A time object represents a (local) time of day, independent of any particular
1191day, and subject to adjustment via a :class:`tzinfo` object.
1192
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001193.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001194
1195 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001196 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001197 following ranges:
1198
1199 * ``0 <= hour < 24``
1200 * ``0 <= minute < 60``
1201 * ``0 <= second < 60``
1202 * ``0 <= microsecond < 1000000``.
1203
1204 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1205 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1206
1207Class attributes:
1208
1209
1210.. attribute:: time.min
1211
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001212 The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001213
1214
1215.. attribute:: time.max
1216
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001217 The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001218
1219
1220.. attribute:: time.resolution
1221
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001222 The smallest possible difference between non-equal :class:`.time` objects,
1223 ``timedelta(microseconds=1)``, although note that arithmetic on
1224 :class:`.time` objects is not supported.
Georg Brandl116aa622007-08-15 14:28:22 +00001225
Georg Brandl116aa622007-08-15 14:28:22 +00001226
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001227Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001228
1229.. attribute:: time.hour
1230
1231 In ``range(24)``.
1232
1233
1234.. attribute:: time.minute
1235
1236 In ``range(60)``.
1237
1238
1239.. attribute:: time.second
1240
1241 In ``range(60)``.
1242
1243
1244.. attribute:: time.microsecond
1245
1246 In ``range(1000000)``.
1247
1248
1249.. attribute:: time.tzinfo
1250
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001251 The object passed as the tzinfo argument to the :class:`.time` constructor, or
Georg Brandl116aa622007-08-15 14:28:22 +00001252 ``None`` if none was passed.
1253
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001254
Georg Brandl116aa622007-08-15 14:28:22 +00001255Supported operations:
1256
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001257* comparison of :class:`.time` to :class:`.time`, where *a* is considered less
Georg Brandl116aa622007-08-15 14:28:22 +00001258 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1259 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
Senthil Kumarana6bac952011-07-04 11:28:30 -07001260 the same :attr:`tzinfo` attribute, the common :attr:`tzinfo` attribute is
1261 ignored and the base times are compared. If both comparands are aware and
1262 have different :attr:`tzinfo` attributes, the comparands are first adjusted by
1263 subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
1264 to stop mixed-type comparisons from falling back to the default comparison by
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001265 object address, when a :class:`.time` object is compared to an object of a
Senthil Kumaran3aac1792011-07-04 11:43:51 -07001266 different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
Senthil Kumarana6bac952011-07-04 11:28:30 -07001267 ``!=``. The latter cases return :const:`False` or :const:`True`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +00001268
1269* hash, use as dict key
1270
1271* efficient pickling
1272
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001273* in Boolean contexts, a :class:`.time` object is considered to be true if and
Georg Brandl116aa622007-08-15 14:28:22 +00001274 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1275 ``0`` if that's ``None``), the result is non-zero.
1276
Georg Brandl116aa622007-08-15 14:28:22 +00001277
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001278Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001279
1280.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1281
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001282 Return a :class:`.time` with the same value, except for those attributes given
Senthil Kumarana6bac952011-07-04 11:28:30 -07001283 new values by whichever keyword arguments are specified. Note that
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001284 ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
1285 aware :class:`.time`, without conversion of the time data.
Georg Brandl116aa622007-08-15 14:28:22 +00001286
1287
1288.. method:: time.isoformat()
1289
1290 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1291 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1292 6-character string is appended, giving the UTC offset in (signed) hours and
1293 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1294
1295
1296.. method:: time.__str__()
1297
1298 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1299
1300
1301.. method:: time.strftime(format)
1302
1303 Return a string representing the time, controlled by an explicit format string.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001304 See section :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001305
1306
1307.. method:: time.utcoffset()
1308
1309 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1310 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1311 return ``None`` or a :class:`timedelta` object representing a whole number of
1312 minutes with magnitude less than one day.
1313
1314
1315.. method:: time.dst()
1316
1317 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1318 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1319 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1320 with magnitude less than one day.
1321
1322
1323.. method:: time.tzname()
1324
1325 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1326 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1327 return ``None`` or a string object.
1328
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001329
Christian Heimesfe337bf2008-03-23 21:54:12 +00001330Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001331
Christian Heimes895627f2007-12-08 17:28:33 +00001332 >>> from datetime import time, tzinfo
1333 >>> class GMT1(tzinfo):
1334 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001335 ... return timedelta(hours=1)
1336 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001337 ... return timedelta(0)
1338 ... def tzname(self,dt):
1339 ... return "Europe/Prague"
1340 ...
1341 >>> t = time(12, 10, 30, tzinfo=GMT1())
1342 >>> t # doctest: +ELLIPSIS
1343 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1344 >>> gmt = GMT1()
1345 >>> t.isoformat()
1346 '12:10:30+01:00'
1347 >>> t.dst()
1348 datetime.timedelta(0)
1349 >>> t.tzname()
1350 'Europe/Prague'
1351 >>> t.strftime("%H:%M:%S %Z")
1352 '12:10:30 Europe/Prague'
1353
Georg Brandl116aa622007-08-15 14:28:22 +00001354
1355.. _datetime-tzinfo:
1356
1357:class:`tzinfo` Objects
1358-----------------------
1359
Brett Cannone1327f72009-01-29 04:10:21 +00001360:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001361instantiated directly. You need to derive a concrete subclass, and (at least)
1362supply implementations of the standard :class:`tzinfo` methods needed by the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001363:class:`.datetime` methods you use. The :mod:`datetime` module supplies
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001364a simple concrete subclass of :class:`tzinfo` :class:`timezone` which can reprsent
1365timezones with fixed offset from UTC such as UTC itself or North American EST and
1366EDT.
Georg Brandl116aa622007-08-15 14:28:22 +00001367
1368An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001369constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
Senthil Kumarana6bac952011-07-04 11:28:30 -07001370view their attributes as being in local time, and the :class:`tzinfo` object
Georg Brandl116aa622007-08-15 14:28:22 +00001371supports methods revealing offset of local time from UTC, the name of the time
1372zone, and DST offset, all relative to a date or time object passed to them.
1373
1374Special requirement for pickling: A :class:`tzinfo` subclass must have an
1375:meth:`__init__` method that can be called with no arguments, else it can be
1376pickled but possibly not unpickled again. This is a technical requirement that
1377may be relaxed in the future.
1378
1379A concrete subclass of :class:`tzinfo` may need to implement the following
1380methods. Exactly which methods are needed depends on the uses made of aware
1381:mod:`datetime` objects. If in doubt, simply implement all of them.
1382
1383
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001384.. method:: tzinfo.utcoffset(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001385
1386 Return offset of local time from UTC, in minutes east of UTC. If local time is
1387 west of UTC, this should be negative. Note that this is intended to be the
1388 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1389 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1390 the UTC offset isn't known, return ``None``. Else the value returned must be a
1391 :class:`timedelta` object specifying a whole number of minutes in the range
1392 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1393 than one day). Most implementations of :meth:`utcoffset` will probably look
1394 like one of these two::
1395
1396 return CONSTANT # fixed-offset class
1397 return CONSTANT + self.dst(dt) # daylight-aware class
1398
1399 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1400 ``None`` either.
1401
1402 The default implementation of :meth:`utcoffset` raises
1403 :exc:`NotImplementedError`.
1404
1405
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001406.. method:: tzinfo.dst(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001407
1408 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1409 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1410 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1411 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1412 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1413 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1414 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
Senthil Kumarana6bac952011-07-04 11:28:30 -07001415 attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
1416 should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
1417 DST changes when crossing time zones.
Georg Brandl116aa622007-08-15 14:28:22 +00001418
1419 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1420 daylight times must be consistent in this sense:
1421
1422 ``tz.utcoffset(dt) - tz.dst(dt)``
1423
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001424 must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo ==
Georg Brandl116aa622007-08-15 14:28:22 +00001425 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1426 zone's "standard offset", which should not depend on the date or the time, but
1427 only on geographic location. The implementation of :meth:`datetime.astimezone`
1428 relies on this, but cannot detect violations; it's the programmer's
1429 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1430 this, it may be able to override the default implementation of
1431 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1432
1433 Most implementations of :meth:`dst` will probably look like one of these two::
1434
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001435 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001436 # a fixed-offset class: doesn't account for DST
1437 return timedelta(0)
1438
1439 or ::
1440
Sandro Tosi4bfe03a2011-11-01 10:32:05 +01001441 def dst(self, dt):
Georg Brandl116aa622007-08-15 14:28:22 +00001442 # Code to set dston and dstoff to the time zone's DST
1443 # transition times based on the input dt.year, and expressed
1444 # in standard local time. Then
1445
1446 if dston <= dt.replace(tzinfo=None) < dstoff:
1447 return timedelta(hours=1)
1448 else:
1449 return timedelta(0)
1450
1451 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1452
1453
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001454.. method:: tzinfo.tzname(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001455
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001456 Return the time zone name corresponding to the :class:`.datetime` object *dt*, as
Georg Brandl116aa622007-08-15 14:28:22 +00001457 a string. Nothing about string names is defined by the :mod:`datetime` module,
1458 and there's no requirement that it mean anything in particular. For example,
1459 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1460 valid replies. Return ``None`` if a string name isn't known. Note that this is
1461 a method rather than a fixed string primarily because some :class:`tzinfo`
1462 subclasses will wish to return different names depending on the specific value
1463 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1464 daylight time.
1465
1466 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1467
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001468
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001469These methods are called by a :class:`.datetime` or :class:`.time` object, in
1470response to their methods of the same names. A :class:`.datetime` object passes
1471itself as the argument, and a :class:`.time` object passes ``None`` as the
Georg Brandl116aa622007-08-15 14:28:22 +00001472argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001473accept a *dt* argument of ``None``, or of class :class:`.datetime`.
Georg Brandl116aa622007-08-15 14:28:22 +00001474
1475When ``None`` is passed, it's up to the class designer to decide the best
1476response. For example, returning ``None`` is appropriate if the class wishes to
1477say that time objects don't participate in the :class:`tzinfo` protocols. It
1478may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1479there is no other convention for discovering the standard offset.
1480
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001481When a :class:`.datetime` object is passed in response to a :class:`.datetime`
Georg Brandl116aa622007-08-15 14:28:22 +00001482method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1483rely on this, unless user code calls :class:`tzinfo` methods directly. The
1484intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1485time, and not need worry about objects in other timezones.
1486
1487There is one more :class:`tzinfo` method that a subclass may wish to override:
1488
1489
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001490.. method:: tzinfo.fromutc(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001491
Senthil Kumaran023c6f72011-07-17 19:01:14 +08001492 This is called from the default :class:`datetime.astimezone()`
1493 implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s
1494 date and time data are to be viewed as expressing a UTC time. The purpose
1495 of :meth:`fromutc` is to adjust the date and time data, returning an
Senthil Kumarana6bac952011-07-04 11:28:30 -07001496 equivalent datetime in *self*'s local time.
Georg Brandl116aa622007-08-15 14:28:22 +00001497
1498 Most :class:`tzinfo` subclasses should be able to inherit the default
1499 :meth:`fromutc` implementation without problems. It's strong enough to handle
1500 fixed-offset time zones, and time zones accounting for both standard and
1501 daylight time, and the latter even if the DST transition times differ in
1502 different years. An example of a time zone the default :meth:`fromutc`
1503 implementation may not handle correctly in all cases is one where the standard
1504 offset (from UTC) depends on the specific date and time passed, which can happen
1505 for political reasons. The default implementations of :meth:`astimezone` and
1506 :meth:`fromutc` may not produce the result you want if the result is one of the
1507 hours straddling the moment the standard offset changes.
1508
1509 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1510 like::
1511
1512 def fromutc(self, dt):
1513 # raise ValueError error if dt.tzinfo is not self
1514 dtoff = dt.utcoffset()
1515 dtdst = dt.dst()
1516 # raise ValueError if dtoff is None or dtdst is None
1517 delta = dtoff - dtdst # this is self's standard offset
1518 if delta:
1519 dt += delta # convert to standard local time
1520 dtdst = dt.dst()
1521 # raise ValueError if dtdst is None
1522 if dtdst:
1523 return dt + dtdst
1524 else:
1525 return dt
1526
1527Example :class:`tzinfo` classes:
1528
1529.. literalinclude:: ../includes/tzinfo-examples.py
1530
Georg Brandl116aa622007-08-15 14:28:22 +00001531Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1532subclass accounting for both standard and daylight time, at the DST transition
1533points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00001534minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
15351:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001536
1537 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1538 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1539 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1540
1541 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1542
1543 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1544
1545When DST starts (the "start" line), the local wall clock leaps from 1:59 to
15463:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1547``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1548begins. In order for :meth:`astimezone` to make this guarantee, the
1549:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1550Eastern) to be in daylight time.
1551
1552When DST ends (the "end" line), there's a potentially worse problem: there's an
1553hour that can't be spelled unambiguously in local wall time: the last hour of
1554daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1555daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1556to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1557:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1558hours into the same local hour then. In the Eastern example, UTC times of the
1559form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1560:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1561consider times in the "repeated hour" to be in standard time. This is easily
1562arranged, as in the example, by expressing DST switch times in the time zone's
1563standard local time.
1564
1565Applications that can't bear such ambiguities should avoid using hybrid
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001566:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`,
1567or any other fixed-offset :class:`tzinfo` subclass (such as a class representing
1568only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
1569
Sandro Tosid11d0d62012-04-24 19:46:06 +02001570.. seealso::
1571
1572 `pytz <http://pypi.python.org/pypi/pytz/>`_
Sandro Tosi100b8892012-04-28 11:19:37 +02001573 The standard library has no :class:`tzinfo` instances except for UTC, but
1574 there exists a third-party library which brings the *IANA timezone
1575 database* (also known as the Olson database) to Python: *pytz*.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001576
Sandro Tosi100b8892012-04-28 11:19:37 +02001577 *pytz* contains up-to-date information and its usage is recommended.
1578
1579 `IANA timezone database <http://www.iana.org/time-zones>`_
1580 The Time Zone Database (often called tz or zoneinfo) contains code and
1581 data that represent the history of local time for many representative
1582 locations around the globe. It is updated periodically to reflect changes
1583 made by political bodies to time zone boundaries, UTC offsets, and
1584 daylight-saving rules.
Sandro Tosid11d0d62012-04-24 19:46:06 +02001585
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001586
1587.. _datetime-timezone:
1588
1589:class:`timezone` Objects
1590--------------------------
1591
1592A :class:`timezone` object represents a timezone that is defined by a
1593fixed offset from UTC. Note that objects of this class cannot be used
1594to represent timezone information in the locations where different
1595offsets are used in different days of the year or where historical
1596changes have been made to civil time.
1597
1598
1599.. class:: timezone(offset[, name])
1600
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001601 The *offset* argument must be specified as a :class:`timedelta`
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001602 object representing the difference between the local time and UTC. It must
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001603 be strictly between ``-timedelta(hours=24)`` and
1604 ``timedelta(hours=24)`` and represent a whole number of minutes,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001605 otherwise :exc:`ValueError` is raised.
1606
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001607 The *name* argument is optional. If specified it must be a string that
1608 is used as the value returned by the ``tzname(dt)`` method. Otherwise,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001609 ``tzname(dt)`` returns a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001610 *offset*, HH and MM are two digits of ``offset.hours`` and
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001611 ``offset.minutes`` respectively.
1612
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001613.. method:: timezone.utcoffset(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001614
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001615 Return the fixed value specified when the :class:`timezone` instance is
1616 constructed. The *dt* argument is ignored. The return value is a
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001617 :class:`timedelta` instance equal to the difference between the
1618 local time and UTC.
1619
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001620.. method:: timezone.tzname(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
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001623 constructed or a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001624 *offset*, HH and MM are two digits of ``offset.hours`` and
1625 ``offset.minutes`` respectively.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001626
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001627.. method:: timezone.dst(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001628
1629 Always returns ``None``.
1630
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001631.. method:: timezone.fromutc(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001632
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001633 Return ``dt + offset``. The *dt* argument must be an aware
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001634 :class:`.datetime` instance, with ``tzinfo`` set to ``self``.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001635
1636Class attributes:
1637
1638.. attribute:: timezone.utc
1639
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001640 The UTC timezone, ``timezone(timedelta(0))``.
Georg Brandl48310cd2009-01-03 21:18:54 +00001641
Georg Brandl116aa622007-08-15 14:28:22 +00001642
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001643.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00001644
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001645:meth:`strftime` and :meth:`strptime` Behavior
1646----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001647
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001648:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
Georg Brandl116aa622007-08-15 14:28:22 +00001649``strftime(format)`` method, to create a string representing the time under the
1650control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1651acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1652although not all objects support a :meth:`timetuple` method.
1653
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001654Conversely, the :meth:`datetime.strptime` class method creates a
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001655:class:`.datetime` object from a string representing a date and time and a
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001656corresponding format string. ``datetime.strptime(date_string, format)`` is
1657equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1658
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001659For :class:`.time` objects, the format codes for year, month, and day should not
Georg Brandl116aa622007-08-15 14:28:22 +00001660be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001661is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00001662
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001663For :class:`date` objects, the format codes for hours, minutes, seconds, and
1664microseconds should not be used, as :class:`date` objects have no such
1665values. If they're used anyway, ``0`` is substituted for them.
1666
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001667For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1668strings.
1669
1670For an aware object:
1671
1672``%z``
1673 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1674 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1675 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1676 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1677 replaced with the string ``'-0330'``.
1678
1679``%Z``
1680 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1681 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl116aa622007-08-15 14:28:22 +00001682
Georg Brandl116aa622007-08-15 14:28:22 +00001683The full set of format codes supported varies across platforms, because Python
1684calls the platform C library's :func:`strftime` function, and platform
Georg Brandl48310cd2009-01-03 21:18:54 +00001685variations are common.
Christian Heimes895627f2007-12-08 17:28:33 +00001686
1687The following is a list of all the format codes that the C standard (1989
1688version) requires, and these work on all platforms with a standard C
1689implementation. Note that the 1999 version of the C standard added additional
1690format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001691
Christian Heimes895627f2007-12-08 17:28:33 +00001692+-----------+--------------------------------+-------+
1693| Directive | Meaning | Notes |
1694+===========+================================+=======+
1695| ``%a`` | Locale's abbreviated weekday | |
1696| | name. | |
1697+-----------+--------------------------------+-------+
1698| ``%A`` | Locale's full weekday name. | |
1699+-----------+--------------------------------+-------+
1700| ``%b`` | Locale's abbreviated month | |
1701| | name. | |
1702+-----------+--------------------------------+-------+
1703| ``%B`` | Locale's full month name. | |
1704+-----------+--------------------------------+-------+
1705| ``%c`` | Locale's appropriate date and | |
1706| | time representation. | |
1707+-----------+--------------------------------+-------+
1708| ``%d`` | Day of the month as a decimal | |
1709| | number [01,31]. | |
1710+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001711| ``%f`` | Microsecond as a decimal | \(1) |
1712| | number [0,999999], zero-padded | |
1713| | on the left | |
1714+-----------+--------------------------------+-------+
Christian Heimes895627f2007-12-08 17:28:33 +00001715| ``%H`` | Hour (24-hour clock) as a | |
1716| | decimal number [00,23]. | |
1717+-----------+--------------------------------+-------+
1718| ``%I`` | Hour (12-hour clock) as a | |
1719| | decimal number [01,12]. | |
1720+-----------+--------------------------------+-------+
1721| ``%j`` | Day of the year as a decimal | |
1722| | number [001,366]. | |
1723+-----------+--------------------------------+-------+
1724| ``%m`` | Month as a decimal number | |
1725| | [01,12]. | |
1726+-----------+--------------------------------+-------+
1727| ``%M`` | Minute as a decimal number | |
1728| | [00,59]. | |
1729+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001730| ``%p`` | Locale's equivalent of either | \(2) |
Christian Heimes895627f2007-12-08 17:28:33 +00001731| | AM or PM. | |
1732+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001733| ``%S`` | Second as a decimal number | \(3) |
Alexander Belopolsky9971e002011-01-10 22:56:14 +00001734| | [00,59]. | |
Christian Heimes895627f2007-12-08 17:28:33 +00001735+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001736| ``%U`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001737| | (Sunday as the first day of | |
1738| | the week) as a decimal number | |
1739| | [00,53]. All days in a new | |
1740| | year preceding the first | |
1741| | Sunday are considered to be in | |
1742| | week 0. | |
1743+-----------+--------------------------------+-------+
1744| ``%w`` | Weekday as a decimal number | |
1745| | [0(Sunday),6]. | |
1746+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001747| ``%W`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001748| | (Monday as the first day of | |
1749| | the week) as a decimal number | |
1750| | [00,53]. All days in a new | |
1751| | year preceding the first | |
1752| | Monday are considered to be in | |
1753| | week 0. | |
1754+-----------+--------------------------------+-------+
1755| ``%x`` | Locale's appropriate date | |
1756| | representation. | |
1757+-----------+--------------------------------+-------+
1758| ``%X`` | Locale's appropriate time | |
1759| | representation. | |
1760+-----------+--------------------------------+-------+
1761| ``%y`` | Year without century as a | |
1762| | decimal number [00,99]. | |
1763+-----------+--------------------------------+-------+
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001764| ``%Y`` | Year with century as a decimal | \(5) |
1765| | number [0001,9999] (strptime), | |
1766| | [1000,9999] (strftime). | |
Christian Heimes895627f2007-12-08 17:28:33 +00001767+-----------+--------------------------------+-------+
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001768| ``%z`` | UTC offset in the form +HHMM | \(6) |
Christian Heimes895627f2007-12-08 17:28:33 +00001769| | or -HHMM (empty string if the | |
1770| | the object is naive). | |
1771+-----------+--------------------------------+-------+
1772| ``%Z`` | Time zone name (empty string | |
1773| | if the object is naive). | |
1774+-----------+--------------------------------+-------+
1775| ``%%`` | A literal ``'%'`` character. | |
1776+-----------+--------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001777
Christian Heimes895627f2007-12-08 17:28:33 +00001778Notes:
1779
1780(1)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001781 When used with the :meth:`strptime` method, the ``%f`` directive
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001782 accepts from one to six digits and zero pads on the right. ``%f`` is
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001783 an extension to the set of format characters in the C standard (but
1784 implemented separately in datetime objects, and therefore always
1785 available).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001786
1787(2)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001788 When used with the :meth:`strptime` method, the ``%p`` directive only affects
Christian Heimes895627f2007-12-08 17:28:33 +00001789 the output hour field if the ``%I`` directive is used to parse the hour.
1790
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001791(3)
Alexander Belopolsky9971e002011-01-10 22:56:14 +00001792 Unlike :mod:`time` module, :mod:`datetime` module does not support
1793 leap seconds.
Christian Heimes895627f2007-12-08 17:28:33 +00001794
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001795(4)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001796 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in
Christian Heimes895627f2007-12-08 17:28:33 +00001797 calculations when the day of the week and the year are specified.
1798
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001799(5)
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001800 For technical reasons, :meth:`strftime` method does not support
Alexander Belopolsky5fc850b2011-01-10 23:31:51 +00001801 dates before year 1000: ``t.strftime(format)`` will raise a
1802 :exc:`ValueError` when ``t.year < 1000`` even if ``format`` does
1803 not contain ``%Y`` directive. The :meth:`strptime` method can
1804 parse years in the full [1, 9999] range, but years < 1000 must be
1805 zero-filled to 4-digit width.
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001806
1807 .. versionchanged:: 3.2
1808 In previous versions, :meth:`strftime` method was restricted to
1809 years >= 1900.
1810
1811(6)
Christian Heimes895627f2007-12-08 17:28:33 +00001812 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1813 ``%z`` is replaced with the string ``'-0330'``.
Alexander Belopolskyca94f552010-06-17 18:30:34 +00001814
Georg Brandl67b21b72010-08-17 15:07:14 +00001815.. versionchanged:: 3.2
1816 When the ``%z`` directive is provided to the :meth:`strptime` method, an
Ezio Melotti35ec7f72011-10-02 12:44:50 +03001817 aware :class:`.datetime` object will be produced. The ``tzinfo`` of the
Georg Brandl67b21b72010-08-17 15:07:14 +00001818 result will be set to a :class:`timezone` instance.
R David Murray9075d8b2012-05-14 22:14:46 -04001819
1820.. rubric:: Footnotes
1821
1822.. [#] If, that is, we ignore the effects of Relativity