blob: 26d994663087c24c248ad83c85a1cc7b36a6c1e1 [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+--------------------------------+-----------------------------------------------+
Georg Brandl527a5cf2010-08-01 19:21:34 +0000236| ``str(t)`` | Returns a string in the form |
237| | ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D |
238| | is negative for negative ``t``. (5) |
239+--------------------------------+-----------------------------------------------+
240| ``repr(t)`` | Returns a string in the form |
241| | ``datetime.timedelta(D[, S[, U]])``, where D |
242| | is negative for negative ``t``. (5) |
243+--------------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000244
245Notes:
246
247(1)
248 This is exact, but may overflow.
249
250(2)
251 This is exact, and cannot overflow.
252
253(3)
254 Division by 0 raises :exc:`ZeroDivisionError`.
255
256(4)
257 -*timedelta.max* is not representable as a :class:`timedelta` object.
258
Georg Brandl527a5cf2010-08-01 19:21:34 +0000259(5)
260 String representations of :class:`timedelta` objects are normalized
261 similarly to their internal representation. This leads to somewhat
262 unusual results for negative timedeltas. For example:
263
264 >>> timedelta(hours=-5)
265 datetime.timedelta(-1, 68400)
266 >>> print(_)
267 -1 day, 19:00:00
268
Georg Brandl116aa622007-08-15 14:28:22 +0000269In addition to the operations listed above :class:`timedelta` objects support
270certain additions and subtractions with :class:`date` and :class:`datetime`
271objects (see below).
272
273Comparisons of :class:`timedelta` objects are supported with the
274:class:`timedelta` object representing the smaller duration considered to be the
275smaller timedelta. In order to stop mixed-type comparisons from falling back to
276the default comparison by object address, when a :class:`timedelta` object is
277compared to an object of a different type, :exc:`TypeError` is raised unless the
278comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
279:const:`True`, respectively.
280
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000281:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl116aa622007-08-15 14:28:22 +0000282efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
283considered to be true if and only if it isn't equal to ``timedelta(0)``.
284
Christian Heimesfe337bf2008-03-23 21:54:12 +0000285Example usage:
Georg Brandl48310cd2009-01-03 21:18:54 +0000286
Christian Heimes895627f2007-12-08 17:28:33 +0000287 >>> from datetime import timedelta
288 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000289 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Christian Heimes895627f2007-12-08 17:28:33 +0000290 ... minutes=50, seconds=600) # adds up to 365 days
291 >>> year == another_year
292 True
293 >>> ten_years = 10 * year
294 >>> ten_years, ten_years.days // 365
295 (datetime.timedelta(3650), 10)
296 >>> nine_years = ten_years - year
297 >>> nine_years, nine_years.days // 365
298 (datetime.timedelta(3285), 9)
299 >>> three_years = nine_years // 3;
300 >>> three_years, three_years.days // 365
301 (datetime.timedelta(1095), 3)
302 >>> abs(three_years - ten_years) == 2 * three_years + year
303 True
304
Georg Brandl116aa622007-08-15 14:28:22 +0000305
306.. _datetime-date:
307
308:class:`date` Objects
309---------------------
310
311A :class:`date` object represents a date (year, month and day) in an idealized
312calendar, the current Gregorian calendar indefinitely extended in both
313directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
314called day number 2, and so on. This matches the definition of the "proleptic
315Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
316where it's the base calendar for all computations. See the book for algorithms
317for converting between proleptic Gregorian ordinals and many other calendar
318systems.
319
320
321.. class:: date(year, month, day)
322
Georg Brandl5c106642007-11-29 17:41:05 +0000323 All arguments are required. Arguments may be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000324 ranges:
325
326 * ``MINYEAR <= year <= MAXYEAR``
327 * ``1 <= month <= 12``
328 * ``1 <= day <= number of days in the given month and year``
329
330 If an argument outside those ranges is given, :exc:`ValueError` is raised.
331
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000332
Georg Brandl116aa622007-08-15 14:28:22 +0000333Other constructors, all class methods:
334
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000335.. classmethod:: date.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000336
337 Return the current local date. This is equivalent to
338 ``date.fromtimestamp(time.time())``.
339
340
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000341.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000342
343 Return the local date corresponding to the POSIX timestamp, such as is returned
344 by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out
345 of the range of values supported by the platform C :cfunc:`localtime` function.
346 It's common for this to be restricted to years from 1970 through 2038. Note
347 that on non-POSIX systems that include leap seconds in their notion of a
348 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
349
350
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000351.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000352
353 Return the date corresponding to the proleptic Gregorian ordinal, where January
354 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
355 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
356 d``.
357
Georg Brandl116aa622007-08-15 14:28:22 +0000358
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000359Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000360
361.. attribute:: date.min
362
363 The earliest representable date, ``date(MINYEAR, 1, 1)``.
364
365
366.. attribute:: date.max
367
368 The latest representable date, ``date(MAXYEAR, 12, 31)``.
369
370
371.. attribute:: date.resolution
372
373 The smallest possible difference between non-equal date objects,
374 ``timedelta(days=1)``.
375
Georg Brandl116aa622007-08-15 14:28:22 +0000376
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000377Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000378
379.. attribute:: date.year
380
381 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
382
383
384.. attribute:: date.month
385
386 Between 1 and 12 inclusive.
387
388
389.. attribute:: date.day
390
391 Between 1 and the number of days in the given month of the given year.
392
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000393
Georg Brandl116aa622007-08-15 14:28:22 +0000394Supported operations:
395
396+-------------------------------+----------------------------------------------+
397| Operation | Result |
398+===============================+==============================================+
399| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
400| | from *date1*. (1) |
401+-------------------------------+----------------------------------------------+
402| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
403| | timedelta == date1``. (2) |
404+-------------------------------+----------------------------------------------+
405| ``timedelta = date1 - date2`` | \(3) |
406+-------------------------------+----------------------------------------------+
407| ``date1 < date2`` | *date1* is considered less than *date2* when |
408| | *date1* precedes *date2* in time. (4) |
409+-------------------------------+----------------------------------------------+
410
411Notes:
412
413(1)
414 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
415 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
416 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
417 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
418 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
419
420(2)
421 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
422 isolation can overflow in cases where date1 - timedelta does not.
423 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
424
425(3)
426 This is exact, and cannot overflow. timedelta.seconds and
427 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
428
429(4)
430 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
431 date2.toordinal()``. In order to stop comparison from falling back to the
432 default scheme of comparing object addresses, date comparison normally raises
433 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
434 However, ``NotImplemented`` is returned instead if the other comparand has a
435 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
436 chance at implementing mixed-type comparison. If not, when a :class:`date`
437 object is compared to an object of a different type, :exc:`TypeError` is raised
438 unless the comparison is ``==`` or ``!=``. The latter cases return
439 :const:`False` or :const:`True`, respectively.
440
441Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
442objects are considered to be true.
443
444Instance methods:
445
Georg Brandl116aa622007-08-15 14:28:22 +0000446.. method:: date.replace(year, month, day)
447
448 Return a date with the same value, except for those members given new values by
449 whichever keyword arguments are specified. For example, if ``d == date(2002,
450 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
451
452
453.. method:: date.timetuple()
454
455 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
456 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
457 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
Georg Brandl16489242010-10-06 08:03:21 +0000458 d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1,
459 1).toordinal() + 1`` is the day number within the current year starting with
460 ``1`` for January 1st.
Georg Brandl116aa622007-08-15 14:28:22 +0000461
462
463.. method:: date.toordinal()
464
465 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
466 has ordinal 1. For any :class:`date` object *d*,
467 ``date.fromordinal(d.toordinal()) == d``.
468
469
470.. method:: date.weekday()
471
472 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
473 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
474 :meth:`isoweekday`.
475
476
477.. method:: date.isoweekday()
478
479 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
480 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
481 :meth:`weekday`, :meth:`isocalendar`.
482
483
484.. method:: date.isocalendar()
485
486 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
487
488 The ISO calendar is a widely used variant of the Gregorian calendar. See
Mark Dickinson7e866642009-11-03 16:29:43 +0000489 http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
490 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000491
492 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
493 Monday and ends on a Sunday. The first week of an ISO year is the first
494 (Gregorian) calendar week of a year containing a Thursday. This is called week
495 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
496
497 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
498 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
499 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
500 4).isocalendar() == (2004, 1, 7)``.
501
502
503.. method:: date.isoformat()
504
505 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
506 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
507
508
509.. method:: date.__str__()
510
511 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
512
513
514.. method:: date.ctime()
515
516 Return a string representing the date, for example ``date(2002, 12,
517 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
518 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
519 :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
520 :meth:`date.ctime` does not invoke) conforms to the C standard.
521
522
523.. method:: date.strftime(format)
524
525 Return a string representing the date, controlled by an explicit format string.
526 Format codes referring to hours, minutes or seconds will see 0 values. See
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000527 section :ref:`strftime-strptime-behavior`.
528
Georg Brandl116aa622007-08-15 14:28:22 +0000529
Christian Heimes895627f2007-12-08 17:28:33 +0000530Example of counting days to an event::
531
532 >>> import time
533 >>> from datetime import date
534 >>> today = date.today()
535 >>> today
536 datetime.date(2007, 12, 5)
537 >>> today == date.fromtimestamp(time.time())
538 True
539 >>> my_birthday = date(today.year, 6, 24)
540 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000541 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000542 >>> my_birthday
543 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000544 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000545 >>> time_to_birthday.days
546 202
547
Christian Heimesfe337bf2008-03-23 21:54:12 +0000548Example of working with :class:`date`:
549
550.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000551
552 >>> from datetime import date
553 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
554 >>> d
555 datetime.date(2002, 3, 11)
556 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000557 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000558 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000559 2002 # year
560 3 # month
561 11 # day
562 0
563 0
564 0
565 0 # weekday (0 = Monday)
566 70 # 70th day in the year
567 -1
568 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000569 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000570 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000571 2002 # ISO year
572 11 # ISO week number
573 1 # ISO day number ( 1 = Monday )
574 >>> d.isoformat()
575 '2002-03-11'
576 >>> d.strftime("%d/%m/%y")
577 '11/03/02'
578 >>> d.strftime("%A %d. %B %Y")
579 'Monday 11. March 2002'
580
Georg Brandl116aa622007-08-15 14:28:22 +0000581
582.. _datetime-datetime:
583
584:class:`datetime` Objects
585-------------------------
586
587A :class:`datetime` object is a single object containing all the information
588from a :class:`date` object and a :class:`time` object. Like a :class:`date`
589object, :class:`datetime` assumes the current Gregorian calendar extended in
590both directions; like a time object, :class:`datetime` assumes there are exactly
5913600\*24 seconds in every day.
592
593Constructor:
594
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000595.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000596
597 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000598 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
599 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000600
601 * ``MINYEAR <= year <= MAXYEAR``
602 * ``1 <= month <= 12``
603 * ``1 <= day <= number of days in the given month and year``
604 * ``0 <= hour < 24``
605 * ``0 <= minute < 60``
606 * ``0 <= second < 60``
607 * ``0 <= microsecond < 1000000``
608
609 If an argument outside those ranges is given, :exc:`ValueError` is raised.
610
611Other constructors, all class methods:
612
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000613.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000614
615 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
616 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
617 :meth:`fromtimestamp`.
618
619
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000620.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000621
622 Return the current local date and time. If optional argument *tz* is ``None``
623 or not specified, this is like :meth:`today`, but, if possible, supplies more
624 precision than can be gotten from going through a :func:`time.time` timestamp
625 (for example, this may be possible on platforms supplying the C
626 :cfunc:`gettimeofday` function).
627
628 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
629 current date and time are converted to *tz*'s time zone. In this case the
630 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
631 See also :meth:`today`, :meth:`utcnow`.
632
633
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000634.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000635
636 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
637 :meth:`now`, but returns the current UTC date and time, as a naive
638 :class:`datetime` object. See also :meth:`now`.
639
640
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000641.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000642
643 Return the local date and time corresponding to the POSIX timestamp, such as is
644 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
645 specified, the timestamp is converted to the platform's local date and time, and
646 the returned :class:`datetime` object is naive.
647
648 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
649 timestamp is converted to *tz*'s time zone. In this case the result is
650 equivalent to
651 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
652
653 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
654 the range of values supported by the platform C :cfunc:`localtime` or
655 :cfunc:`gmtime` functions. It's common for this to be restricted to years in
656 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
657 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
658 and then it's possible to have two timestamps differing by a second that yield
659 identical :class:`datetime` objects. See also :meth:`utcfromtimestamp`.
660
661
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000662.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000663
664 Return the UTC :class:`datetime` corresponding to the POSIX timestamp, with
665 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
666 out of the range of values supported by the platform C :cfunc:`gmtime` function.
667 It's common for this to be restricted to years in 1970 through 2038. See also
668 :meth:`fromtimestamp`.
669
670
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000671.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000672
673 Return the :class:`datetime` corresponding to the proleptic Gregorian ordinal,
674 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
675 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
676 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
677
678
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000679.. classmethod:: datetime.combine(date, time)
Georg Brandl116aa622007-08-15 14:28:22 +0000680
681 Return a new :class:`datetime` object whose date members are equal to the given
682 :class:`date` object's, and whose time and :attr:`tzinfo` members are equal to
683 the given :class:`time` object's. For any :class:`datetime` object *d*, ``d ==
684 datetime.combine(d.date(), d.timetz())``. If date is a :class:`datetime`
685 object, its time and :attr:`tzinfo` members are ignored.
686
687
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000688.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000689
690 Return a :class:`datetime` corresponding to *date_string*, parsed according to
691 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
692 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
693 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 +0000694 time tuple. See section :ref:`strftime-strptime-behavior`.
695
Georg Brandl116aa622007-08-15 14:28:22 +0000696
Georg Brandl116aa622007-08-15 14:28:22 +0000697
698Class attributes:
699
Georg Brandl116aa622007-08-15 14:28:22 +0000700.. attribute:: datetime.min
701
702 The earliest representable :class:`datetime`, ``datetime(MINYEAR, 1, 1,
703 tzinfo=None)``.
704
705
706.. attribute:: datetime.max
707
708 The latest representable :class:`datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
709 59, 999999, tzinfo=None)``.
710
711
712.. attribute:: datetime.resolution
713
714 The smallest possible difference between non-equal :class:`datetime` objects,
715 ``timedelta(microseconds=1)``.
716
Georg Brandl116aa622007-08-15 14:28:22 +0000717
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000718Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000719
720.. attribute:: datetime.year
721
722 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
723
724
725.. attribute:: datetime.month
726
727 Between 1 and 12 inclusive.
728
729
730.. attribute:: datetime.day
731
732 Between 1 and the number of days in the given month of the given year.
733
734
735.. attribute:: datetime.hour
736
737 In ``range(24)``.
738
739
740.. attribute:: datetime.minute
741
742 In ``range(60)``.
743
744
745.. attribute:: datetime.second
746
747 In ``range(60)``.
748
749
750.. attribute:: datetime.microsecond
751
752 In ``range(1000000)``.
753
754
755.. attribute:: datetime.tzinfo
756
757 The object passed as the *tzinfo* argument to the :class:`datetime` constructor,
758 or ``None`` if none was passed.
759
Benjamin Peterson23b9ef72010-02-03 02:43:37 +0000760
Georg Brandl116aa622007-08-15 14:28:22 +0000761Supported operations:
762
763+---------------------------------------+-------------------------------+
764| Operation | Result |
765+=======================================+===============================+
766| ``datetime2 = datetime1 + timedelta`` | \(1) |
767+---------------------------------------+-------------------------------+
768| ``datetime2 = datetime1 - timedelta`` | \(2) |
769+---------------------------------------+-------------------------------+
770| ``timedelta = datetime1 - datetime2`` | \(3) |
771+---------------------------------------+-------------------------------+
772| ``datetime1 < datetime2`` | Compares :class:`datetime` to |
773| | :class:`datetime`. (4) |
774+---------------------------------------+-------------------------------+
775
776(1)
777 datetime2 is a duration of timedelta removed from datetime1, moving forward in
778 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
779 result has the same :attr:`tzinfo` member as the input datetime, and datetime2 -
780 datetime1 == timedelta after. :exc:`OverflowError` is raised if datetime2.year
781 would be smaller than :const:`MINYEAR` or larger than :const:`MAXYEAR`. Note
782 that no time zone adjustments are done even if the input is an aware object.
783
784(2)
785 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
786 addition, the result has the same :attr:`tzinfo` member as the input datetime,
787 and no time zone adjustments are done even if the input is aware. This isn't
788 quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation
789 can overflow in cases where datetime1 - timedelta does not.
790
791(3)
792 Subtraction of a :class:`datetime` from a :class:`datetime` is defined only if
793 both operands are naive, or if both are aware. If one is aware and the other is
794 naive, :exc:`TypeError` is raised.
795
796 If both are naive, or both are aware and have the same :attr:`tzinfo` member,
797 the :attr:`tzinfo` members are ignored, and the result is a :class:`timedelta`
798 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
799 are done in this case.
800
801 If both are aware and have different :attr:`tzinfo` members, ``a-b`` acts as if
802 *a* and *b* were first converted to naive UTC datetimes first. The result is
803 ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) -
804 b.utcoffset())`` except that the implementation never overflows.
805
806(4)
807 *datetime1* is considered less than *datetime2* when *datetime1* precedes
808 *datetime2* in time.
809
810 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
811 If both comparands are aware, and have the same :attr:`tzinfo` member, the
812 common :attr:`tzinfo` member is ignored and the base datetimes are compared. If
813 both comparands are aware and have different :attr:`tzinfo` members, the
814 comparands are first adjusted by subtracting their UTC offsets (obtained from
815 ``self.utcoffset()``).
816
817 .. note::
818
819 In order to stop comparison from falling back to the default scheme of comparing
820 object addresses, datetime comparison normally raises :exc:`TypeError` if the
821 other comparand isn't also a :class:`datetime` object. However,
822 ``NotImplemented`` is returned instead if the other comparand has a
823 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
824 chance at implementing mixed-type comparison. If not, when a :class:`datetime`
825 object is compared to an object of a different type, :exc:`TypeError` is raised
826 unless the comparison is ``==`` or ``!=``. The latter cases return
827 :const:`False` or :const:`True`, respectively.
828
829:class:`datetime` objects can be used as dictionary keys. In Boolean contexts,
830all :class:`datetime` objects are considered to be true.
831
832Instance methods:
833
Georg Brandl116aa622007-08-15 14:28:22 +0000834.. method:: datetime.date()
835
836 Return :class:`date` object with same year, month and day.
837
838
839.. method:: datetime.time()
840
841 Return :class:`time` object with same hour, minute, second and microsecond.
842 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
843
844
845.. method:: datetime.timetz()
846
847 Return :class:`time` object with same hour, minute, second, microsecond, and
848 tzinfo members. See also method :meth:`time`.
849
850
851.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
852
853 Return a datetime with the same members, except for those members given new
854 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
855 can be specified to create a naive datetime from an aware datetime with no
856 conversion of date and time members.
857
858
859.. method:: datetime.astimezone(tz)
860
861 Return a :class:`datetime` object with new :attr:`tzinfo` member *tz*, adjusting
862 the date and time members so the result is the same UTC time as *self*, but in
863 *tz*'s local time.
864
865 *tz* must be an instance of a :class:`tzinfo` subclass, and its
866 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
867 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
868 not return ``None``).
869
870 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
871 adjustment of date or time members is performed. Else the result is local time
872 in time zone *tz*, representing the same UTC time as *self*: after ``astz =
873 dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have the same date
874 and time members as ``dt - dt.utcoffset()``. The discussion of class
875 :class:`tzinfo` explains the cases at Daylight Saving Time transition boundaries
876 where this cannot be achieved (an issue only if *tz* models both standard and
877 daylight time).
878
879 If you merely want to attach a time zone object *tz* to a datetime *dt* without
880 adjustment of date and time members, use ``dt.replace(tzinfo=tz)``. If you
881 merely want to remove the time zone object from an aware datetime *dt* without
882 conversion of date and time members, use ``dt.replace(tzinfo=None)``.
883
884 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
885 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
886 Ignoring error cases, :meth:`astimezone` acts like::
887
888 def astimezone(self, tz):
889 if self.tzinfo is tz:
890 return self
891 # Convert self to UTC, and attach the new time zone object.
892 utc = (self - self.utcoffset()).replace(tzinfo=tz)
893 # Convert from UTC to tz's local time.
894 return tz.fromutc(utc)
895
896
897.. method:: datetime.utcoffset()
898
899 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
900 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
901 return ``None``, or a :class:`timedelta` object representing a whole number of
902 minutes with magnitude less than one day.
903
904
905.. method:: datetime.dst()
906
907 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
908 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
909 ``None``, or a :class:`timedelta` object representing a whole number of minutes
910 with magnitude less than one day.
911
912
913.. method:: datetime.tzname()
914
915 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
916 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
917 ``None`` or a string object,
918
919
920.. method:: datetime.timetuple()
921
922 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
923 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
Georg Brandl16489242010-10-06 08:03:21 +0000924 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
925 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
926 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
927 of the result is set according to the :meth:`dst` method: :attr:`tzinfo` is
Georg Brandld098c3d2010-10-06 10:38:58 +0000928 ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
Georg Brandl16489242010-10-06 08:03:21 +0000929 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
930 else ``tm_isdst`` is set to ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +0000931
932
933.. method:: datetime.utctimetuple()
934
935 If :class:`datetime` instance *d* is naive, this is the same as
936 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
937 ``d.dst()`` returns. DST is never in effect for a UTC time.
938
939 If *d* is aware, *d* is normalized to UTC time, by subtracting
940 ``d.utcoffset()``, and a :class:`time.struct_time` for the normalized time is
941 returned. :attr:`tm_isdst` is forced to 0. Note that the result's
942 :attr:`tm_year` member may be :const:`MINYEAR`\ -1 or :const:`MAXYEAR`\ +1, if
943 *d*.year was ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
944 boundary.
945
946
947.. method:: datetime.toordinal()
948
949 Return the proleptic Gregorian ordinal of the date. The same as
950 ``self.date().toordinal()``.
951
952
953.. method:: datetime.weekday()
954
955 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
956 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
957
958
959.. method:: datetime.isoweekday()
960
961 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
962 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
963 :meth:`isocalendar`.
964
965
966.. method:: datetime.isocalendar()
967
968 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
969 ``self.date().isocalendar()``.
970
971
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000972.. method:: datetime.isoformat(sep='T')
Georg Brandl116aa622007-08-15 14:28:22 +0000973
974 Return a string representing the date and time in ISO 8601 format,
975 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
976 YYYY-MM-DDTHH:MM:SS
977
978 If :meth:`utcoffset` does not return ``None``, a 6-character string is
979 appended, giving the UTC offset in (signed) hours and minutes:
980 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
981 YYYY-MM-DDTHH:MM:SS+HH:MM
982
983 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000984 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +0000985
986 >>> from datetime import tzinfo, timedelta, datetime
987 >>> class TZ(tzinfo):
988 ... def utcoffset(self, dt): return timedelta(minutes=-399)
989 ...
990 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
991 '2002-12-25 00:00:00-06:39'
992
993
994.. method:: datetime.__str__()
995
996 For a :class:`datetime` instance *d*, ``str(d)`` is equivalent to
997 ``d.isoformat(' ')``.
998
999
1000.. method:: datetime.ctime()
1001
1002 Return a string representing the date and time, for example ``datetime(2002, 12,
1003 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1004 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
1005 native C :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
1006 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1007
1008
1009.. method:: datetime.strftime(format)
1010
1011 Return a string representing the date and time, controlled by an explicit format
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001012 string. See section :ref:`strftime-strptime-behavior`.
1013
Georg Brandl116aa622007-08-15 14:28:22 +00001014
Christian Heimesfe337bf2008-03-23 21:54:12 +00001015Examples of working with datetime objects:
1016
1017.. doctest::
1018
Christian Heimes895627f2007-12-08 17:28:33 +00001019 >>> from datetime import datetime, date, time
1020 >>> # Using datetime.combine()
1021 >>> d = date(2005, 7, 14)
1022 >>> t = time(12, 30)
1023 >>> datetime.combine(d, t)
1024 datetime.datetime(2005, 7, 14, 12, 30)
1025 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001026 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001027 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001028 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001029 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1030 >>> # Using datetime.strptime()
1031 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1032 >>> dt
1033 datetime.datetime(2006, 11, 21, 16, 30)
1034 >>> # Using datetime.timetuple() to get tuple of all attributes
1035 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001036 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001037 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001038 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001039 2006 # year
1040 11 # month
1041 21 # day
1042 16 # hour
1043 30 # minute
1044 0 # second
1045 1 # weekday (0 = Monday)
1046 325 # number of days since 1st January
1047 -1 # dst - method tzinfo.dst() returned None
1048 >>> # Date in ISO format
1049 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001050 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001051 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001052 ...
1053 2006 # ISO year
1054 47 # ISO week
1055 2 # ISO weekday
1056 >>> # Formatting datetime
1057 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1058 'Tuesday, 21. November 2006 04:30PM'
1059
Christian Heimesfe337bf2008-03-23 21:54:12 +00001060Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001061
1062 >>> from datetime import timedelta, datetime, tzinfo
1063 >>> class GMT1(tzinfo):
1064 ... def __init__(self): # DST starts last Sunday in March
1065 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1066 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001067 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001068 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1069 ... def utcoffset(self, dt):
1070 ... return timedelta(hours=1) + self.dst(dt)
Georg Brandl48310cd2009-01-03 21:18:54 +00001071 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001072 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1073 ... return timedelta(hours=1)
1074 ... else:
1075 ... return timedelta(0)
1076 ... def tzname(self,dt):
1077 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001078 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001079 >>> class GMT2(tzinfo):
1080 ... def __init__(self):
Georg Brandl48310cd2009-01-03 21:18:54 +00001081 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001082 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001083 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001084 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1085 ... def utcoffset(self, dt):
1086 ... return timedelta(hours=1) + self.dst(dt)
1087 ... def dst(self, dt):
1088 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1089 ... return timedelta(hours=2)
1090 ... else:
1091 ... return timedelta(0)
1092 ... def tzname(self,dt):
1093 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001094 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001095 >>> gmt1 = GMT1()
1096 >>> # Daylight Saving Time
1097 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1098 >>> dt1.dst()
1099 datetime.timedelta(0)
1100 >>> dt1.utcoffset()
1101 datetime.timedelta(0, 3600)
1102 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1103 >>> dt2.dst()
1104 datetime.timedelta(0, 3600)
1105 >>> dt2.utcoffset()
1106 datetime.timedelta(0, 7200)
1107 >>> # Convert datetime to another time zone
1108 >>> dt3 = dt2.astimezone(GMT2())
1109 >>> dt3 # doctest: +ELLIPSIS
1110 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1111 >>> dt2 # doctest: +ELLIPSIS
1112 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1113 >>> dt2.utctimetuple() == dt3.utctimetuple()
1114 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001115
Christian Heimes895627f2007-12-08 17:28:33 +00001116
Georg Brandl116aa622007-08-15 14:28:22 +00001117
1118.. _datetime-time:
1119
1120:class:`time` Objects
1121---------------------
1122
1123A time object represents a (local) time of day, independent of any particular
1124day, and subject to adjustment via a :class:`tzinfo` object.
1125
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001126.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001127
1128 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001129 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001130 following ranges:
1131
1132 * ``0 <= hour < 24``
1133 * ``0 <= minute < 60``
1134 * ``0 <= second < 60``
1135 * ``0 <= microsecond < 1000000``.
1136
1137 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1138 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1139
1140Class attributes:
1141
1142
1143.. attribute:: time.min
1144
1145 The earliest representable :class:`time`, ``time(0, 0, 0, 0)``.
1146
1147
1148.. attribute:: time.max
1149
1150 The latest representable :class:`time`, ``time(23, 59, 59, 999999)``.
1151
1152
1153.. attribute:: time.resolution
1154
1155 The smallest possible difference between non-equal :class:`time` objects,
1156 ``timedelta(microseconds=1)``, although note that arithmetic on :class:`time`
1157 objects is not supported.
1158
Georg Brandl116aa622007-08-15 14:28:22 +00001159
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001160Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001161
1162.. attribute:: time.hour
1163
1164 In ``range(24)``.
1165
1166
1167.. attribute:: time.minute
1168
1169 In ``range(60)``.
1170
1171
1172.. attribute:: time.second
1173
1174 In ``range(60)``.
1175
1176
1177.. attribute:: time.microsecond
1178
1179 In ``range(1000000)``.
1180
1181
1182.. attribute:: time.tzinfo
1183
1184 The object passed as the tzinfo argument to the :class:`time` constructor, or
1185 ``None`` if none was passed.
1186
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001187
Georg Brandl116aa622007-08-15 14:28:22 +00001188Supported operations:
1189
1190* comparison of :class:`time` to :class:`time`, where *a* is considered less
1191 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1192 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
1193 the same :attr:`tzinfo` member, the common :attr:`tzinfo` member is ignored and
1194 the base times are compared. If both comparands are aware and have different
1195 :attr:`tzinfo` members, the comparands are first adjusted by subtracting their
1196 UTC offsets (obtained from ``self.utcoffset()``). In order to stop mixed-type
1197 comparisons from falling back to the default comparison by object address, when
1198 a :class:`time` object is compared to an object of a different type,
1199 :exc:`TypeError` is raised unless the comparison is ``==`` or ``!=``. The
1200 latter cases return :const:`False` or :const:`True`, respectively.
1201
1202* hash, use as dict key
1203
1204* efficient pickling
1205
1206* in Boolean contexts, a :class:`time` object is considered to be true if and
1207 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1208 ``0`` if that's ``None``), the result is non-zero.
1209
Georg Brandl116aa622007-08-15 14:28:22 +00001210
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001211Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001212
1213.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1214
1215 Return a :class:`time` with the same value, except for those members given new
1216 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
1217 can be specified to create a naive :class:`time` from an aware :class:`time`,
1218 without conversion of the time members.
1219
1220
1221.. method:: time.isoformat()
1222
1223 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1224 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1225 6-character string is appended, giving the UTC offset in (signed) hours and
1226 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1227
1228
1229.. method:: time.__str__()
1230
1231 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1232
1233
1234.. method:: time.strftime(format)
1235
1236 Return a string representing the time, controlled by an explicit format string.
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001237 See section :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001238
1239
1240.. method:: time.utcoffset()
1241
1242 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1243 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1244 return ``None`` or a :class:`timedelta` object representing a whole number of
1245 minutes with magnitude less than one day.
1246
1247
1248.. method:: time.dst()
1249
1250 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1251 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1252 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1253 with magnitude less than one day.
1254
1255
1256.. method:: time.tzname()
1257
1258 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1259 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1260 return ``None`` or a string object.
1261
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001262
Christian Heimesfe337bf2008-03-23 21:54:12 +00001263Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001264
Christian Heimes895627f2007-12-08 17:28:33 +00001265 >>> from datetime import time, tzinfo
1266 >>> class GMT1(tzinfo):
1267 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001268 ... return timedelta(hours=1)
1269 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001270 ... return timedelta(0)
1271 ... def tzname(self,dt):
1272 ... return "Europe/Prague"
1273 ...
1274 >>> t = time(12, 10, 30, tzinfo=GMT1())
1275 >>> t # doctest: +ELLIPSIS
1276 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1277 >>> gmt = GMT1()
1278 >>> t.isoformat()
1279 '12:10:30+01:00'
1280 >>> t.dst()
1281 datetime.timedelta(0)
1282 >>> t.tzname()
1283 'Europe/Prague'
1284 >>> t.strftime("%H:%M:%S %Z")
1285 '12:10:30 Europe/Prague'
1286
Georg Brandl116aa622007-08-15 14:28:22 +00001287
1288.. _datetime-tzinfo:
1289
1290:class:`tzinfo` Objects
1291-----------------------
1292
Brett Cannone1327f72009-01-29 04:10:21 +00001293:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001294instantiated directly. You need to derive a concrete subclass, and (at least)
1295supply implementations of the standard :class:`tzinfo` methods needed by the
1296:class:`datetime` methods you use. The :mod:`datetime` module does not supply
1297any concrete subclasses of :class:`tzinfo`.
1298
1299An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1300constructors for :class:`datetime` and :class:`time` objects. The latter objects
1301view their members as being in local time, and the :class:`tzinfo` object
1302supports methods revealing offset of local time from UTC, the name of the time
1303zone, and DST offset, all relative to a date or time object passed to them.
1304
1305Special requirement for pickling: A :class:`tzinfo` subclass must have an
1306:meth:`__init__` method that can be called with no arguments, else it can be
1307pickled but possibly not unpickled again. This is a technical requirement that
1308may be relaxed in the future.
1309
1310A concrete subclass of :class:`tzinfo` may need to implement the following
1311methods. Exactly which methods are needed depends on the uses made of aware
1312:mod:`datetime` objects. If in doubt, simply implement all of them.
1313
1314
1315.. method:: tzinfo.utcoffset(self, dt)
1316
1317 Return offset of local time from UTC, in minutes east of UTC. If local time is
1318 west of UTC, this should be negative. Note that this is intended to be the
1319 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1320 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1321 the UTC offset isn't known, return ``None``. Else the value returned must be a
1322 :class:`timedelta` object specifying a whole number of minutes in the range
1323 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1324 than one day). Most implementations of :meth:`utcoffset` will probably look
1325 like one of these two::
1326
1327 return CONSTANT # fixed-offset class
1328 return CONSTANT + self.dst(dt) # daylight-aware class
1329
1330 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1331 ``None`` either.
1332
1333 The default implementation of :meth:`utcoffset` raises
1334 :exc:`NotImplementedError`.
1335
1336
1337.. method:: tzinfo.dst(self, dt)
1338
1339 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1340 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1341 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1342 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1343 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1344 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1345 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
1346 member's :meth:`dst` method to determine how the :attr:`tm_isdst` flag should be
1347 set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for DST changes
1348 when crossing time zones.
1349
1350 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1351 daylight times must be consistent in this sense:
1352
1353 ``tz.utcoffset(dt) - tz.dst(dt)``
1354
1355 must return the same result for every :class:`datetime` *dt* with ``dt.tzinfo ==
1356 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1357 zone's "standard offset", which should not depend on the date or the time, but
1358 only on geographic location. The implementation of :meth:`datetime.astimezone`
1359 relies on this, but cannot detect violations; it's the programmer's
1360 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1361 this, it may be able to override the default implementation of
1362 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1363
1364 Most implementations of :meth:`dst` will probably look like one of these two::
1365
1366 def dst(self):
1367 # a fixed-offset class: doesn't account for DST
1368 return timedelta(0)
1369
1370 or ::
1371
1372 def dst(self):
1373 # Code to set dston and dstoff to the time zone's DST
1374 # transition times based on the input dt.year, and expressed
1375 # in standard local time. Then
1376
1377 if dston <= dt.replace(tzinfo=None) < dstoff:
1378 return timedelta(hours=1)
1379 else:
1380 return timedelta(0)
1381
1382 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1383
1384
1385.. method:: tzinfo.tzname(self, dt)
1386
1387 Return the time zone name corresponding to the :class:`datetime` object *dt*, as
1388 a string. Nothing about string names is defined by the :mod:`datetime` module,
1389 and there's no requirement that it mean anything in particular. For example,
1390 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1391 valid replies. Return ``None`` if a string name isn't known. Note that this is
1392 a method rather than a fixed string primarily because some :class:`tzinfo`
1393 subclasses will wish to return different names depending on the specific value
1394 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1395 daylight time.
1396
1397 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1398
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001399
Georg Brandl116aa622007-08-15 14:28:22 +00001400These methods are called by a :class:`datetime` or :class:`time` object, in
1401response to their methods of the same names. A :class:`datetime` object passes
1402itself as the argument, and a :class:`time` object passes ``None`` as the
1403argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
1404accept a *dt* argument of ``None``, or of class :class:`datetime`.
1405
1406When ``None`` is passed, it's up to the class designer to decide the best
1407response. For example, returning ``None`` is appropriate if the class wishes to
1408say that time objects don't participate in the :class:`tzinfo` protocols. It
1409may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1410there is no other convention for discovering the standard offset.
1411
1412When a :class:`datetime` object is passed in response to a :class:`datetime`
1413method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1414rely on this, unless user code calls :class:`tzinfo` methods directly. The
1415intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1416time, and not need worry about objects in other timezones.
1417
1418There is one more :class:`tzinfo` method that a subclass may wish to override:
1419
1420
1421.. method:: tzinfo.fromutc(self, dt)
1422
1423 This is called from the default :class:`datetime.astimezone()` implementation.
1424 When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members
1425 are to be viewed as expressing a UTC time. The purpose of :meth:`fromutc` is to
1426 adjust the date and time members, returning an equivalent datetime in *self*'s
1427 local time.
1428
1429 Most :class:`tzinfo` subclasses should be able to inherit the default
1430 :meth:`fromutc` implementation without problems. It's strong enough to handle
1431 fixed-offset time zones, and time zones accounting for both standard and
1432 daylight time, and the latter even if the DST transition times differ in
1433 different years. An example of a time zone the default :meth:`fromutc`
1434 implementation may not handle correctly in all cases is one where the standard
1435 offset (from UTC) depends on the specific date and time passed, which can happen
1436 for political reasons. The default implementations of :meth:`astimezone` and
1437 :meth:`fromutc` may not produce the result you want if the result is one of the
1438 hours straddling the moment the standard offset changes.
1439
1440 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1441 like::
1442
1443 def fromutc(self, dt):
1444 # raise ValueError error if dt.tzinfo is not self
1445 dtoff = dt.utcoffset()
1446 dtdst = dt.dst()
1447 # raise ValueError if dtoff is None or dtdst is None
1448 delta = dtoff - dtdst # this is self's standard offset
1449 if delta:
1450 dt += delta # convert to standard local time
1451 dtdst = dt.dst()
1452 # raise ValueError if dtdst is None
1453 if dtdst:
1454 return dt + dtdst
1455 else:
1456 return dt
1457
1458Example :class:`tzinfo` classes:
1459
1460.. literalinclude:: ../includes/tzinfo-examples.py
1461
1462
1463Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1464subclass accounting for both standard and daylight time, at the DST transition
1465points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl16215c72010-10-06 07:59:52 +00001466minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
14671:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001468
1469 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1470 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1471 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1472
1473 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1474
1475 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1476
1477When DST starts (the "start" line), the local wall clock leaps from 1:59 to
14783:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1479``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1480begins. In order for :meth:`astimezone` to make this guarantee, the
1481:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1482Eastern) to be in daylight time.
1483
1484When DST ends (the "end" line), there's a potentially worse problem: there's an
1485hour that can't be spelled unambiguously in local wall time: the last hour of
1486daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1487daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1488to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1489:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1490hours into the same local hour then. In the Eastern example, UTC times of the
1491form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1492:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1493consider times in the "repeated hour" to be in standard time. This is easily
1494arranged, as in the example, by expressing DST switch times in the time zone's
1495standard local time.
1496
1497Applications that can't bear such ambiguities should avoid using hybrid
1498:class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any
1499other fixed-offset :class:`tzinfo` subclass (such as a class representing only
1500EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
Georg Brandl48310cd2009-01-03 21:18:54 +00001501
Georg Brandl116aa622007-08-15 14:28:22 +00001502
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001503.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00001504
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001505:meth:`strftime` and :meth:`strptime` Behavior
1506----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001507
1508:class:`date`, :class:`datetime`, and :class:`time` objects all support a
1509``strftime(format)`` method, to create a string representing the time under the
1510control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1511acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1512although not all objects support a :meth:`timetuple` method.
1513
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001514Conversely, the :meth:`datetime.strptime` class method creates a
1515:class:`datetime` object from a string representing a date and time and a
1516corresponding format string. ``datetime.strptime(date_string, format)`` is
1517equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1518
Georg Brandl116aa622007-08-15 14:28:22 +00001519For :class:`time` objects, the format codes for year, month, and day should not
1520be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001521is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00001522
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001523For :class:`date` objects, the format codes for hours, minutes, seconds, and
1524microseconds should not be used, as :class:`date` objects have no such
1525values. If they're used anyway, ``0`` is substituted for them.
1526
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001527For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1528strings.
1529
1530For an aware object:
1531
1532``%z``
1533 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1534 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1535 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1536 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1537 replaced with the string ``'-0330'``.
1538
1539``%Z``
1540 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1541 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl116aa622007-08-15 14:28:22 +00001542
Georg Brandl116aa622007-08-15 14:28:22 +00001543The full set of format codes supported varies across platforms, because Python
1544calls the platform C library's :func:`strftime` function, and platform
Georg Brandl48310cd2009-01-03 21:18:54 +00001545variations are common.
Christian Heimes895627f2007-12-08 17:28:33 +00001546
1547The following is a list of all the format codes that the C standard (1989
1548version) requires, and these work on all platforms with a standard C
1549implementation. Note that the 1999 version of the C standard added additional
1550format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001551
1552The exact range of years for which :meth:`strftime` works also varies across
1553platforms. Regardless of platform, years before 1900 cannot be used.
1554
Christian Heimes895627f2007-12-08 17:28:33 +00001555+-----------+--------------------------------+-------+
1556| Directive | Meaning | Notes |
1557+===========+================================+=======+
1558| ``%a`` | Locale's abbreviated weekday | |
1559| | name. | |
1560+-----------+--------------------------------+-------+
1561| ``%A`` | Locale's full weekday name. | |
1562+-----------+--------------------------------+-------+
1563| ``%b`` | Locale's abbreviated month | |
1564| | name. | |
1565+-----------+--------------------------------+-------+
1566| ``%B`` | Locale's full month name. | |
1567+-----------+--------------------------------+-------+
1568| ``%c`` | Locale's appropriate date and | |
1569| | time representation. | |
1570+-----------+--------------------------------+-------+
1571| ``%d`` | Day of the month as a decimal | |
1572| | number [01,31]. | |
1573+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001574| ``%f`` | Microsecond as a decimal | \(1) |
1575| | number [0,999999], zero-padded | |
1576| | on the left | |
1577+-----------+--------------------------------+-------+
Christian Heimes895627f2007-12-08 17:28:33 +00001578| ``%H`` | Hour (24-hour clock) as a | |
1579| | decimal number [00,23]. | |
1580+-----------+--------------------------------+-------+
1581| ``%I`` | Hour (12-hour clock) as a | |
1582| | decimal number [01,12]. | |
1583+-----------+--------------------------------+-------+
1584| ``%j`` | Day of the year as a decimal | |
1585| | number [001,366]. | |
1586+-----------+--------------------------------+-------+
1587| ``%m`` | Month as a decimal number | |
1588| | [01,12]. | |
1589+-----------+--------------------------------+-------+
1590| ``%M`` | Minute as a decimal number | |
1591| | [00,59]. | |
1592+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001593| ``%p`` | Locale's equivalent of either | \(2) |
Christian Heimes895627f2007-12-08 17:28:33 +00001594| | AM or PM. | |
1595+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001596| ``%S`` | Second as a decimal number | \(3) |
Christian Heimes895627f2007-12-08 17:28:33 +00001597| | [00,61]. | |
1598+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001599| ``%U`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001600| | (Sunday as the first day of | |
1601| | the week) as a decimal number | |
1602| | [00,53]. All days in a new | |
1603| | year preceding the first | |
1604| | Sunday are considered to be in | |
1605| | week 0. | |
1606+-----------+--------------------------------+-------+
1607| ``%w`` | Weekday as a decimal number | |
1608| | [0(Sunday),6]. | |
1609+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001610| ``%W`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001611| | (Monday as the first day of | |
1612| | the week) as a decimal number | |
1613| | [00,53]. All days in a new | |
1614| | year preceding the first | |
1615| | Monday are considered to be in | |
1616| | week 0. | |
1617+-----------+--------------------------------+-------+
1618| ``%x`` | Locale's appropriate date | |
1619| | representation. | |
1620+-----------+--------------------------------+-------+
1621| ``%X`` | Locale's appropriate time | |
1622| | representation. | |
1623+-----------+--------------------------------+-------+
1624| ``%y`` | Year without century as a | |
1625| | decimal number [00,99]. | |
1626+-----------+--------------------------------+-------+
1627| ``%Y`` | Year with century as a decimal | |
1628| | number. | |
1629+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001630| ``%z`` | UTC offset in the form +HHMM | \(5) |
Christian Heimes895627f2007-12-08 17:28:33 +00001631| | or -HHMM (empty string if the | |
1632| | the object is naive). | |
1633+-----------+--------------------------------+-------+
1634| ``%Z`` | Time zone name (empty string | |
1635| | if the object is naive). | |
1636+-----------+--------------------------------+-------+
1637| ``%%`` | A literal ``'%'`` character. | |
1638+-----------+--------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001639
Christian Heimes895627f2007-12-08 17:28:33 +00001640Notes:
1641
1642(1)
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001643 When used with the :meth:`strptime` method, the ``%f`` directive
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001644 accepts from one to six digits and zero pads on the right. ``%f`` is
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001645 an extension to the set of format characters in the C standard (but
1646 implemented separately in datetime objects, and therefore always
1647 available).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001648
1649(2)
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001650 When used with the :meth:`strptime` method, the ``%p`` directive only affects
Christian Heimes895627f2007-12-08 17:28:33 +00001651 the output hour field if the ``%I`` directive is used to parse the hour.
1652
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001653(3)
R. David Murraybd25d332009-04-02 04:50:03 +00001654 The range really is ``0`` to ``61``; according to the Posix standard this
1655 accounts for leap seconds and the (very rare) double leap seconds.
1656 The :mod:`time` module may produce and does accept leap seconds since
1657 it is based on the Posix standard, but the :mod:`datetime` module
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001658 does not accept leap seconds in :meth:`strptime` input nor will it
R. David Murraybd25d332009-04-02 04:50:03 +00001659 produce them in :func:`strftime` output.
Christian Heimes895627f2007-12-08 17:28:33 +00001660
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001661(4)
Benjamin Peterson23b9ef72010-02-03 02:43:37 +00001662 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in
Christian Heimes895627f2007-12-08 17:28:33 +00001663 calculations when the day of the week and the year are specified.
1664
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001665(5)
Christian Heimes895627f2007-12-08 17:28:33 +00001666 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1667 ``%z`` is replaced with the string ``'-0330'``.