blob: 3789bebcb3288dfdb9ad63d1942b01de52c3ffa7 [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
14focus of the implementation is on efficient member extraction for output
15formatting and manipulation. For related
16functionality, see also the :mod:`time` and :mod:`calendar` modules.
17
18There are two kinds of date and time objects: "naive" and "aware". This
19distinction refers to whether the object has any notion of time zone, daylight
20saving time, or other kind of algorithmic or political time adjustment. Whether
21a naive :class:`datetime` object represents Coordinated Universal Time (UTC),
22local time, or time in some other timezone is purely up to the program, just
23like it's up to the program whether a particular number represents metres,
24miles, or mass. Naive :class:`datetime` objects are easy to understand and to
25work with, at the cost of ignoring some aspects of reality.
26
27For applications requiring more, :class:`datetime` and :class:`time` objects
28have an optional time zone information member, :attr:`tzinfo`, that can contain
29an instance of a subclass of the abstract :class:`tzinfo` class. These
30:class:`tzinfo` objects capture information about the offset from UTC time, the
31time zone name, and whether Daylight Saving Time is in effect. Note that no
32concrete :class:`tzinfo` classes are supplied by the :mod:`datetime` module.
33Supporting timezones at whatever level of detail is required is up to the
34application. The rules for time adjustment across the world are more political
35than rational, and there is no standard suitable for every application.
36
37The :mod:`datetime` module exports the following constants:
38
Georg Brandl116aa622007-08-15 14:28:22 +000039.. data:: MINYEAR
40
41 The smallest year number allowed in a :class:`date` or :class:`datetime` object.
42 :const:`MINYEAR` is ``1``.
43
44
45.. data:: MAXYEAR
46
47 The largest year number allowed in a :class:`date` or :class:`datetime` object.
48 :const:`MAXYEAR` is ``9999``.
49
50
51.. seealso::
52
53 Module :mod:`calendar`
54 General calendar related functions.
55
56 Module :mod:`time`
57 Time access and conversions.
58
59
60Available Types
61---------------
62
Georg Brandl116aa622007-08-15 14:28:22 +000063.. class:: date
Benjamin Petersonf3d7dbe2009-10-04 14:54:52 +000064 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000065
66 An idealized naive date, assuming the current Gregorian calendar always was, and
67 always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and
68 :attr:`day`.
69
70
71.. class:: time
Benjamin Petersonf3d7dbe2009-10-04 14:54:52 +000072 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000073
74 An idealized time, independent of any particular day, assuming that every day
75 has exactly 24\*60\*60 seconds (there is no notion of "leap seconds" here).
76 Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
77 and :attr:`tzinfo`.
78
79
80.. class:: datetime
Benjamin Petersonf3d7dbe2009-10-04 14:54:52 +000081 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000082
83 A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`,
84 :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
85 and :attr:`tzinfo`.
86
87
88.. class:: timedelta
Benjamin Petersonf3d7dbe2009-10-04 14:54:52 +000089 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000090
91 A duration expressing the difference between two :class:`date`, :class:`time`,
92 or :class:`datetime` instances to microsecond resolution.
93
94
95.. class:: tzinfo
96
97 An abstract base class for time zone information objects. These are used by the
98 :class:`datetime` and :class:`time` classes to provide a customizable notion of
99 time adjustment (for example, to account for time zone and/or daylight saving
100 time).
101
102Objects of these types are immutable.
103
104Objects of the :class:`date` type are always naive.
105
106An object *d* of type :class:`time` or :class:`datetime` may be naive or aware.
107*d* is aware if ``d.tzinfo`` is not ``None`` and ``d.tzinfo.utcoffset(d)`` does
108not return ``None``. If ``d.tzinfo`` is ``None``, or if ``d.tzinfo`` is not
109``None`` but ``d.tzinfo.utcoffset(d)`` returns ``None``, *d* is naive.
110
111The distinction between naive and aware doesn't apply to :class:`timedelta`
112objects.
113
114Subclass relationships::
115
116 object
117 timedelta
118 tzinfo
119 time
120 date
121 datetime
122
123
124.. _datetime-timedelta:
125
126:class:`timedelta` Objects
127--------------------------
128
129A :class:`timedelta` object represents a duration, the difference between two
130dates or times.
131
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000132.. class:: timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000133
Georg Brandl5c106642007-11-29 17:41:05 +0000134 All arguments are optional and default to ``0``. Arguments may be integers
Georg Brandl116aa622007-08-15 14:28:22 +0000135 or floats, and may be positive or negative.
136
137 Only *days*, *seconds* and *microseconds* are stored internally. Arguments are
138 converted to those units:
139
140 * A millisecond is converted to 1000 microseconds.
141 * A minute is converted to 60 seconds.
142 * An hour is converted to 3600 seconds.
143 * A week is converted to 7 days.
144
145 and days, seconds and microseconds are then normalized so that the
146 representation is unique, with
147
148 * ``0 <= microseconds < 1000000``
149 * ``0 <= seconds < 3600*24`` (the number of seconds in one day)
150 * ``-999999999 <= days <= 999999999``
151
152 If any argument is a float and there are fractional microseconds, the fractional
153 microseconds left over from all arguments are combined and their sum is rounded
154 to the nearest microsecond. If no argument is a float, the conversion and
155 normalization processes are exact (no information is lost).
156
157 If the normalized value of days lies outside the indicated range,
158 :exc:`OverflowError` is raised.
159
160 Note that normalization of negative values may be surprising at first. For
Christian Heimesfe337bf2008-03-23 21:54:12 +0000161 example,
Georg Brandl116aa622007-08-15 14:28:22 +0000162
Christian Heimes895627f2007-12-08 17:28:33 +0000163 >>> from datetime import timedelta
Georg Brandl116aa622007-08-15 14:28:22 +0000164 >>> d = timedelta(microseconds=-1)
165 >>> (d.days, d.seconds, d.microseconds)
166 (-1, 86399, 999999)
167
Georg Brandl116aa622007-08-15 14:28:22 +0000168
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000169Class attributes are:
Georg Brandl116aa622007-08-15 14:28:22 +0000170
171.. attribute:: timedelta.min
172
173 The most negative :class:`timedelta` object, ``timedelta(-999999999)``.
174
175
176.. attribute:: timedelta.max
177
178 The most positive :class:`timedelta` object, ``timedelta(days=999999999,
179 hours=23, minutes=59, seconds=59, microseconds=999999)``.
180
181
182.. attribute:: timedelta.resolution
183
184 The smallest possible difference between non-equal :class:`timedelta` objects,
185 ``timedelta(microseconds=1)``.
186
187Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``.
188``-timedelta.max`` is not representable as a :class:`timedelta` object.
189
190Instance attributes (read-only):
191
192+------------------+--------------------------------------------+
193| Attribute | Value |
194+==================+============================================+
195| ``days`` | Between -999999999 and 999999999 inclusive |
196+------------------+--------------------------------------------+
197| ``seconds`` | Between 0 and 86399 inclusive |
198+------------------+--------------------------------------------+
199| ``microseconds`` | Between 0 and 999999 inclusive |
200+------------------+--------------------------------------------+
201
202Supported operations:
203
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000204.. XXX this table is too wide!
Georg Brandl116aa622007-08-15 14:28:22 +0000205
206+--------------------------------+-----------------------------------------------+
207| Operation | Result |
208+================================+===============================================+
209| ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == |
210| | *t3* and *t1*-*t3* == *t2* are true. (1) |
211+--------------------------------+-----------------------------------------------+
212| ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* |
213| | == *t2* - *t3* and *t2* == *t1* + *t3* are |
214| | true. (1) |
215+--------------------------------+-----------------------------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000216| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer. |
Georg Brandl116aa622007-08-15 14:28:22 +0000217| | Afterwards *t1* // i == *t2* is true, |
218| | provided ``i != 0``. |
219+--------------------------------+-----------------------------------------------+
220| | In general, *t1* \* i == *t1* \* (i-1) + *t1* |
221| | is true. (1) |
222+--------------------------------+-----------------------------------------------+
223| ``t1 = t2 // i`` | The floor is computed and the remainder (if |
224| | any) is thrown away. (3) |
225+--------------------------------+-----------------------------------------------+
226| ``+t1`` | Returns a :class:`timedelta` object with the |
227| | same value. (2) |
228+--------------------------------+-----------------------------------------------+
229| ``-t1`` | equivalent to :class:`timedelta`\ |
230| | (-*t1.days*, -*t1.seconds*, |
231| | -*t1.microseconds*), and to *t1*\* -1. (1)(4) |
232+--------------------------------+-----------------------------------------------+
Georg Brandl628e6f92009-10-27 20:24:45 +0000233| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, and|
Georg Brandl116aa622007-08-15 14:28:22 +0000234| | to -*t* when ``t.days < 0``. (2) |
235+--------------------------------+-----------------------------------------------+
236
237Notes:
238
239(1)
240 This is exact, but may overflow.
241
242(2)
243 This is exact, and cannot overflow.
244
245(3)
246 Division by 0 raises :exc:`ZeroDivisionError`.
247
248(4)
249 -*timedelta.max* is not representable as a :class:`timedelta` object.
250
251In addition to the operations listed above :class:`timedelta` objects support
252certain additions and subtractions with :class:`date` and :class:`datetime`
253objects (see below).
254
255Comparisons of :class:`timedelta` objects are supported with the
256:class:`timedelta` object representing the smaller duration considered to be the
257smaller timedelta. In order to stop mixed-type comparisons from falling back to
258the default comparison by object address, when a :class:`timedelta` object is
259compared to an object of a different type, :exc:`TypeError` is raised unless the
260comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
261:const:`True`, respectively.
262
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000263:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl116aa622007-08-15 14:28:22 +0000264efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
265considered to be true if and only if it isn't equal to ``timedelta(0)``.
266
Christian Heimesfe337bf2008-03-23 21:54:12 +0000267Example usage:
Georg Brandl48310cd2009-01-03 21:18:54 +0000268
Christian Heimes895627f2007-12-08 17:28:33 +0000269 >>> from datetime import timedelta
270 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000271 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Christian Heimes895627f2007-12-08 17:28:33 +0000272 ... minutes=50, seconds=600) # adds up to 365 days
273 >>> year == another_year
274 True
275 >>> ten_years = 10 * year
276 >>> ten_years, ten_years.days // 365
277 (datetime.timedelta(3650), 10)
278 >>> nine_years = ten_years - year
279 >>> nine_years, nine_years.days // 365
280 (datetime.timedelta(3285), 9)
281 >>> three_years = nine_years // 3;
282 >>> three_years, three_years.days // 365
283 (datetime.timedelta(1095), 3)
284 >>> abs(three_years - ten_years) == 2 * three_years + year
285 True
286
Georg Brandl116aa622007-08-15 14:28:22 +0000287
288.. _datetime-date:
289
290:class:`date` Objects
291---------------------
292
293A :class:`date` object represents a date (year, month and day) in an idealized
294calendar, the current Gregorian calendar indefinitely extended in both
295directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
296called day number 2, and so on. This matches the definition of the "proleptic
297Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
298where it's the base calendar for all computations. See the book for algorithms
299for converting between proleptic Gregorian ordinals and many other calendar
300systems.
301
302
303.. class:: date(year, month, day)
304
Georg Brandl5c106642007-11-29 17:41:05 +0000305 All arguments are required. Arguments may be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000306 ranges:
307
308 * ``MINYEAR <= year <= MAXYEAR``
309 * ``1 <= month <= 12``
310 * ``1 <= day <= number of days in the given month and year``
311
312 If an argument outside those ranges is given, :exc:`ValueError` is raised.
313
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000314
Georg Brandl116aa622007-08-15 14:28:22 +0000315Other constructors, all class methods:
316
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000317.. classmethod:: date.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000318
319 Return the current local date. This is equivalent to
320 ``date.fromtimestamp(time.time())``.
321
322
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000323.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000324
325 Return the local date corresponding to the POSIX timestamp, such as is returned
326 by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out
327 of the range of values supported by the platform C :cfunc:`localtime` function.
328 It's common for this to be restricted to years from 1970 through 2038. Note
329 that on non-POSIX systems that include leap seconds in their notion of a
330 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
331
332
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000333.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000334
335 Return the date corresponding to the proleptic Gregorian ordinal, where January
336 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
337 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
338 d``.
339
Georg Brandl116aa622007-08-15 14:28:22 +0000340
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000341Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000342
343.. attribute:: date.min
344
345 The earliest representable date, ``date(MINYEAR, 1, 1)``.
346
347
348.. attribute:: date.max
349
350 The latest representable date, ``date(MAXYEAR, 12, 31)``.
351
352
353.. attribute:: date.resolution
354
355 The smallest possible difference between non-equal date objects,
356 ``timedelta(days=1)``.
357
Georg Brandl116aa622007-08-15 14:28:22 +0000358
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000359Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000360
361.. attribute:: date.year
362
363 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
364
365
366.. attribute:: date.month
367
368 Between 1 and 12 inclusive.
369
370
371.. attribute:: date.day
372
373 Between 1 and the number of days in the given month of the given year.
374
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000375
Georg Brandl116aa622007-08-15 14:28:22 +0000376Supported operations:
377
378+-------------------------------+----------------------------------------------+
379| Operation | Result |
380+===============================+==============================================+
381| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
382| | from *date1*. (1) |
383+-------------------------------+----------------------------------------------+
384| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
385| | timedelta == date1``. (2) |
386+-------------------------------+----------------------------------------------+
387| ``timedelta = date1 - date2`` | \(3) |
388+-------------------------------+----------------------------------------------+
389| ``date1 < date2`` | *date1* is considered less than *date2* when |
390| | *date1* precedes *date2* in time. (4) |
391+-------------------------------+----------------------------------------------+
392
393Notes:
394
395(1)
396 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
397 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
398 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
399 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
400 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
401
402(2)
403 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
404 isolation can overflow in cases where date1 - timedelta does not.
405 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
406
407(3)
408 This is exact, and cannot overflow. timedelta.seconds and
409 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
410
411(4)
412 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
413 date2.toordinal()``. In order to stop comparison from falling back to the
414 default scheme of comparing object addresses, date comparison normally raises
415 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
416 However, ``NotImplemented`` is returned instead if the other comparand has a
417 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
418 chance at implementing mixed-type comparison. If not, when a :class:`date`
419 object is compared to an object of a different type, :exc:`TypeError` is raised
420 unless the comparison is ``==`` or ``!=``. The latter cases return
421 :const:`False` or :const:`True`, respectively.
422
423Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
424objects are considered to be true.
425
426Instance methods:
427
Georg Brandl116aa622007-08-15 14:28:22 +0000428.. method:: date.replace(year, month, day)
429
430 Return a date with the same value, except for those members given new values by
431 whichever keyword arguments are specified. For example, if ``d == date(2002,
432 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
433
434
435.. method:: date.timetuple()
436
437 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
438 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
439 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
440 d.weekday(), d.toordinal() - date(d.year, 1, 1).toordinal() + 1, -1))``
441
442
443.. method:: date.toordinal()
444
445 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
446 has ordinal 1. For any :class:`date` object *d*,
447 ``date.fromordinal(d.toordinal()) == d``.
448
449
450.. method:: date.weekday()
451
452 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
453 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
454 :meth:`isoweekday`.
455
456
457.. method:: date.isoweekday()
458
459 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
460 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
461 :meth:`weekday`, :meth:`isocalendar`.
462
463
464.. method:: date.isocalendar()
465
466 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
467
468 The ISO calendar is a widely used variant of the Gregorian calendar. See
Mark Dickinson7e866642009-11-03 16:29:43 +0000469 http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
470 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000471
472 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
473 Monday and ends on a Sunday. The first week of an ISO year is the first
474 (Gregorian) calendar week of a year containing a Thursday. This is called week
475 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
476
477 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
478 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
479 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
480 4).isocalendar() == (2004, 1, 7)``.
481
482
483.. method:: date.isoformat()
484
485 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
486 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
487
488
489.. method:: date.__str__()
490
491 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
492
493
494.. method:: date.ctime()
495
496 Return a string representing the date, for example ``date(2002, 12,
497 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
498 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
499 :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
500 :meth:`date.ctime` does not invoke) conforms to the C standard.
501
502
503.. method:: date.strftime(format)
504
505 Return a string representing the date, controlled by an explicit format string.
506 Format codes referring to hours, minutes or seconds will see 0 values. See
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000507 section :ref:`strftime-strptime-behavior`.
508
Georg Brandl116aa622007-08-15 14:28:22 +0000509
Christian Heimes895627f2007-12-08 17:28:33 +0000510Example of counting days to an event::
511
512 >>> import time
513 >>> from datetime import date
514 >>> today = date.today()
515 >>> today
516 datetime.date(2007, 12, 5)
517 >>> today == date.fromtimestamp(time.time())
518 True
519 >>> my_birthday = date(today.year, 6, 24)
520 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000521 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000522 >>> my_birthday
523 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000524 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000525 >>> time_to_birthday.days
526 202
527
Christian Heimesfe337bf2008-03-23 21:54:12 +0000528Example of working with :class:`date`:
529
530.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000531
532 >>> from datetime import date
533 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
534 >>> d
535 datetime.date(2002, 3, 11)
536 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000537 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000538 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000539 2002 # year
540 3 # month
541 11 # day
542 0
543 0
544 0
545 0 # weekday (0 = Monday)
546 70 # 70th day in the year
547 -1
548 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000549 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000550 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000551 2002 # ISO year
552 11 # ISO week number
553 1 # ISO day number ( 1 = Monday )
554 >>> d.isoformat()
555 '2002-03-11'
556 >>> d.strftime("%d/%m/%y")
557 '11/03/02'
558 >>> d.strftime("%A %d. %B %Y")
559 'Monday 11. March 2002'
560
Georg Brandl116aa622007-08-15 14:28:22 +0000561
562.. _datetime-datetime:
563
564:class:`datetime` Objects
565-------------------------
566
567A :class:`datetime` object is a single object containing all the information
568from a :class:`date` object and a :class:`time` object. Like a :class:`date`
569object, :class:`datetime` assumes the current Gregorian calendar extended in
570both directions; like a time object, :class:`datetime` assumes there are exactly
5713600\*24 seconds in every day.
572
573Constructor:
574
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000575.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000576
577 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000578 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
579 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000580
581 * ``MINYEAR <= year <= MAXYEAR``
582 * ``1 <= month <= 12``
583 * ``1 <= day <= number of days in the given month and year``
584 * ``0 <= hour < 24``
585 * ``0 <= minute < 60``
586 * ``0 <= second < 60``
587 * ``0 <= microsecond < 1000000``
588
589 If an argument outside those ranges is given, :exc:`ValueError` is raised.
590
591Other constructors, all class methods:
592
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000593.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000594
595 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
596 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
597 :meth:`fromtimestamp`.
598
599
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000600.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000601
602 Return the current local date and time. If optional argument *tz* is ``None``
603 or not specified, this is like :meth:`today`, but, if possible, supplies more
604 precision than can be gotten from going through a :func:`time.time` timestamp
605 (for example, this may be possible on platforms supplying the C
606 :cfunc:`gettimeofday` function).
607
608 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
609 current date and time are converted to *tz*'s time zone. In this case the
610 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
611 See also :meth:`today`, :meth:`utcnow`.
612
613
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000614.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000615
616 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
617 :meth:`now`, but returns the current UTC date and time, as a naive
618 :class:`datetime` object. See also :meth:`now`.
619
620
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000621.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000622
623 Return the local date and time corresponding to the POSIX timestamp, such as is
624 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
625 specified, the timestamp is converted to the platform's local date and time, and
626 the returned :class:`datetime` object is naive.
627
628 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
629 timestamp is converted to *tz*'s time zone. In this case the result is
630 equivalent to
631 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
632
633 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
634 the range of values supported by the platform C :cfunc:`localtime` or
635 :cfunc:`gmtime` functions. It's common for this to be restricted to years in
636 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
637 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
638 and then it's possible to have two timestamps differing by a second that yield
639 identical :class:`datetime` objects. See also :meth:`utcfromtimestamp`.
640
641
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000642.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000643
644 Return the UTC :class:`datetime` corresponding to the POSIX timestamp, with
645 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
646 out of the range of values supported by the platform C :cfunc:`gmtime` function.
647 It's common for this to be restricted to years in 1970 through 2038. See also
648 :meth:`fromtimestamp`.
649
650
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000651.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000652
653 Return the :class:`datetime` corresponding to the proleptic Gregorian ordinal,
654 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
655 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
656 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
657
658
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000659.. classmethod:: datetime.combine(date, time)
Georg Brandl116aa622007-08-15 14:28:22 +0000660
661 Return a new :class:`datetime` object whose date members are equal to the given
662 :class:`date` object's, and whose time and :attr:`tzinfo` members are equal to
663 the given :class:`time` object's. For any :class:`datetime` object *d*, ``d ==
664 datetime.combine(d.date(), d.timetz())``. If date is a :class:`datetime`
665 object, its time and :attr:`tzinfo` members are ignored.
666
667
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000668.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000669
670 Return a :class:`datetime` corresponding to *date_string*, parsed according to
671 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
672 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
673 can't be parsed by :func:`time.strptime` or if it returns a value which isn't a
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000674 time tuple. See section :ref:`strftime-strptime-behavior`.
675
Georg Brandl116aa622007-08-15 14:28:22 +0000676
Georg Brandl116aa622007-08-15 14:28:22 +0000677
678Class attributes:
679
Georg Brandl116aa622007-08-15 14:28:22 +0000680.. attribute:: datetime.min
681
682 The earliest representable :class:`datetime`, ``datetime(MINYEAR, 1, 1,
683 tzinfo=None)``.
684
685
686.. attribute:: datetime.max
687
688 The latest representable :class:`datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
689 59, 999999, tzinfo=None)``.
690
691
692.. attribute:: datetime.resolution
693
694 The smallest possible difference between non-equal :class:`datetime` objects,
695 ``timedelta(microseconds=1)``.
696
Georg Brandl116aa622007-08-15 14:28:22 +0000697
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000698Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000699
700.. attribute:: datetime.year
701
702 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
703
704
705.. attribute:: datetime.month
706
707 Between 1 and 12 inclusive.
708
709
710.. attribute:: datetime.day
711
712 Between 1 and the number of days in the given month of the given year.
713
714
715.. attribute:: datetime.hour
716
717 In ``range(24)``.
718
719
720.. attribute:: datetime.minute
721
722 In ``range(60)``.
723
724
725.. attribute:: datetime.second
726
727 In ``range(60)``.
728
729
730.. attribute:: datetime.microsecond
731
732 In ``range(1000000)``.
733
734
735.. attribute:: datetime.tzinfo
736
737 The object passed as the *tzinfo* argument to the :class:`datetime` constructor,
738 or ``None`` if none was passed.
739
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000740
Georg Brandl116aa622007-08-15 14:28:22 +0000741Supported operations:
742
743+---------------------------------------+-------------------------------+
744| Operation | Result |
745+=======================================+===============================+
746| ``datetime2 = datetime1 + timedelta`` | \(1) |
747+---------------------------------------+-------------------------------+
748| ``datetime2 = datetime1 - timedelta`` | \(2) |
749+---------------------------------------+-------------------------------+
750| ``timedelta = datetime1 - datetime2`` | \(3) |
751+---------------------------------------+-------------------------------+
752| ``datetime1 < datetime2`` | Compares :class:`datetime` to |
753| | :class:`datetime`. (4) |
754+---------------------------------------+-------------------------------+
755
756(1)
757 datetime2 is a duration of timedelta removed from datetime1, moving forward in
758 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
759 result has the same :attr:`tzinfo` member as the input datetime, and datetime2 -
760 datetime1 == timedelta after. :exc:`OverflowError` is raised if datetime2.year
761 would be smaller than :const:`MINYEAR` or larger than :const:`MAXYEAR`. Note
762 that no time zone adjustments are done even if the input is an aware object.
763
764(2)
765 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
766 addition, the result has the same :attr:`tzinfo` member as the input datetime,
767 and no time zone adjustments are done even if the input is aware. This isn't
768 quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation
769 can overflow in cases where datetime1 - timedelta does not.
770
771(3)
772 Subtraction of a :class:`datetime` from a :class:`datetime` is defined only if
773 both operands are naive, or if both are aware. If one is aware and the other is
774 naive, :exc:`TypeError` is raised.
775
776 If both are naive, or both are aware and have the same :attr:`tzinfo` member,
777 the :attr:`tzinfo` members are ignored, and the result is a :class:`timedelta`
778 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
779 are done in this case.
780
781 If both are aware and have different :attr:`tzinfo` members, ``a-b`` acts as if
782 *a* and *b* were first converted to naive UTC datetimes first. The result is
783 ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) -
784 b.utcoffset())`` except that the implementation never overflows.
785
786(4)
787 *datetime1* is considered less than *datetime2* when *datetime1* precedes
788 *datetime2* in time.
789
790 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
791 If both comparands are aware, and have the same :attr:`tzinfo` member, the
792 common :attr:`tzinfo` member is ignored and the base datetimes are compared. If
793 both comparands are aware and have different :attr:`tzinfo` members, the
794 comparands are first adjusted by subtracting their UTC offsets (obtained from
795 ``self.utcoffset()``).
796
797 .. note::
798
799 In order to stop comparison from falling back to the default scheme of comparing
800 object addresses, datetime comparison normally raises :exc:`TypeError` if the
801 other comparand isn't also a :class:`datetime` object. However,
802 ``NotImplemented`` is returned instead if the other comparand has a
803 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
804 chance at implementing mixed-type comparison. If not, when a :class:`datetime`
805 object is compared to an object of a different type, :exc:`TypeError` is raised
806 unless the comparison is ``==`` or ``!=``. The latter cases return
807 :const:`False` or :const:`True`, respectively.
808
809:class:`datetime` objects can be used as dictionary keys. In Boolean contexts,
810all :class:`datetime` objects are considered to be true.
811
812Instance methods:
813
Georg Brandl116aa622007-08-15 14:28:22 +0000814.. method:: datetime.date()
815
816 Return :class:`date` object with same year, month and day.
817
818
819.. method:: datetime.time()
820
821 Return :class:`time` object with same hour, minute, second and microsecond.
822 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
823
824
825.. method:: datetime.timetz()
826
827 Return :class:`time` object with same hour, minute, second, microsecond, and
828 tzinfo members. See also method :meth:`time`.
829
830
831.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
832
833 Return a datetime with the same members, except for those members given new
834 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
835 can be specified to create a naive datetime from an aware datetime with no
836 conversion of date and time members.
837
838
839.. method:: datetime.astimezone(tz)
840
841 Return a :class:`datetime` object with new :attr:`tzinfo` member *tz*, adjusting
842 the date and time members so the result is the same UTC time as *self*, but in
843 *tz*'s local time.
844
845 *tz* must be an instance of a :class:`tzinfo` subclass, and its
846 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
847 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
848 not return ``None``).
849
850 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
851 adjustment of date or time members is performed. Else the result is local time
852 in time zone *tz*, representing the same UTC time as *self*: after ``astz =
853 dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have the same date
854 and time members as ``dt - dt.utcoffset()``. The discussion of class
855 :class:`tzinfo` explains the cases at Daylight Saving Time transition boundaries
856 where this cannot be achieved (an issue only if *tz* models both standard and
857 daylight time).
858
859 If you merely want to attach a time zone object *tz* to a datetime *dt* without
860 adjustment of date and time members, use ``dt.replace(tzinfo=tz)``. If you
861 merely want to remove the time zone object from an aware datetime *dt* without
862 conversion of date and time members, use ``dt.replace(tzinfo=None)``.
863
864 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
865 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
866 Ignoring error cases, :meth:`astimezone` acts like::
867
868 def astimezone(self, tz):
869 if self.tzinfo is tz:
870 return self
871 # Convert self to UTC, and attach the new time zone object.
872 utc = (self - self.utcoffset()).replace(tzinfo=tz)
873 # Convert from UTC to tz's local time.
874 return tz.fromutc(utc)
875
876
877.. method:: datetime.utcoffset()
878
879 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
880 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
881 return ``None``, or a :class:`timedelta` object representing a whole number of
882 minutes with magnitude less than one day.
883
884
885.. method:: datetime.dst()
886
887 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
888 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
889 ``None``, or a :class:`timedelta` object representing a whole number of minutes
890 with magnitude less than one day.
891
892
893.. method:: datetime.tzname()
894
895 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
896 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
897 ``None`` or a string object,
898
899
900.. method:: datetime.timetuple()
901
902 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
903 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
904 d.hour, d.minute, d.second, d.weekday(), d.toordinal() - date(d.year, 1,
905 1).toordinal() + 1, dst))`` The :attr:`tm_isdst` flag of the result is set
906 according to the :meth:`dst` method: :attr:`tzinfo` is ``None`` or :meth:`dst`
907 returns ``None``, :attr:`tm_isdst` is set to ``-1``; else if :meth:`dst`
908 returns a non-zero value, :attr:`tm_isdst` is set to ``1``; else ``tm_isdst`` is
909 set to ``0``.
910
911
912.. method:: datetime.utctimetuple()
913
914 If :class:`datetime` instance *d* is naive, this is the same as
915 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
916 ``d.dst()`` returns. DST is never in effect for a UTC time.
917
918 If *d* is aware, *d* is normalized to UTC time, by subtracting
919 ``d.utcoffset()``, and a :class:`time.struct_time` for the normalized time is
920 returned. :attr:`tm_isdst` is forced to 0. Note that the result's
921 :attr:`tm_year` member may be :const:`MINYEAR`\ -1 or :const:`MAXYEAR`\ +1, if
922 *d*.year was ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
923 boundary.
924
925
926.. method:: datetime.toordinal()
927
928 Return the proleptic Gregorian ordinal of the date. The same as
929 ``self.date().toordinal()``.
930
931
932.. method:: datetime.weekday()
933
934 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
935 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
936
937
938.. method:: datetime.isoweekday()
939
940 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
941 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
942 :meth:`isocalendar`.
943
944
945.. method:: datetime.isocalendar()
946
947 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
948 ``self.date().isocalendar()``.
949
950
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000951.. method:: datetime.isoformat(sep='T')
Georg Brandl116aa622007-08-15 14:28:22 +0000952
953 Return a string representing the date and time in ISO 8601 format,
954 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
955 YYYY-MM-DDTHH:MM:SS
956
957 If :meth:`utcoffset` does not return ``None``, a 6-character string is
958 appended, giving the UTC offset in (signed) hours and minutes:
959 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
960 YYYY-MM-DDTHH:MM:SS+HH:MM
961
962 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000963 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +0000964
965 >>> from datetime import tzinfo, timedelta, datetime
966 >>> class TZ(tzinfo):
967 ... def utcoffset(self, dt): return timedelta(minutes=-399)
968 ...
969 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
970 '2002-12-25 00:00:00-06:39'
971
972
973.. method:: datetime.__str__()
974
975 For a :class:`datetime` instance *d*, ``str(d)`` is equivalent to
976 ``d.isoformat(' ')``.
977
978
979.. method:: datetime.ctime()
980
981 Return a string representing the date and time, for example ``datetime(2002, 12,
982 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
983 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
984 native C :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
985 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
986
987
988.. method:: datetime.strftime(format)
989
990 Return a string representing the date and time, controlled by an explicit format
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000991 string. See section :ref:`strftime-strptime-behavior`.
992
Georg Brandl116aa622007-08-15 14:28:22 +0000993
Christian Heimesfe337bf2008-03-23 21:54:12 +0000994Examples of working with datetime objects:
995
996.. doctest::
997
Christian Heimes895627f2007-12-08 17:28:33 +0000998 >>> from datetime import datetime, date, time
999 >>> # Using datetime.combine()
1000 >>> d = date(2005, 7, 14)
1001 >>> t = time(12, 30)
1002 >>> datetime.combine(d, t)
1003 datetime.datetime(2005, 7, 14, 12, 30)
1004 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001005 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001006 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001007 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001008 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1009 >>> # Using datetime.strptime()
1010 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1011 >>> dt
1012 datetime.datetime(2006, 11, 21, 16, 30)
1013 >>> # Using datetime.timetuple() to get tuple of all attributes
1014 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001015 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001016 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001017 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001018 2006 # year
1019 11 # month
1020 21 # day
1021 16 # hour
1022 30 # minute
1023 0 # second
1024 1 # weekday (0 = Monday)
1025 325 # number of days since 1st January
1026 -1 # dst - method tzinfo.dst() returned None
1027 >>> # Date in ISO format
1028 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001029 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001030 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001031 ...
1032 2006 # ISO year
1033 47 # ISO week
1034 2 # ISO weekday
1035 >>> # Formatting datetime
1036 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1037 'Tuesday, 21. November 2006 04:30PM'
1038
Christian Heimesfe337bf2008-03-23 21:54:12 +00001039Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001040
1041 >>> from datetime import timedelta, datetime, tzinfo
1042 >>> class GMT1(tzinfo):
1043 ... def __init__(self): # DST starts last Sunday in March
1044 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1045 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001046 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001047 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1048 ... def utcoffset(self, dt):
1049 ... return timedelta(hours=1) + self.dst(dt)
Georg Brandl48310cd2009-01-03 21:18:54 +00001050 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001051 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1052 ... return timedelta(hours=1)
1053 ... else:
1054 ... return timedelta(0)
1055 ... def tzname(self,dt):
1056 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001057 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001058 >>> class GMT2(tzinfo):
1059 ... def __init__(self):
Georg Brandl48310cd2009-01-03 21:18:54 +00001060 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001061 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001062 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001063 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1064 ... def utcoffset(self, dt):
1065 ... return timedelta(hours=1) + self.dst(dt)
1066 ... def dst(self, dt):
1067 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1068 ... return timedelta(hours=2)
1069 ... else:
1070 ... return timedelta(0)
1071 ... def tzname(self,dt):
1072 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001073 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001074 >>> gmt1 = GMT1()
1075 >>> # Daylight Saving Time
1076 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1077 >>> dt1.dst()
1078 datetime.timedelta(0)
1079 >>> dt1.utcoffset()
1080 datetime.timedelta(0, 3600)
1081 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1082 >>> dt2.dst()
1083 datetime.timedelta(0, 3600)
1084 >>> dt2.utcoffset()
1085 datetime.timedelta(0, 7200)
1086 >>> # Convert datetime to another time zone
1087 >>> dt3 = dt2.astimezone(GMT2())
1088 >>> dt3 # doctest: +ELLIPSIS
1089 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1090 >>> dt2 # doctest: +ELLIPSIS
1091 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1092 >>> dt2.utctimetuple() == dt3.utctimetuple()
1093 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001094
Christian Heimes895627f2007-12-08 17:28:33 +00001095
Georg Brandl116aa622007-08-15 14:28:22 +00001096
1097.. _datetime-time:
1098
1099:class:`time` Objects
1100---------------------
1101
1102A time object represents a (local) time of day, independent of any particular
1103day, and subject to adjustment via a :class:`tzinfo` object.
1104
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001105.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001106
1107 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001108 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001109 following ranges:
1110
1111 * ``0 <= hour < 24``
1112 * ``0 <= minute < 60``
1113 * ``0 <= second < 60``
1114 * ``0 <= microsecond < 1000000``.
1115
1116 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1117 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1118
1119Class attributes:
1120
1121
1122.. attribute:: time.min
1123
1124 The earliest representable :class:`time`, ``time(0, 0, 0, 0)``.
1125
1126
1127.. attribute:: time.max
1128
1129 The latest representable :class:`time`, ``time(23, 59, 59, 999999)``.
1130
1131
1132.. attribute:: time.resolution
1133
1134 The smallest possible difference between non-equal :class:`time` objects,
1135 ``timedelta(microseconds=1)``, although note that arithmetic on :class:`time`
1136 objects is not supported.
1137
Georg Brandl116aa622007-08-15 14:28:22 +00001138
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001139Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001140
1141.. attribute:: time.hour
1142
1143 In ``range(24)``.
1144
1145
1146.. attribute:: time.minute
1147
1148 In ``range(60)``.
1149
1150
1151.. attribute:: time.second
1152
1153 In ``range(60)``.
1154
1155
1156.. attribute:: time.microsecond
1157
1158 In ``range(1000000)``.
1159
1160
1161.. attribute:: time.tzinfo
1162
1163 The object passed as the tzinfo argument to the :class:`time` constructor, or
1164 ``None`` if none was passed.
1165
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001166
Georg Brandl116aa622007-08-15 14:28:22 +00001167Supported operations:
1168
1169* comparison of :class:`time` to :class:`time`, where *a* is considered less
1170 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1171 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
1172 the same :attr:`tzinfo` member, the common :attr:`tzinfo` member is ignored and
1173 the base times are compared. If both comparands are aware and have different
1174 :attr:`tzinfo` members, the comparands are first adjusted by subtracting their
1175 UTC offsets (obtained from ``self.utcoffset()``). In order to stop mixed-type
1176 comparisons from falling back to the default comparison by object address, when
1177 a :class:`time` object is compared to an object of a different type,
1178 :exc:`TypeError` is raised unless the comparison is ``==`` or ``!=``. The
1179 latter cases return :const:`False` or :const:`True`, respectively.
1180
1181* hash, use as dict key
1182
1183* efficient pickling
1184
1185* in Boolean contexts, a :class:`time` object is considered to be true if and
1186 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1187 ``0`` if that's ``None``), the result is non-zero.
1188
Georg Brandl116aa622007-08-15 14:28:22 +00001189
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001190Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001191
1192.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1193
1194 Return a :class:`time` with the same value, except for those members given new
1195 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
1196 can be specified to create a naive :class:`time` from an aware :class:`time`,
1197 without conversion of the time members.
1198
1199
1200.. method:: time.isoformat()
1201
1202 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1203 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1204 6-character string is appended, giving the UTC offset in (signed) hours and
1205 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1206
1207
1208.. method:: time.__str__()
1209
1210 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1211
1212
1213.. method:: time.strftime(format)
1214
1215 Return a string representing the time, controlled by an explicit format string.
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001216 See section :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001217
1218
1219.. method:: time.utcoffset()
1220
1221 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1222 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1223 return ``None`` or a :class:`timedelta` object representing a whole number of
1224 minutes with magnitude less than one day.
1225
1226
1227.. method:: time.dst()
1228
1229 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1230 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1231 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1232 with magnitude less than one day.
1233
1234
1235.. method:: time.tzname()
1236
1237 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1238 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1239 return ``None`` or a string object.
1240
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001241
Christian Heimesfe337bf2008-03-23 21:54:12 +00001242Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001243
Christian Heimes895627f2007-12-08 17:28:33 +00001244 >>> from datetime import time, tzinfo
1245 >>> class GMT1(tzinfo):
1246 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001247 ... return timedelta(hours=1)
1248 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001249 ... return timedelta(0)
1250 ... def tzname(self,dt):
1251 ... return "Europe/Prague"
1252 ...
1253 >>> t = time(12, 10, 30, tzinfo=GMT1())
1254 >>> t # doctest: +ELLIPSIS
1255 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1256 >>> gmt = GMT1()
1257 >>> t.isoformat()
1258 '12:10:30+01:00'
1259 >>> t.dst()
1260 datetime.timedelta(0)
1261 >>> t.tzname()
1262 'Europe/Prague'
1263 >>> t.strftime("%H:%M:%S %Z")
1264 '12:10:30 Europe/Prague'
1265
Georg Brandl116aa622007-08-15 14:28:22 +00001266
1267.. _datetime-tzinfo:
1268
1269:class:`tzinfo` Objects
1270-----------------------
1271
Brett Cannone1327f72009-01-29 04:10:21 +00001272:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001273instantiated directly. You need to derive a concrete subclass, and (at least)
1274supply implementations of the standard :class:`tzinfo` methods needed by the
1275:class:`datetime` methods you use. The :mod:`datetime` module does not supply
1276any concrete subclasses of :class:`tzinfo`.
1277
1278An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1279constructors for :class:`datetime` and :class:`time` objects. The latter objects
1280view their members as being in local time, and the :class:`tzinfo` object
1281supports methods revealing offset of local time from UTC, the name of the time
1282zone, and DST offset, all relative to a date or time object passed to them.
1283
1284Special requirement for pickling: A :class:`tzinfo` subclass must have an
1285:meth:`__init__` method that can be called with no arguments, else it can be
1286pickled but possibly not unpickled again. This is a technical requirement that
1287may be relaxed in the future.
1288
1289A concrete subclass of :class:`tzinfo` may need to implement the following
1290methods. Exactly which methods are needed depends on the uses made of aware
1291:mod:`datetime` objects. If in doubt, simply implement all of them.
1292
1293
1294.. method:: tzinfo.utcoffset(self, dt)
1295
1296 Return offset of local time from UTC, in minutes east of UTC. If local time is
1297 west of UTC, this should be negative. Note that this is intended to be the
1298 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1299 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1300 the UTC offset isn't known, return ``None``. Else the value returned must be a
1301 :class:`timedelta` object specifying a whole number of minutes in the range
1302 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1303 than one day). Most implementations of :meth:`utcoffset` will probably look
1304 like one of these two::
1305
1306 return CONSTANT # fixed-offset class
1307 return CONSTANT + self.dst(dt) # daylight-aware class
1308
1309 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1310 ``None`` either.
1311
1312 The default implementation of :meth:`utcoffset` raises
1313 :exc:`NotImplementedError`.
1314
1315
1316.. method:: tzinfo.dst(self, dt)
1317
1318 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1319 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1320 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1321 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1322 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1323 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1324 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
1325 member's :meth:`dst` method to determine how the :attr:`tm_isdst` flag should be
1326 set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for DST changes
1327 when crossing time zones.
1328
1329 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1330 daylight times must be consistent in this sense:
1331
1332 ``tz.utcoffset(dt) - tz.dst(dt)``
1333
1334 must return the same result for every :class:`datetime` *dt* with ``dt.tzinfo ==
1335 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1336 zone's "standard offset", which should not depend on the date or the time, but
1337 only on geographic location. The implementation of :meth:`datetime.astimezone`
1338 relies on this, but cannot detect violations; it's the programmer's
1339 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1340 this, it may be able to override the default implementation of
1341 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1342
1343 Most implementations of :meth:`dst` will probably look like one of these two::
1344
1345 def dst(self):
1346 # a fixed-offset class: doesn't account for DST
1347 return timedelta(0)
1348
1349 or ::
1350
1351 def dst(self):
1352 # Code to set dston and dstoff to the time zone's DST
1353 # transition times based on the input dt.year, and expressed
1354 # in standard local time. Then
1355
1356 if dston <= dt.replace(tzinfo=None) < dstoff:
1357 return timedelta(hours=1)
1358 else:
1359 return timedelta(0)
1360
1361 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1362
1363
1364.. method:: tzinfo.tzname(self, dt)
1365
1366 Return the time zone name corresponding to the :class:`datetime` object *dt*, as
1367 a string. Nothing about string names is defined by the :mod:`datetime` module,
1368 and there's no requirement that it mean anything in particular. For example,
1369 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1370 valid replies. Return ``None`` if a string name isn't known. Note that this is
1371 a method rather than a fixed string primarily because some :class:`tzinfo`
1372 subclasses will wish to return different names depending on the specific value
1373 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1374 daylight time.
1375
1376 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1377
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001378
Georg Brandl116aa622007-08-15 14:28:22 +00001379These methods are called by a :class:`datetime` or :class:`time` object, in
1380response to their methods of the same names. A :class:`datetime` object passes
1381itself as the argument, and a :class:`time` object passes ``None`` as the
1382argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
1383accept a *dt* argument of ``None``, or of class :class:`datetime`.
1384
1385When ``None`` is passed, it's up to the class designer to decide the best
1386response. For example, returning ``None`` is appropriate if the class wishes to
1387say that time objects don't participate in the :class:`tzinfo` protocols. It
1388may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1389there is no other convention for discovering the standard offset.
1390
1391When a :class:`datetime` object is passed in response to a :class:`datetime`
1392method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1393rely on this, unless user code calls :class:`tzinfo` methods directly. The
1394intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1395time, and not need worry about objects in other timezones.
1396
1397There is one more :class:`tzinfo` method that a subclass may wish to override:
1398
1399
1400.. method:: tzinfo.fromutc(self, dt)
1401
1402 This is called from the default :class:`datetime.astimezone()` implementation.
1403 When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members
1404 are to be viewed as expressing a UTC time. The purpose of :meth:`fromutc` is to
1405 adjust the date and time members, returning an equivalent datetime in *self*'s
1406 local time.
1407
1408 Most :class:`tzinfo` subclasses should be able to inherit the default
1409 :meth:`fromutc` implementation without problems. It's strong enough to handle
1410 fixed-offset time zones, and time zones accounting for both standard and
1411 daylight time, and the latter even if the DST transition times differ in
1412 different years. An example of a time zone the default :meth:`fromutc`
1413 implementation may not handle correctly in all cases is one where the standard
1414 offset (from UTC) depends on the specific date and time passed, which can happen
1415 for political reasons. The default implementations of :meth:`astimezone` and
1416 :meth:`fromutc` may not produce the result you want if the result is one of the
1417 hours straddling the moment the standard offset changes.
1418
1419 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1420 like::
1421
1422 def fromutc(self, dt):
1423 # raise ValueError error if dt.tzinfo is not self
1424 dtoff = dt.utcoffset()
1425 dtdst = dt.dst()
1426 # raise ValueError if dtoff is None or dtdst is None
1427 delta = dtoff - dtdst # this is self's standard offset
1428 if delta:
1429 dt += delta # convert to standard local time
1430 dtdst = dt.dst()
1431 # raise ValueError if dtdst is None
1432 if dtdst:
1433 return dt + dtdst
1434 else:
1435 return dt
1436
1437Example :class:`tzinfo` classes:
1438
1439.. literalinclude:: ../includes/tzinfo-examples.py
1440
1441
1442Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1443subclass accounting for both standard and daylight time, at the DST transition
1444points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
1445minute after 1:59 (EST) on the first Sunday in April, and ends the minute after
14461:59 (EDT) on the last Sunday in October::
1447
1448 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1449 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1450 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1451
1452 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1453
1454 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1455
1456When DST starts (the "start" line), the local wall clock leaps from 1:59 to
14573:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1458``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1459begins. In order for :meth:`astimezone` to make this guarantee, the
1460:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1461Eastern) to be in daylight time.
1462
1463When DST ends (the "end" line), there's a potentially worse problem: there's an
1464hour that can't be spelled unambiguously in local wall time: the last hour of
1465daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1466daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1467to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1468:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1469hours into the same local hour then. In the Eastern example, UTC times of the
1470form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1471:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1472consider times in the "repeated hour" to be in standard time. This is easily
1473arranged, as in the example, by expressing DST switch times in the time zone's
1474standard local time.
1475
1476Applications that can't bear such ambiguities should avoid using hybrid
1477:class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any
1478other fixed-offset :class:`tzinfo` subclass (such as a class representing only
1479EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
Georg Brandl48310cd2009-01-03 21:18:54 +00001480
Georg Brandl116aa622007-08-15 14:28:22 +00001481
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001482.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00001483
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001484:meth:`strftime` and :meth:`strptime` Behavior
1485----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001486
1487:class:`date`, :class:`datetime`, and :class:`time` objects all support a
1488``strftime(format)`` method, to create a string representing the time under the
1489control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1490acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1491although not all objects support a :meth:`timetuple` method.
1492
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001493Conversely, the :meth:`datetime.strptime` class method creates a
1494:class:`datetime` object from a string representing a date and time and a
1495corresponding format string. ``datetime.strptime(date_string, format)`` is
1496equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1497
Georg Brandl116aa622007-08-15 14:28:22 +00001498For :class:`time` objects, the format codes for year, month, and day should not
1499be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001500is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00001501
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001502For :class:`date` objects, the format codes for hours, minutes, seconds, and
1503microseconds should not be used, as :class:`date` objects have no such
1504values. If they're used anyway, ``0`` is substituted for them.
1505
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001506For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1507strings.
1508
1509For an aware object:
1510
1511``%z``
1512 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1513 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1514 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1515 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1516 replaced with the string ``'-0330'``.
1517
1518``%Z``
1519 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1520 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl116aa622007-08-15 14:28:22 +00001521
Georg Brandl116aa622007-08-15 14:28:22 +00001522The full set of format codes supported varies across platforms, because Python
1523calls the platform C library's :func:`strftime` function, and platform
Georg Brandl48310cd2009-01-03 21:18:54 +00001524variations are common.
Christian Heimes895627f2007-12-08 17:28:33 +00001525
1526The following is a list of all the format codes that the C standard (1989
1527version) requires, and these work on all platforms with a standard C
1528implementation. Note that the 1999 version of the C standard added additional
1529format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001530
1531The exact range of years for which :meth:`strftime` works also varies across
1532platforms. Regardless of platform, years before 1900 cannot be used.
1533
Christian Heimes895627f2007-12-08 17:28:33 +00001534+-----------+--------------------------------+-------+
1535| Directive | Meaning | Notes |
1536+===========+================================+=======+
1537| ``%a`` | Locale's abbreviated weekday | |
1538| | name. | |
1539+-----------+--------------------------------+-------+
1540| ``%A`` | Locale's full weekday name. | |
1541+-----------+--------------------------------+-------+
1542| ``%b`` | Locale's abbreviated month | |
1543| | name. | |
1544+-----------+--------------------------------+-------+
1545| ``%B`` | Locale's full month name. | |
1546+-----------+--------------------------------+-------+
1547| ``%c`` | Locale's appropriate date and | |
1548| | time representation. | |
1549+-----------+--------------------------------+-------+
1550| ``%d`` | Day of the month as a decimal | |
1551| | number [01,31]. | |
1552+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001553| ``%f`` | Microsecond as a decimal | \(1) |
1554| | number [0,999999], zero-padded | |
1555| | on the left | |
1556+-----------+--------------------------------+-------+
Christian Heimes895627f2007-12-08 17:28:33 +00001557| ``%H`` | Hour (24-hour clock) as a | |
1558| | decimal number [00,23]. | |
1559+-----------+--------------------------------+-------+
1560| ``%I`` | Hour (12-hour clock) as a | |
1561| | decimal number [01,12]. | |
1562+-----------+--------------------------------+-------+
1563| ``%j`` | Day of the year as a decimal | |
1564| | number [001,366]. | |
1565+-----------+--------------------------------+-------+
1566| ``%m`` | Month as a decimal number | |
1567| | [01,12]. | |
1568+-----------+--------------------------------+-------+
1569| ``%M`` | Minute as a decimal number | |
1570| | [00,59]. | |
1571+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001572| ``%p`` | Locale's equivalent of either | \(2) |
Christian Heimes895627f2007-12-08 17:28:33 +00001573| | AM or PM. | |
1574+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001575| ``%S`` | Second as a decimal number | \(3) |
Christian Heimes895627f2007-12-08 17:28:33 +00001576| | [00,61]. | |
1577+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001578| ``%U`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001579| | (Sunday as the first day of | |
1580| | the week) as a decimal number | |
1581| | [00,53]. All days in a new | |
1582| | year preceding the first | |
1583| | Sunday are considered to be in | |
1584| | week 0. | |
1585+-----------+--------------------------------+-------+
1586| ``%w`` | Weekday as a decimal number | |
1587| | [0(Sunday),6]. | |
1588+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001589| ``%W`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001590| | (Monday as the first day of | |
1591| | the week) as a decimal number | |
1592| | [00,53]. All days in a new | |
1593| | year preceding the first | |
1594| | Monday are considered to be in | |
1595| | week 0. | |
1596+-----------+--------------------------------+-------+
1597| ``%x`` | Locale's appropriate date | |
1598| | representation. | |
1599+-----------+--------------------------------+-------+
1600| ``%X`` | Locale's appropriate time | |
1601| | representation. | |
1602+-----------+--------------------------------+-------+
1603| ``%y`` | Year without century as a | |
1604| | decimal number [00,99]. | |
1605+-----------+--------------------------------+-------+
1606| ``%Y`` | Year with century as a decimal | |
1607| | number. | |
1608+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001609| ``%z`` | UTC offset in the form +HHMM | \(5) |
Christian Heimes895627f2007-12-08 17:28:33 +00001610| | or -HHMM (empty string if the | |
1611| | the object is naive). | |
1612+-----------+--------------------------------+-------+
1613| ``%Z`` | Time zone name (empty string | |
1614| | if the object is naive). | |
1615+-----------+--------------------------------+-------+
1616| ``%%`` | A literal ``'%'`` character. | |
1617+-----------+--------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001618
Christian Heimes895627f2007-12-08 17:28:33 +00001619Notes:
1620
1621(1)
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001622 When used with the :meth:`strptime` method, the ``%f`` directive
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001623 accepts from one to six digits and zero pads on the right. ``%f`` is
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001624 an extension to the set of format characters in the C standard (but
1625 implemented separately in datetime objects, and therefore always
1626 available).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001627
1628(2)
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001629 When used with the :meth:`strptime` method, the ``%p`` directive only affects
Christian Heimes895627f2007-12-08 17:28:33 +00001630 the output hour field if the ``%I`` directive is used to parse the hour.
1631
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001632(3)
R. David Murraybd25d332009-04-02 04:50:03 +00001633 The range really is ``0`` to ``61``; according to the Posix standard this
1634 accounts for leap seconds and the (very rare) double leap seconds.
1635 The :mod:`time` module may produce and does accept leap seconds since
1636 it is based on the Posix standard, but the :mod:`datetime` module
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001637 does not accept leap seconds in :meth:`strptime` input nor will it
R. David Murraybd25d332009-04-02 04:50:03 +00001638 produce them in :func:`strftime` output.
Christian Heimes895627f2007-12-08 17:28:33 +00001639
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001640(4)
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001641 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in
Christian Heimes895627f2007-12-08 17:28:33 +00001642 calculations when the day of the week and the year are specified.
1643
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001644(5)
Christian Heimes895627f2007-12-08 17:28:33 +00001645 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1646 ``%z`` is replaced with the string ``'-0330'``.