blob: 758e4d243db9825c1c3aad51a665926da2334ba2 [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 Peterson4ac9ce42009-10-04 14:49:41 +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 Peterson4ac9ce42009-10-04 14:49:41 +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 Peterson4ac9ce42009-10-04 14:49:41 +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 Peterson4ac9ce42009-10-04 14:49:41 +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 Peterson5e55b3e2010-02-03 02:35:45 +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+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000223| ``f = t2 / t3`` | Division (3) of *t2* by *t3*. Returns a |
224| | :class:`float` object. |
225+--------------------------------+-----------------------------------------------+
226| ``t1 = t2 // i`` or | The floor is computed and the remainder (if |
227| ``t1 = t2 // t3`` | any) is thrown away. In the second case, an |
228| | integer is returned (3) |
229+--------------------------------+-----------------------------------------------+
230| ``t1 = t2 % t3`` | The remainder is computed as a |
231| | :class:`timedelta` object. (3) |
232+--------------------------------+-----------------------------------------------+
233| ``q, r = divmod(t1, t2)`` | Computes the quotient and the remainder: |
234| | ``q = t1 // t2`` (3) and ``r = t1 % t2``. |
235| | q is an integer and r is a :class:`timedelta` |
236| | object. |
Georg Brandl116aa622007-08-15 14:28:22 +0000237+--------------------------------+-----------------------------------------------+
238| ``+t1`` | Returns a :class:`timedelta` object with the |
239| | same value. (2) |
240+--------------------------------+-----------------------------------------------+
241| ``-t1`` | equivalent to :class:`timedelta`\ |
242| | (-*t1.days*, -*t1.seconds*, |
243| | -*t1.microseconds*), and to *t1*\* -1. (1)(4) |
244+--------------------------------+-----------------------------------------------+
Georg Brandl495f7b52009-10-27 15:28:25 +0000245| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, and|
Georg Brandl116aa622007-08-15 14:28:22 +0000246| | to -*t* when ``t.days < 0``. (2) |
247+--------------------------------+-----------------------------------------------+
248
249Notes:
250
251(1)
252 This is exact, but may overflow.
253
254(2)
255 This is exact, and cannot overflow.
256
257(3)
258 Division by 0 raises :exc:`ZeroDivisionError`.
259
260(4)
261 -*timedelta.max* is not representable as a :class:`timedelta` object.
262
263In addition to the operations listed above :class:`timedelta` objects support
264certain additions and subtractions with :class:`date` and :class:`datetime`
265objects (see below).
266
Mark Dickinson7c186e22010-04-20 22:32:49 +0000267.. versionadded:: 3.2
268 Floor division and true division of a :class:`timedelta` object by
269 another :class:`timedelta` object are now supported, as are
270 remainder operations and the :func:`divmod` function.
271
272
Georg Brandl116aa622007-08-15 14:28:22 +0000273Comparisons 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
Antoine Pitroube6859d2009-11-25 23:02:32 +0000285Instance methods:
286
287.. method:: timedelta.total_seconds()
288
289 Return the total number of seconds contained in the duration. Equivalent to
290 ``td.microseconds / 1000000 + td.seconds + td.days * 24 * 3600``.
291
292 .. versionadded:: 3.2
293
294
Christian Heimesfe337bf2008-03-23 21:54:12 +0000295Example usage:
Georg Brandl48310cd2009-01-03 21:18:54 +0000296
Christian Heimes895627f2007-12-08 17:28:33 +0000297 >>> from datetime import timedelta
298 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000299 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Christian Heimes895627f2007-12-08 17:28:33 +0000300 ... minutes=50, seconds=600) # adds up to 365 days
Antoine Pitroube6859d2009-11-25 23:02:32 +0000301 >>> year.total_seconds()
302 31536000.0
Christian Heimes895627f2007-12-08 17:28:33 +0000303 >>> year == another_year
304 True
305 >>> ten_years = 10 * year
306 >>> ten_years, ten_years.days // 365
307 (datetime.timedelta(3650), 10)
308 >>> nine_years = ten_years - year
309 >>> nine_years, nine_years.days // 365
310 (datetime.timedelta(3285), 9)
311 >>> three_years = nine_years // 3;
312 >>> three_years, three_years.days // 365
313 (datetime.timedelta(1095), 3)
314 >>> abs(three_years - ten_years) == 2 * three_years + year
315 True
316
Georg Brandl116aa622007-08-15 14:28:22 +0000317
318.. _datetime-date:
319
320:class:`date` Objects
321---------------------
322
323A :class:`date` object represents a date (year, month and day) in an idealized
324calendar, the current Gregorian calendar indefinitely extended in both
325directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
326called day number 2, and so on. This matches the definition of the "proleptic
327Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
328where it's the base calendar for all computations. See the book for algorithms
329for converting between proleptic Gregorian ordinals and many other calendar
330systems.
331
332
333.. class:: date(year, month, day)
334
Georg Brandl5c106642007-11-29 17:41:05 +0000335 All arguments are required. Arguments may be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000336 ranges:
337
338 * ``MINYEAR <= year <= MAXYEAR``
339 * ``1 <= month <= 12``
340 * ``1 <= day <= number of days in the given month and year``
341
342 If an argument outside those ranges is given, :exc:`ValueError` is raised.
343
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000344
Georg Brandl116aa622007-08-15 14:28:22 +0000345Other constructors, all class methods:
346
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000347.. classmethod:: date.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000348
349 Return the current local date. This is equivalent to
350 ``date.fromtimestamp(time.time())``.
351
352
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000353.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000354
355 Return the local date corresponding to the POSIX timestamp, such as is returned
356 by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out
357 of the range of values supported by the platform C :cfunc:`localtime` function.
358 It's common for this to be restricted to years from 1970 through 2038. Note
359 that on non-POSIX systems that include leap seconds in their notion of a
360 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
361
362
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000363.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000364
365 Return the date corresponding to the proleptic Gregorian ordinal, where January
366 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
367 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
368 d``.
369
Georg Brandl116aa622007-08-15 14:28:22 +0000370
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000371Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000372
373.. attribute:: date.min
374
375 The earliest representable date, ``date(MINYEAR, 1, 1)``.
376
377
378.. attribute:: date.max
379
380 The latest representable date, ``date(MAXYEAR, 12, 31)``.
381
382
383.. attribute:: date.resolution
384
385 The smallest possible difference between non-equal date objects,
386 ``timedelta(days=1)``.
387
Georg Brandl116aa622007-08-15 14:28:22 +0000388
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000389Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000390
391.. attribute:: date.year
392
393 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
394
395
396.. attribute:: date.month
397
398 Between 1 and 12 inclusive.
399
400
401.. attribute:: date.day
402
403 Between 1 and the number of days in the given month of the given year.
404
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000405
Georg Brandl116aa622007-08-15 14:28:22 +0000406Supported operations:
407
408+-------------------------------+----------------------------------------------+
409| Operation | Result |
410+===============================+==============================================+
411| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
412| | from *date1*. (1) |
413+-------------------------------+----------------------------------------------+
414| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
415| | timedelta == date1``. (2) |
416+-------------------------------+----------------------------------------------+
417| ``timedelta = date1 - date2`` | \(3) |
418+-------------------------------+----------------------------------------------+
419| ``date1 < date2`` | *date1* is considered less than *date2* when |
420| | *date1* precedes *date2* in time. (4) |
421+-------------------------------+----------------------------------------------+
422
423Notes:
424
425(1)
426 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
427 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
428 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
429 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
430 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
431
432(2)
433 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
434 isolation can overflow in cases where date1 - timedelta does not.
435 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
436
437(3)
438 This is exact, and cannot overflow. timedelta.seconds and
439 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
440
441(4)
442 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
443 date2.toordinal()``. In order to stop comparison from falling back to the
444 default scheme of comparing object addresses, date comparison normally raises
445 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
446 However, ``NotImplemented`` is returned instead if the other comparand has a
447 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
448 chance at implementing mixed-type comparison. If not, when a :class:`date`
449 object is compared to an object of a different type, :exc:`TypeError` is raised
450 unless the comparison is ``==`` or ``!=``. The latter cases return
451 :const:`False` or :const:`True`, respectively.
452
453Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
454objects are considered to be true.
455
456Instance methods:
457
Georg Brandl116aa622007-08-15 14:28:22 +0000458.. method:: date.replace(year, month, day)
459
460 Return a date with the same value, except for those members given new values by
461 whichever keyword arguments are specified. For example, if ``d == date(2002,
462 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
463
464
465.. method:: date.timetuple()
466
467 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
468 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
469 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
470 d.weekday(), d.toordinal() - date(d.year, 1, 1).toordinal() + 1, -1))``
471
472
473.. method:: date.toordinal()
474
475 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
476 has ordinal 1. For any :class:`date` object *d*,
477 ``date.fromordinal(d.toordinal()) == d``.
478
479
480.. method:: date.weekday()
481
482 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
483 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
484 :meth:`isoweekday`.
485
486
487.. method:: date.isoweekday()
488
489 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
490 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
491 :meth:`weekday`, :meth:`isocalendar`.
492
493
494.. method:: date.isocalendar()
495
496 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
497
498 The ISO calendar is a widely used variant of the Gregorian calendar. See
Mark Dickinsonf964ac22009-11-03 16:29:10 +0000499 http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
500 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000501
502 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
503 Monday and ends on a Sunday. The first week of an ISO year is the first
504 (Gregorian) calendar week of a year containing a Thursday. This is called week
505 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
506
507 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
508 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
509 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
510 4).isocalendar() == (2004, 1, 7)``.
511
512
513.. method:: date.isoformat()
514
515 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
516 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
517
518
519.. method:: date.__str__()
520
521 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
522
523
524.. method:: date.ctime()
525
526 Return a string representing the date, for example ``date(2002, 12,
527 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
528 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
529 :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
530 :meth:`date.ctime` does not invoke) conforms to the C standard.
531
532
533.. method:: date.strftime(format)
534
535 Return a string representing the date, controlled by an explicit format string.
536 Format codes referring to hours, minutes or seconds will see 0 values. See
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000537 section :ref:`strftime-strptime-behavior`.
538
Georg Brandl116aa622007-08-15 14:28:22 +0000539
Christian Heimes895627f2007-12-08 17:28:33 +0000540Example of counting days to an event::
541
542 >>> import time
543 >>> from datetime import date
544 >>> today = date.today()
545 >>> today
546 datetime.date(2007, 12, 5)
547 >>> today == date.fromtimestamp(time.time())
548 True
549 >>> my_birthday = date(today.year, 6, 24)
550 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000551 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000552 >>> my_birthday
553 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000554 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000555 >>> time_to_birthday.days
556 202
557
Christian Heimesfe337bf2008-03-23 21:54:12 +0000558Example of working with :class:`date`:
559
560.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000561
562 >>> from datetime import date
563 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
564 >>> d
565 datetime.date(2002, 3, 11)
566 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000567 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000568 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000569 2002 # year
570 3 # month
571 11 # day
572 0
573 0
574 0
575 0 # weekday (0 = Monday)
576 70 # 70th day in the year
577 -1
578 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000579 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000580 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000581 2002 # ISO year
582 11 # ISO week number
583 1 # ISO day number ( 1 = Monday )
584 >>> d.isoformat()
585 '2002-03-11'
586 >>> d.strftime("%d/%m/%y")
587 '11/03/02'
588 >>> d.strftime("%A %d. %B %Y")
589 'Monday 11. March 2002'
590
Georg Brandl116aa622007-08-15 14:28:22 +0000591
592.. _datetime-datetime:
593
594:class:`datetime` Objects
595-------------------------
596
597A :class:`datetime` object is a single object containing all the information
598from a :class:`date` object and a :class:`time` object. Like a :class:`date`
599object, :class:`datetime` assumes the current Gregorian calendar extended in
600both directions; like a time object, :class:`datetime` assumes there are exactly
6013600\*24 seconds in every day.
602
603Constructor:
604
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000605.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000606
607 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000608 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
609 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000610
611 * ``MINYEAR <= year <= MAXYEAR``
612 * ``1 <= month <= 12``
613 * ``1 <= day <= number of days in the given month and year``
614 * ``0 <= hour < 24``
615 * ``0 <= minute < 60``
616 * ``0 <= second < 60``
617 * ``0 <= microsecond < 1000000``
618
619 If an argument outside those ranges is given, :exc:`ValueError` is raised.
620
621Other constructors, all class methods:
622
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000623.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000624
625 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
626 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
627 :meth:`fromtimestamp`.
628
629
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000630.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000631
632 Return the current local date and time. If optional argument *tz* is ``None``
633 or not specified, this is like :meth:`today`, but, if possible, supplies more
634 precision than can be gotten from going through a :func:`time.time` timestamp
635 (for example, this may be possible on platforms supplying the C
636 :cfunc:`gettimeofday` function).
637
638 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
639 current date and time are converted to *tz*'s time zone. In this case the
640 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
641 See also :meth:`today`, :meth:`utcnow`.
642
643
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000644.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000645
646 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
647 :meth:`now`, but returns the current UTC date and time, as a naive
648 :class:`datetime` object. See also :meth:`now`.
649
650
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000651.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000652
653 Return the local date and time corresponding to the POSIX timestamp, such as is
654 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
655 specified, the timestamp is converted to the platform's local date and time, and
656 the returned :class:`datetime` object is naive.
657
658 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
659 timestamp is converted to *tz*'s time zone. In this case the result is
660 equivalent to
661 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
662
663 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
664 the range of values supported by the platform C :cfunc:`localtime` or
665 :cfunc:`gmtime` functions. It's common for this to be restricted to years in
666 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
667 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
668 and then it's possible to have two timestamps differing by a second that yield
669 identical :class:`datetime` objects. See also :meth:`utcfromtimestamp`.
670
671
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000672.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000673
674 Return the UTC :class:`datetime` corresponding to the POSIX timestamp, with
675 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
676 out of the range of values supported by the platform C :cfunc:`gmtime` function.
677 It's common for this to be restricted to years in 1970 through 2038. See also
678 :meth:`fromtimestamp`.
679
680
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000681.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000682
683 Return the :class:`datetime` corresponding to the proleptic Gregorian ordinal,
684 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
685 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
686 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
687
688
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000689.. classmethod:: datetime.combine(date, time)
Georg Brandl116aa622007-08-15 14:28:22 +0000690
691 Return a new :class:`datetime` object whose date members are equal to the given
692 :class:`date` object's, and whose time and :attr:`tzinfo` members are equal to
693 the given :class:`time` object's. For any :class:`datetime` object *d*, ``d ==
694 datetime.combine(d.date(), d.timetz())``. If date is a :class:`datetime`
695 object, its time and :attr:`tzinfo` members are ignored.
696
697
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000698.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000699
700 Return a :class:`datetime` corresponding to *date_string*, parsed according to
701 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
702 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
703 can't be parsed by :func:`time.strptime` or if it returns a value which isn't a
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000704 time tuple. See section :ref:`strftime-strptime-behavior`.
705
Georg Brandl116aa622007-08-15 14:28:22 +0000706
Georg Brandl116aa622007-08-15 14:28:22 +0000707
708Class attributes:
709
Georg Brandl116aa622007-08-15 14:28:22 +0000710.. attribute:: datetime.min
711
712 The earliest representable :class:`datetime`, ``datetime(MINYEAR, 1, 1,
713 tzinfo=None)``.
714
715
716.. attribute:: datetime.max
717
718 The latest representable :class:`datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
719 59, 999999, tzinfo=None)``.
720
721
722.. attribute:: datetime.resolution
723
724 The smallest possible difference between non-equal :class:`datetime` objects,
725 ``timedelta(microseconds=1)``.
726
Georg Brandl116aa622007-08-15 14:28:22 +0000727
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000728Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000729
730.. attribute:: datetime.year
731
732 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
733
734
735.. attribute:: datetime.month
736
737 Between 1 and 12 inclusive.
738
739
740.. attribute:: datetime.day
741
742 Between 1 and the number of days in the given month of the given year.
743
744
745.. attribute:: datetime.hour
746
747 In ``range(24)``.
748
749
750.. attribute:: datetime.minute
751
752 In ``range(60)``.
753
754
755.. attribute:: datetime.second
756
757 In ``range(60)``.
758
759
760.. attribute:: datetime.microsecond
761
762 In ``range(1000000)``.
763
764
765.. attribute:: datetime.tzinfo
766
767 The object passed as the *tzinfo* argument to the :class:`datetime` constructor,
768 or ``None`` if none was passed.
769
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000770
Georg Brandl116aa622007-08-15 14:28:22 +0000771Supported operations:
772
773+---------------------------------------+-------------------------------+
774| Operation | Result |
775+=======================================+===============================+
776| ``datetime2 = datetime1 + timedelta`` | \(1) |
777+---------------------------------------+-------------------------------+
778| ``datetime2 = datetime1 - timedelta`` | \(2) |
779+---------------------------------------+-------------------------------+
780| ``timedelta = datetime1 - datetime2`` | \(3) |
781+---------------------------------------+-------------------------------+
782| ``datetime1 < datetime2`` | Compares :class:`datetime` to |
783| | :class:`datetime`. (4) |
784+---------------------------------------+-------------------------------+
785
786(1)
787 datetime2 is a duration of timedelta removed from datetime1, moving forward in
788 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
789 result has the same :attr:`tzinfo` member as the input datetime, and datetime2 -
790 datetime1 == timedelta after. :exc:`OverflowError` is raised if datetime2.year
791 would be smaller than :const:`MINYEAR` or larger than :const:`MAXYEAR`. Note
792 that no time zone adjustments are done even if the input is an aware object.
793
794(2)
795 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
796 addition, the result has the same :attr:`tzinfo` member as the input datetime,
797 and no time zone adjustments are done even if the input is aware. This isn't
798 quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation
799 can overflow in cases where datetime1 - timedelta does not.
800
801(3)
802 Subtraction of a :class:`datetime` from a :class:`datetime` is defined only if
803 both operands are naive, or if both are aware. If one is aware and the other is
804 naive, :exc:`TypeError` is raised.
805
806 If both are naive, or both are aware and have the same :attr:`tzinfo` member,
807 the :attr:`tzinfo` members are ignored, and the result is a :class:`timedelta`
808 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
809 are done in this case.
810
811 If both are aware and have different :attr:`tzinfo` members, ``a-b`` acts as if
812 *a* and *b* were first converted to naive UTC datetimes first. The result is
813 ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) -
814 b.utcoffset())`` except that the implementation never overflows.
815
816(4)
817 *datetime1* is considered less than *datetime2* when *datetime1* precedes
818 *datetime2* in time.
819
820 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
821 If both comparands are aware, and have the same :attr:`tzinfo` member, the
822 common :attr:`tzinfo` member is ignored and the base datetimes are compared. If
823 both comparands are aware and have different :attr:`tzinfo` members, the
824 comparands are first adjusted by subtracting their UTC offsets (obtained from
825 ``self.utcoffset()``).
826
827 .. note::
828
829 In order to stop comparison from falling back to the default scheme of comparing
830 object addresses, datetime comparison normally raises :exc:`TypeError` if the
831 other comparand isn't also a :class:`datetime` object. However,
832 ``NotImplemented`` is returned instead if the other comparand has a
833 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
834 chance at implementing mixed-type comparison. If not, when a :class:`datetime`
835 object is compared to an object of a different type, :exc:`TypeError` is raised
836 unless the comparison is ``==`` or ``!=``. The latter cases return
837 :const:`False` or :const:`True`, respectively.
838
839:class:`datetime` objects can be used as dictionary keys. In Boolean contexts,
840all :class:`datetime` objects are considered to be true.
841
842Instance methods:
843
Georg Brandl116aa622007-08-15 14:28:22 +0000844.. method:: datetime.date()
845
846 Return :class:`date` object with same year, month and day.
847
848
849.. method:: datetime.time()
850
851 Return :class:`time` object with same hour, minute, second and microsecond.
852 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
853
854
855.. method:: datetime.timetz()
856
857 Return :class:`time` object with same hour, minute, second, microsecond, and
858 tzinfo members. See also method :meth:`time`.
859
860
861.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
862
863 Return a datetime with the same members, except for those members given new
864 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
865 can be specified to create a naive datetime from an aware datetime with no
866 conversion of date and time members.
867
868
869.. method:: datetime.astimezone(tz)
870
871 Return a :class:`datetime` object with new :attr:`tzinfo` member *tz*, adjusting
872 the date and time members so the result is the same UTC time as *self*, but in
873 *tz*'s local time.
874
875 *tz* must be an instance of a :class:`tzinfo` subclass, and its
876 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
877 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
878 not return ``None``).
879
880 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
881 adjustment of date or time members is performed. Else the result is local time
882 in time zone *tz*, representing the same UTC time as *self*: after ``astz =
883 dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have the same date
884 and time members as ``dt - dt.utcoffset()``. The discussion of class
885 :class:`tzinfo` explains the cases at Daylight Saving Time transition boundaries
886 where this cannot be achieved (an issue only if *tz* models both standard and
887 daylight time).
888
889 If you merely want to attach a time zone object *tz* to a datetime *dt* without
890 adjustment of date and time members, use ``dt.replace(tzinfo=tz)``. If you
891 merely want to remove the time zone object from an aware datetime *dt* without
892 conversion of date and time members, use ``dt.replace(tzinfo=None)``.
893
894 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
895 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
896 Ignoring error cases, :meth:`astimezone` acts like::
897
898 def astimezone(self, tz):
899 if self.tzinfo is tz:
900 return self
901 # Convert self to UTC, and attach the new time zone object.
902 utc = (self - self.utcoffset()).replace(tzinfo=tz)
903 # Convert from UTC to tz's local time.
904 return tz.fromutc(utc)
905
906
907.. method:: datetime.utcoffset()
908
909 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
910 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
911 return ``None``, or a :class:`timedelta` object representing a whole number of
912 minutes with magnitude less than one day.
913
914
915.. method:: datetime.dst()
916
917 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
918 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
919 ``None``, or a :class:`timedelta` object representing a whole number of minutes
920 with magnitude less than one day.
921
922
923.. method:: datetime.tzname()
924
925 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
926 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
927 ``None`` or a string object,
928
929
930.. method:: datetime.timetuple()
931
932 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
933 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
934 d.hour, d.minute, d.second, d.weekday(), d.toordinal() - date(d.year, 1,
935 1).toordinal() + 1, dst))`` The :attr:`tm_isdst` flag of the result is set
936 according to the :meth:`dst` method: :attr:`tzinfo` is ``None`` or :meth:`dst`
937 returns ``None``, :attr:`tm_isdst` is set to ``-1``; else if :meth:`dst`
938 returns a non-zero value, :attr:`tm_isdst` is set to ``1``; else ``tm_isdst`` is
939 set to ``0``.
940
941
942.. method:: datetime.utctimetuple()
943
944 If :class:`datetime` instance *d* is naive, this is the same as
945 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
946 ``d.dst()`` returns. DST is never in effect for a UTC time.
947
948 If *d* is aware, *d* is normalized to UTC time, by subtracting
949 ``d.utcoffset()``, and a :class:`time.struct_time` for the normalized time is
950 returned. :attr:`tm_isdst` is forced to 0. Note that the result's
951 :attr:`tm_year` member may be :const:`MINYEAR`\ -1 or :const:`MAXYEAR`\ +1, if
952 *d*.year was ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
953 boundary.
954
955
956.. method:: datetime.toordinal()
957
958 Return the proleptic Gregorian ordinal of the date. The same as
959 ``self.date().toordinal()``.
960
961
962.. method:: datetime.weekday()
963
964 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
965 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
966
967
968.. method:: datetime.isoweekday()
969
970 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
971 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
972 :meth:`isocalendar`.
973
974
975.. method:: datetime.isocalendar()
976
977 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
978 ``self.date().isocalendar()``.
979
980
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000981.. method:: datetime.isoformat(sep='T')
Georg Brandl116aa622007-08-15 14:28:22 +0000982
983 Return a string representing the date and time in ISO 8601 format,
984 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
985 YYYY-MM-DDTHH:MM:SS
986
987 If :meth:`utcoffset` does not return ``None``, a 6-character string is
988 appended, giving the UTC offset in (signed) hours and minutes:
989 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
990 YYYY-MM-DDTHH:MM:SS+HH:MM
991
992 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000993 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +0000994
995 >>> from datetime import tzinfo, timedelta, datetime
996 >>> class TZ(tzinfo):
997 ... def utcoffset(self, dt): return timedelta(minutes=-399)
998 ...
999 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1000 '2002-12-25 00:00:00-06:39'
1001
1002
1003.. method:: datetime.__str__()
1004
1005 For a :class:`datetime` instance *d*, ``str(d)`` is equivalent to
1006 ``d.isoformat(' ')``.
1007
1008
1009.. method:: datetime.ctime()
1010
1011 Return a string representing the date and time, for example ``datetime(2002, 12,
1012 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1013 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
1014 native C :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
1015 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1016
1017
1018.. method:: datetime.strftime(format)
1019
1020 Return a string representing the date and time, controlled by an explicit format
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001021 string. See section :ref:`strftime-strptime-behavior`.
1022
Georg Brandl116aa622007-08-15 14:28:22 +00001023
Christian Heimesfe337bf2008-03-23 21:54:12 +00001024Examples of working with datetime objects:
1025
1026.. doctest::
1027
Christian Heimes895627f2007-12-08 17:28:33 +00001028 >>> from datetime import datetime, date, time
1029 >>> # Using datetime.combine()
1030 >>> d = date(2005, 7, 14)
1031 >>> t = time(12, 30)
1032 >>> datetime.combine(d, t)
1033 datetime.datetime(2005, 7, 14, 12, 30)
1034 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001035 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001036 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001037 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001038 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1039 >>> # Using datetime.strptime()
1040 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1041 >>> dt
1042 datetime.datetime(2006, 11, 21, 16, 30)
1043 >>> # Using datetime.timetuple() to get tuple of all attributes
1044 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001045 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001046 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001047 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001048 2006 # year
1049 11 # month
1050 21 # day
1051 16 # hour
1052 30 # minute
1053 0 # second
1054 1 # weekday (0 = Monday)
1055 325 # number of days since 1st January
1056 -1 # dst - method tzinfo.dst() returned None
1057 >>> # Date in ISO format
1058 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001059 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001060 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001061 ...
1062 2006 # ISO year
1063 47 # ISO week
1064 2 # ISO weekday
1065 >>> # Formatting datetime
1066 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1067 'Tuesday, 21. November 2006 04:30PM'
1068
Christian Heimesfe337bf2008-03-23 21:54:12 +00001069Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001070
1071 >>> from datetime import timedelta, datetime, tzinfo
1072 >>> class GMT1(tzinfo):
1073 ... def __init__(self): # DST starts last Sunday in March
1074 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1075 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001076 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001077 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1078 ... def utcoffset(self, dt):
1079 ... return timedelta(hours=1) + self.dst(dt)
Georg Brandl48310cd2009-01-03 21:18:54 +00001080 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001081 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1082 ... return timedelta(hours=1)
1083 ... else:
1084 ... return timedelta(0)
1085 ... def tzname(self,dt):
1086 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001087 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001088 >>> class GMT2(tzinfo):
1089 ... def __init__(self):
Georg Brandl48310cd2009-01-03 21:18:54 +00001090 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001091 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001092 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001093 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1094 ... def utcoffset(self, dt):
1095 ... return timedelta(hours=1) + self.dst(dt)
1096 ... def dst(self, dt):
1097 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1098 ... return timedelta(hours=2)
1099 ... else:
1100 ... return timedelta(0)
1101 ... def tzname(self,dt):
1102 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001103 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001104 >>> gmt1 = GMT1()
1105 >>> # Daylight Saving Time
1106 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1107 >>> dt1.dst()
1108 datetime.timedelta(0)
1109 >>> dt1.utcoffset()
1110 datetime.timedelta(0, 3600)
1111 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1112 >>> dt2.dst()
1113 datetime.timedelta(0, 3600)
1114 >>> dt2.utcoffset()
1115 datetime.timedelta(0, 7200)
1116 >>> # Convert datetime to another time zone
1117 >>> dt3 = dt2.astimezone(GMT2())
1118 >>> dt3 # doctest: +ELLIPSIS
1119 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1120 >>> dt2 # doctest: +ELLIPSIS
1121 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1122 >>> dt2.utctimetuple() == dt3.utctimetuple()
1123 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001124
Christian Heimes895627f2007-12-08 17:28:33 +00001125
Georg Brandl116aa622007-08-15 14:28:22 +00001126
1127.. _datetime-time:
1128
1129:class:`time` Objects
1130---------------------
1131
1132A time object represents a (local) time of day, independent of any particular
1133day, and subject to adjustment via a :class:`tzinfo` object.
1134
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001135.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001136
1137 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001138 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001139 following ranges:
1140
1141 * ``0 <= hour < 24``
1142 * ``0 <= minute < 60``
1143 * ``0 <= second < 60``
1144 * ``0 <= microsecond < 1000000``.
1145
1146 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1147 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1148
1149Class attributes:
1150
1151
1152.. attribute:: time.min
1153
1154 The earliest representable :class:`time`, ``time(0, 0, 0, 0)``.
1155
1156
1157.. attribute:: time.max
1158
1159 The latest representable :class:`time`, ``time(23, 59, 59, 999999)``.
1160
1161
1162.. attribute:: time.resolution
1163
1164 The smallest possible difference between non-equal :class:`time` objects,
1165 ``timedelta(microseconds=1)``, although note that arithmetic on :class:`time`
1166 objects is not supported.
1167
Georg Brandl116aa622007-08-15 14:28:22 +00001168
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001169Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001170
1171.. attribute:: time.hour
1172
1173 In ``range(24)``.
1174
1175
1176.. attribute:: time.minute
1177
1178 In ``range(60)``.
1179
1180
1181.. attribute:: time.second
1182
1183 In ``range(60)``.
1184
1185
1186.. attribute:: time.microsecond
1187
1188 In ``range(1000000)``.
1189
1190
1191.. attribute:: time.tzinfo
1192
1193 The object passed as the tzinfo argument to the :class:`time` constructor, or
1194 ``None`` if none was passed.
1195
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001196
Georg Brandl116aa622007-08-15 14:28:22 +00001197Supported operations:
1198
1199* comparison of :class:`time` to :class:`time`, where *a* is considered less
1200 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1201 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
1202 the same :attr:`tzinfo` member, the common :attr:`tzinfo` member is ignored and
1203 the base times are compared. If both comparands are aware and have different
1204 :attr:`tzinfo` members, the comparands are first adjusted by subtracting their
1205 UTC offsets (obtained from ``self.utcoffset()``). In order to stop mixed-type
1206 comparisons from falling back to the default comparison by object address, when
1207 a :class:`time` object is compared to an object of a different type,
1208 :exc:`TypeError` is raised unless the comparison is ``==`` or ``!=``. The
1209 latter cases return :const:`False` or :const:`True`, respectively.
1210
1211* hash, use as dict key
1212
1213* efficient pickling
1214
1215* in Boolean contexts, a :class:`time` object is considered to be true if and
1216 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1217 ``0`` if that's ``None``), the result is non-zero.
1218
Georg Brandl116aa622007-08-15 14:28:22 +00001219
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001220Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001221
1222.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1223
1224 Return a :class:`time` with the same value, except for those members given new
1225 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
1226 can be specified to create a naive :class:`time` from an aware :class:`time`,
1227 without conversion of the time members.
1228
1229
1230.. method:: time.isoformat()
1231
1232 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1233 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1234 6-character string is appended, giving the UTC offset in (signed) hours and
1235 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1236
1237
1238.. method:: time.__str__()
1239
1240 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1241
1242
1243.. method:: time.strftime(format)
1244
1245 Return a string representing the time, controlled by an explicit format string.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001246 See section :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001247
1248
1249.. method:: time.utcoffset()
1250
1251 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1252 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1253 return ``None`` or a :class:`timedelta` object representing a whole number of
1254 minutes with magnitude less than one day.
1255
1256
1257.. method:: time.dst()
1258
1259 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1260 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1261 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1262 with magnitude less than one day.
1263
1264
1265.. method:: time.tzname()
1266
1267 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1268 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1269 return ``None`` or a string object.
1270
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001271
Christian Heimesfe337bf2008-03-23 21:54:12 +00001272Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001273
Christian Heimes895627f2007-12-08 17:28:33 +00001274 >>> from datetime import time, tzinfo
1275 >>> class GMT1(tzinfo):
1276 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001277 ... return timedelta(hours=1)
1278 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001279 ... return timedelta(0)
1280 ... def tzname(self,dt):
1281 ... return "Europe/Prague"
1282 ...
1283 >>> t = time(12, 10, 30, tzinfo=GMT1())
1284 >>> t # doctest: +ELLIPSIS
1285 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1286 >>> gmt = GMT1()
1287 >>> t.isoformat()
1288 '12:10:30+01:00'
1289 >>> t.dst()
1290 datetime.timedelta(0)
1291 >>> t.tzname()
1292 'Europe/Prague'
1293 >>> t.strftime("%H:%M:%S %Z")
1294 '12:10:30 Europe/Prague'
1295
Georg Brandl116aa622007-08-15 14:28:22 +00001296
1297.. _datetime-tzinfo:
1298
1299:class:`tzinfo` Objects
1300-----------------------
1301
Brett Cannone1327f72009-01-29 04:10:21 +00001302:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001303instantiated directly. You need to derive a concrete subclass, and (at least)
1304supply implementations of the standard :class:`tzinfo` methods needed by the
1305:class:`datetime` methods you use. The :mod:`datetime` module does not supply
1306any concrete subclasses of :class:`tzinfo`.
1307
1308An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1309constructors for :class:`datetime` and :class:`time` objects. The latter objects
1310view their members as being in local time, and the :class:`tzinfo` object
1311supports methods revealing offset of local time from UTC, the name of the time
1312zone, and DST offset, all relative to a date or time object passed to them.
1313
1314Special requirement for pickling: A :class:`tzinfo` subclass must have an
1315:meth:`__init__` method that can be called with no arguments, else it can be
1316pickled but possibly not unpickled again. This is a technical requirement that
1317may be relaxed in the future.
1318
1319A concrete subclass of :class:`tzinfo` may need to implement the following
1320methods. Exactly which methods are needed depends on the uses made of aware
1321:mod:`datetime` objects. If in doubt, simply implement all of them.
1322
1323
1324.. method:: tzinfo.utcoffset(self, dt)
1325
1326 Return offset of local time from UTC, in minutes east of UTC. If local time is
1327 west of UTC, this should be negative. Note that this is intended to be the
1328 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1329 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1330 the UTC offset isn't known, return ``None``. Else the value returned must be a
1331 :class:`timedelta` object specifying a whole number of minutes in the range
1332 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1333 than one day). Most implementations of :meth:`utcoffset` will probably look
1334 like one of these two::
1335
1336 return CONSTANT # fixed-offset class
1337 return CONSTANT + self.dst(dt) # daylight-aware class
1338
1339 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1340 ``None`` either.
1341
1342 The default implementation of :meth:`utcoffset` raises
1343 :exc:`NotImplementedError`.
1344
1345
1346.. method:: tzinfo.dst(self, dt)
1347
1348 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1349 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1350 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1351 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1352 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1353 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1354 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
1355 member's :meth:`dst` method to determine how the :attr:`tm_isdst` flag should be
1356 set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for DST changes
1357 when crossing time zones.
1358
1359 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1360 daylight times must be consistent in this sense:
1361
1362 ``tz.utcoffset(dt) - tz.dst(dt)``
1363
1364 must return the same result for every :class:`datetime` *dt* with ``dt.tzinfo ==
1365 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1366 zone's "standard offset", which should not depend on the date or the time, but
1367 only on geographic location. The implementation of :meth:`datetime.astimezone`
1368 relies on this, but cannot detect violations; it's the programmer's
1369 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1370 this, it may be able to override the default implementation of
1371 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1372
1373 Most implementations of :meth:`dst` will probably look like one of these two::
1374
1375 def dst(self):
1376 # a fixed-offset class: doesn't account for DST
1377 return timedelta(0)
1378
1379 or ::
1380
1381 def dst(self):
1382 # Code to set dston and dstoff to the time zone's DST
1383 # transition times based on the input dt.year, and expressed
1384 # in standard local time. Then
1385
1386 if dston <= dt.replace(tzinfo=None) < dstoff:
1387 return timedelta(hours=1)
1388 else:
1389 return timedelta(0)
1390
1391 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1392
1393
1394.. method:: tzinfo.tzname(self, dt)
1395
1396 Return the time zone name corresponding to the :class:`datetime` object *dt*, as
1397 a string. Nothing about string names is defined by the :mod:`datetime` module,
1398 and there's no requirement that it mean anything in particular. For example,
1399 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1400 valid replies. Return ``None`` if a string name isn't known. Note that this is
1401 a method rather than a fixed string primarily because some :class:`tzinfo`
1402 subclasses will wish to return different names depending on the specific value
1403 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1404 daylight time.
1405
1406 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1407
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001408
Georg Brandl116aa622007-08-15 14:28:22 +00001409These methods are called by a :class:`datetime` or :class:`time` object, in
1410response to their methods of the same names. A :class:`datetime` object passes
1411itself as the argument, and a :class:`time` object passes ``None`` as the
1412argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
1413accept a *dt* argument of ``None``, or of class :class:`datetime`.
1414
1415When ``None`` is passed, it's up to the class designer to decide the best
1416response. For example, returning ``None`` is appropriate if the class wishes to
1417say that time objects don't participate in the :class:`tzinfo` protocols. It
1418may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1419there is no other convention for discovering the standard offset.
1420
1421When a :class:`datetime` object is passed in response to a :class:`datetime`
1422method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1423rely on this, unless user code calls :class:`tzinfo` methods directly. The
1424intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1425time, and not need worry about objects in other timezones.
1426
1427There is one more :class:`tzinfo` method that a subclass may wish to override:
1428
1429
1430.. method:: tzinfo.fromutc(self, dt)
1431
1432 This is called from the default :class:`datetime.astimezone()` implementation.
1433 When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members
1434 are to be viewed as expressing a UTC time. The purpose of :meth:`fromutc` is to
1435 adjust the date and time members, returning an equivalent datetime in *self*'s
1436 local time.
1437
1438 Most :class:`tzinfo` subclasses should be able to inherit the default
1439 :meth:`fromutc` implementation without problems. It's strong enough to handle
1440 fixed-offset time zones, and time zones accounting for both standard and
1441 daylight time, and the latter even if the DST transition times differ in
1442 different years. An example of a time zone the default :meth:`fromutc`
1443 implementation may not handle correctly in all cases is one where the standard
1444 offset (from UTC) depends on the specific date and time passed, which can happen
1445 for political reasons. The default implementations of :meth:`astimezone` and
1446 :meth:`fromutc` may not produce the result you want if the result is one of the
1447 hours straddling the moment the standard offset changes.
1448
1449 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1450 like::
1451
1452 def fromutc(self, dt):
1453 # raise ValueError error if dt.tzinfo is not self
1454 dtoff = dt.utcoffset()
1455 dtdst = dt.dst()
1456 # raise ValueError if dtoff is None or dtdst is None
1457 delta = dtoff - dtdst # this is self's standard offset
1458 if delta:
1459 dt += delta # convert to standard local time
1460 dtdst = dt.dst()
1461 # raise ValueError if dtdst is None
1462 if dtdst:
1463 return dt + dtdst
1464 else:
1465 return dt
1466
1467Example :class:`tzinfo` classes:
1468
1469.. literalinclude:: ../includes/tzinfo-examples.py
1470
1471
1472Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1473subclass accounting for both standard and daylight time, at the DST transition
1474points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00001475minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
14761:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001477
1478 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1479 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1480 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1481
1482 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1483
1484 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1485
1486When DST starts (the "start" line), the local wall clock leaps from 1:59 to
14873:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1488``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1489begins. In order for :meth:`astimezone` to make this guarantee, the
1490:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1491Eastern) to be in daylight time.
1492
1493When DST ends (the "end" line), there's a potentially worse problem: there's an
1494hour that can't be spelled unambiguously in local wall time: the last hour of
1495daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1496daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1497to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1498:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1499hours into the same local hour then. In the Eastern example, UTC times of the
1500form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1501:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1502consider times in the "repeated hour" to be in standard time. This is easily
1503arranged, as in the example, by expressing DST switch times in the time zone's
1504standard local time.
1505
1506Applications that can't bear such ambiguities should avoid using hybrid
1507:class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any
1508other fixed-offset :class:`tzinfo` subclass (such as a class representing only
1509EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
Georg Brandl48310cd2009-01-03 21:18:54 +00001510
Georg Brandl116aa622007-08-15 14:28:22 +00001511
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001512.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00001513
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001514:meth:`strftime` and :meth:`strptime` Behavior
1515----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001516
1517:class:`date`, :class:`datetime`, and :class:`time` objects all support a
1518``strftime(format)`` method, to create a string representing the time under the
1519control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1520acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1521although not all objects support a :meth:`timetuple` method.
1522
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001523Conversely, the :meth:`datetime.strptime` class method creates a
1524:class:`datetime` object from a string representing a date and time and a
1525corresponding format string. ``datetime.strptime(date_string, format)`` is
1526equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1527
Georg Brandl116aa622007-08-15 14:28:22 +00001528For :class:`time` objects, the format codes for year, month, and day should not
1529be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001530is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00001531
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001532For :class:`date` objects, the format codes for hours, minutes, seconds, and
1533microseconds should not be used, as :class:`date` objects have no such
1534values. If they're used anyway, ``0`` is substituted for them.
1535
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001536For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1537strings.
1538
1539For an aware object:
1540
1541``%z``
1542 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1543 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1544 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1545 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1546 replaced with the string ``'-0330'``.
1547
1548``%Z``
1549 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1550 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl116aa622007-08-15 14:28:22 +00001551
Georg Brandl116aa622007-08-15 14:28:22 +00001552The full set of format codes supported varies across platforms, because Python
1553calls the platform C library's :func:`strftime` function, and platform
Georg Brandl48310cd2009-01-03 21:18:54 +00001554variations are common.
Christian Heimes895627f2007-12-08 17:28:33 +00001555
1556The following is a list of all the format codes that the C standard (1989
1557version) requires, and these work on all platforms with a standard C
1558implementation. Note that the 1999 version of the C standard added additional
1559format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001560
1561The exact range of years for which :meth:`strftime` works also varies across
1562platforms. Regardless of platform, years before 1900 cannot be used.
1563
Christian Heimes895627f2007-12-08 17:28:33 +00001564+-----------+--------------------------------+-------+
1565| Directive | Meaning | Notes |
1566+===========+================================+=======+
1567| ``%a`` | Locale's abbreviated weekday | |
1568| | name. | |
1569+-----------+--------------------------------+-------+
1570| ``%A`` | Locale's full weekday name. | |
1571+-----------+--------------------------------+-------+
1572| ``%b`` | Locale's abbreviated month | |
1573| | name. | |
1574+-----------+--------------------------------+-------+
1575| ``%B`` | Locale's full month name. | |
1576+-----------+--------------------------------+-------+
1577| ``%c`` | Locale's appropriate date and | |
1578| | time representation. | |
1579+-----------+--------------------------------+-------+
1580| ``%d`` | Day of the month as a decimal | |
1581| | number [01,31]. | |
1582+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001583| ``%f`` | Microsecond as a decimal | \(1) |
1584| | number [0,999999], zero-padded | |
1585| | on the left | |
1586+-----------+--------------------------------+-------+
Christian Heimes895627f2007-12-08 17:28:33 +00001587| ``%H`` | Hour (24-hour clock) as a | |
1588| | decimal number [00,23]. | |
1589+-----------+--------------------------------+-------+
1590| ``%I`` | Hour (12-hour clock) as a | |
1591| | decimal number [01,12]. | |
1592+-----------+--------------------------------+-------+
1593| ``%j`` | Day of the year as a decimal | |
1594| | number [001,366]. | |
1595+-----------+--------------------------------+-------+
1596| ``%m`` | Month as a decimal number | |
1597| | [01,12]. | |
1598+-----------+--------------------------------+-------+
1599| ``%M`` | Minute as a decimal number | |
1600| | [00,59]. | |
1601+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001602| ``%p`` | Locale's equivalent of either | \(2) |
Christian Heimes895627f2007-12-08 17:28:33 +00001603| | AM or PM. | |
1604+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001605| ``%S`` | Second as a decimal number | \(3) |
Christian Heimes895627f2007-12-08 17:28:33 +00001606| | [00,61]. | |
1607+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001608| ``%U`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001609| | (Sunday as the first day of | |
1610| | the week) as a decimal number | |
1611| | [00,53]. All days in a new | |
1612| | year preceding the first | |
1613| | Sunday are considered to be in | |
1614| | week 0. | |
1615+-----------+--------------------------------+-------+
1616| ``%w`` | Weekday as a decimal number | |
1617| | [0(Sunday),6]. | |
1618+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001619| ``%W`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001620| | (Monday as the first day of | |
1621| | the week) as a decimal number | |
1622| | [00,53]. All days in a new | |
1623| | year preceding the first | |
1624| | Monday are considered to be in | |
1625| | week 0. | |
1626+-----------+--------------------------------+-------+
1627| ``%x`` | Locale's appropriate date | |
1628| | representation. | |
1629+-----------+--------------------------------+-------+
1630| ``%X`` | Locale's appropriate time | |
1631| | representation. | |
1632+-----------+--------------------------------+-------+
1633| ``%y`` | Year without century as a | |
1634| | decimal number [00,99]. | |
1635+-----------+--------------------------------+-------+
1636| ``%Y`` | Year with century as a decimal | |
1637| | number. | |
1638+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001639| ``%z`` | UTC offset in the form +HHMM | \(5) |
Christian Heimes895627f2007-12-08 17:28:33 +00001640| | or -HHMM (empty string if the | |
1641| | the object is naive). | |
1642+-----------+--------------------------------+-------+
1643| ``%Z`` | Time zone name (empty string | |
1644| | if the object is naive). | |
1645+-----------+--------------------------------+-------+
1646| ``%%`` | A literal ``'%'`` character. | |
1647+-----------+--------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001648
Christian Heimes895627f2007-12-08 17:28:33 +00001649Notes:
1650
1651(1)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001652 When used with the :meth:`strptime` method, the ``%f`` directive
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001653 accepts from one to six digits and zero pads on the right. ``%f`` is
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001654 an extension to the set of format characters in the C standard (but
1655 implemented separately in datetime objects, and therefore always
1656 available).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001657
1658(2)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001659 When used with the :meth:`strptime` method, the ``%p`` directive only affects
Christian Heimes895627f2007-12-08 17:28:33 +00001660 the output hour field if the ``%I`` directive is used to parse the hour.
1661
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001662(3)
R. David Murraybd25d332009-04-02 04:50:03 +00001663 The range really is ``0`` to ``61``; according to the Posix standard this
1664 accounts for leap seconds and the (very rare) double leap seconds.
1665 The :mod:`time` module may produce and does accept leap seconds since
1666 it is based on the Posix standard, but the :mod:`datetime` module
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001667 does not accept leap seconds in :meth:`strptime` input nor will it
R. David Murraybd25d332009-04-02 04:50:03 +00001668 produce them in :func:`strftime` output.
Christian Heimes895627f2007-12-08 17:28:33 +00001669
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001670(4)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001671 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in
Christian Heimes895627f2007-12-08 17:28:33 +00001672 calculations when the day of the week and the year are specified.
1673
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001674(5)
Christian Heimes895627f2007-12-08 17:28:33 +00001675 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1676 ``%z`` is replaced with the string ``'-0330'``.