blob: 2498361c03dbbd99dd719976b1f54d87c1db35c5 [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+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000223| ``t1 = t2 * f or t1 = f * t2`` | Delta multiplied by a float. The result is |
224| | rounded to the nearest multiple of |
225| | timedelta.resolution using round-half-to-even.|
226+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000227| ``f = t2 / t3`` | Division (3) of *t2* by *t3*. Returns a |
228| | :class:`float` object. |
229+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000230| ``t1 = t2 / f or t1 = t2 / i`` | Delta divided by a float or an int. The result|
231| | is rounded to the nearest multiple of |
232| | timedelta.resolution using round-half-to-even.|
233+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000234| ``t1 = t2 // i`` or | The floor is computed and the remainder (if |
235| ``t1 = t2 // t3`` | any) is thrown away. In the second case, an |
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000236| | integer is returned. (3) |
Mark Dickinson7c186e22010-04-20 22:32:49 +0000237+--------------------------------+-----------------------------------------------+
238| ``t1 = t2 % t3`` | The remainder is computed as a |
239| | :class:`timedelta` object. (3) |
240+--------------------------------+-----------------------------------------------+
241| ``q, r = divmod(t1, t2)`` | Computes the quotient and the remainder: |
242| | ``q = t1 // t2`` (3) and ``r = t1 % t2``. |
243| | q is an integer and r is a :class:`timedelta` |
244| | object. |
Georg Brandl116aa622007-08-15 14:28:22 +0000245+--------------------------------+-----------------------------------------------+
246| ``+t1`` | Returns a :class:`timedelta` object with the |
247| | same value. (2) |
248+--------------------------------+-----------------------------------------------+
249| ``-t1`` | equivalent to :class:`timedelta`\ |
250| | (-*t1.days*, -*t1.seconds*, |
251| | -*t1.microseconds*), and to *t1*\* -1. (1)(4) |
252+--------------------------------+-----------------------------------------------+
Georg Brandl495f7b52009-10-27 15:28:25 +0000253| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, and|
Georg Brandl116aa622007-08-15 14:28:22 +0000254| | to -*t* when ``t.days < 0``. (2) |
255+--------------------------------+-----------------------------------------------+
256
257Notes:
258
259(1)
260 This is exact, but may overflow.
261
262(2)
263 This is exact, and cannot overflow.
264
265(3)
266 Division by 0 raises :exc:`ZeroDivisionError`.
267
268(4)
269 -*timedelta.max* is not representable as a :class:`timedelta` object.
270
271In addition to the operations listed above :class:`timedelta` objects support
272certain additions and subtractions with :class:`date` and :class:`datetime`
273objects (see below).
274
Mark Dickinson7c186e22010-04-20 22:32:49 +0000275.. versionadded:: 3.2
276 Floor division and true division of a :class:`timedelta` object by
277 another :class:`timedelta` object are now supported, as are
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000278 remainder operations and the :func:`divmod` function. True
279 division and multiplication of a :class:`timedelta` object by
280 a :class:`float` object are now supported.
Mark Dickinson7c186e22010-04-20 22:32:49 +0000281
282
Georg Brandl116aa622007-08-15 14:28:22 +0000283Comparisons of :class:`timedelta` objects are supported with the
284:class:`timedelta` object representing the smaller duration considered to be the
285smaller timedelta. In order to stop mixed-type comparisons from falling back to
286the default comparison by object address, when a :class:`timedelta` object is
287compared to an object of a different type, :exc:`TypeError` is raised unless the
288comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
289:const:`True`, respectively.
290
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000291:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl116aa622007-08-15 14:28:22 +0000292efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
293considered to be true if and only if it isn't equal to ``timedelta(0)``.
294
Antoine Pitroube6859d2009-11-25 23:02:32 +0000295Instance methods:
296
297.. method:: timedelta.total_seconds()
298
299 Return the total number of seconds contained in the duration. Equivalent to
Mark Dickinson0381e3f2010-05-08 14:35:02 +0000300 ``td / timedelta(seconds=1)``.
301
302 Note that for very large time intervals (greater than 270 years on
303 most platforms) this method will lose microsecond accuracy.
Antoine Pitroube6859d2009-11-25 23:02:32 +0000304
305 .. versionadded:: 3.2
306
307
Christian Heimesfe337bf2008-03-23 21:54:12 +0000308Example usage:
Georg Brandl48310cd2009-01-03 21:18:54 +0000309
Christian Heimes895627f2007-12-08 17:28:33 +0000310 >>> from datetime import timedelta
311 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000312 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Christian Heimes895627f2007-12-08 17:28:33 +0000313 ... minutes=50, seconds=600) # adds up to 365 days
Antoine Pitroube6859d2009-11-25 23:02:32 +0000314 >>> year.total_seconds()
315 31536000.0
Christian Heimes895627f2007-12-08 17:28:33 +0000316 >>> year == another_year
317 True
318 >>> ten_years = 10 * year
319 >>> ten_years, ten_years.days // 365
320 (datetime.timedelta(3650), 10)
321 >>> nine_years = ten_years - year
322 >>> nine_years, nine_years.days // 365
323 (datetime.timedelta(3285), 9)
324 >>> three_years = nine_years // 3;
325 >>> three_years, three_years.days // 365
326 (datetime.timedelta(1095), 3)
327 >>> abs(three_years - ten_years) == 2 * three_years + year
328 True
329
Georg Brandl116aa622007-08-15 14:28:22 +0000330
331.. _datetime-date:
332
333:class:`date` Objects
334---------------------
335
336A :class:`date` object represents a date (year, month and day) in an idealized
337calendar, the current Gregorian calendar indefinitely extended in both
338directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
339called day number 2, and so on. This matches the definition of the "proleptic
340Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
341where it's the base calendar for all computations. See the book for algorithms
342for converting between proleptic Gregorian ordinals and many other calendar
343systems.
344
345
346.. class:: date(year, month, day)
347
Georg Brandl5c106642007-11-29 17:41:05 +0000348 All arguments are required. Arguments may be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000349 ranges:
350
351 * ``MINYEAR <= year <= MAXYEAR``
352 * ``1 <= month <= 12``
353 * ``1 <= day <= number of days in the given month and year``
354
355 If an argument outside those ranges is given, :exc:`ValueError` is raised.
356
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000357
Georg Brandl116aa622007-08-15 14:28:22 +0000358Other constructors, all class methods:
359
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000360.. classmethod:: date.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000361
362 Return the current local date. This is equivalent to
363 ``date.fromtimestamp(time.time())``.
364
365
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000366.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000367
368 Return the local date corresponding to the POSIX timestamp, such as is returned
369 by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out
370 of the range of values supported by the platform C :cfunc:`localtime` function.
371 It's common for this to be restricted to years from 1970 through 2038. Note
372 that on non-POSIX systems that include leap seconds in their notion of a
373 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
374
375
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000376.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000377
378 Return the date corresponding to the proleptic Gregorian ordinal, where January
379 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
380 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
381 d``.
382
Georg Brandl116aa622007-08-15 14:28:22 +0000383
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000384Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000385
386.. attribute:: date.min
387
388 The earliest representable date, ``date(MINYEAR, 1, 1)``.
389
390
391.. attribute:: date.max
392
393 The latest representable date, ``date(MAXYEAR, 12, 31)``.
394
395
396.. attribute:: date.resolution
397
398 The smallest possible difference between non-equal date objects,
399 ``timedelta(days=1)``.
400
Georg Brandl116aa622007-08-15 14:28:22 +0000401
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000402Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000403
404.. attribute:: date.year
405
406 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
407
408
409.. attribute:: date.month
410
411 Between 1 and 12 inclusive.
412
413
414.. attribute:: date.day
415
416 Between 1 and the number of days in the given month of the given year.
417
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000418
Georg Brandl116aa622007-08-15 14:28:22 +0000419Supported operations:
420
421+-------------------------------+----------------------------------------------+
422| Operation | Result |
423+===============================+==============================================+
424| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
425| | from *date1*. (1) |
426+-------------------------------+----------------------------------------------+
427| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
428| | timedelta == date1``. (2) |
429+-------------------------------+----------------------------------------------+
430| ``timedelta = date1 - date2`` | \(3) |
431+-------------------------------+----------------------------------------------+
432| ``date1 < date2`` | *date1* is considered less than *date2* when |
433| | *date1* precedes *date2* in time. (4) |
434+-------------------------------+----------------------------------------------+
435
436Notes:
437
438(1)
439 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
440 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
441 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
442 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
443 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
444
445(2)
446 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
447 isolation can overflow in cases where date1 - timedelta does not.
448 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
449
450(3)
451 This is exact, and cannot overflow. timedelta.seconds and
452 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
453
454(4)
455 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
456 date2.toordinal()``. In order to stop comparison from falling back to the
457 default scheme of comparing object addresses, date comparison normally raises
458 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
459 However, ``NotImplemented`` is returned instead if the other comparand has a
460 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
461 chance at implementing mixed-type comparison. If not, when a :class:`date`
462 object is compared to an object of a different type, :exc:`TypeError` is raised
463 unless the comparison is ``==`` or ``!=``. The latter cases return
464 :const:`False` or :const:`True`, respectively.
465
466Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
467objects are considered to be true.
468
469Instance methods:
470
Georg Brandl116aa622007-08-15 14:28:22 +0000471.. method:: date.replace(year, month, day)
472
473 Return a date with the same value, except for those members given new values by
474 whichever keyword arguments are specified. For example, if ``d == date(2002,
475 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
476
477
478.. method:: date.timetuple()
479
480 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
481 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
482 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000483 d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1,
484 1).toordinal() + 1`` is the day number within the current year starting with
485 ``1`` for January 1st.
Georg Brandl116aa622007-08-15 14:28:22 +0000486
487
488.. method:: date.toordinal()
489
490 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
491 has ordinal 1. For any :class:`date` object *d*,
492 ``date.fromordinal(d.toordinal()) == d``.
493
494
495.. method:: date.weekday()
496
497 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
498 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
499 :meth:`isoweekday`.
500
501
502.. method:: date.isoweekday()
503
504 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
505 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
506 :meth:`weekday`, :meth:`isocalendar`.
507
508
509.. method:: date.isocalendar()
510
511 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
512
513 The ISO calendar is a widely used variant of the Gregorian calendar. See
Mark Dickinsonf964ac22009-11-03 16:29:10 +0000514 http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
515 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000516
517 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
518 Monday and ends on a Sunday. The first week of an ISO year is the first
519 (Gregorian) calendar week of a year containing a Thursday. This is called week
520 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
521
522 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
523 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
524 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
525 4).isocalendar() == (2004, 1, 7)``.
526
527
528.. method:: date.isoformat()
529
530 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
531 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
532
533
534.. method:: date.__str__()
535
536 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
537
538
539.. method:: date.ctime()
540
541 Return a string representing the date, for example ``date(2002, 12,
542 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
543 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
544 :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
545 :meth:`date.ctime` does not invoke) conforms to the C standard.
546
547
548.. method:: date.strftime(format)
549
550 Return a string representing the date, controlled by an explicit format string.
551 Format codes referring to hours, minutes or seconds will see 0 values. See
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000552 section :ref:`strftime-strptime-behavior`.
553
Georg Brandl116aa622007-08-15 14:28:22 +0000554
Christian Heimes895627f2007-12-08 17:28:33 +0000555Example of counting days to an event::
556
557 >>> import time
558 >>> from datetime import date
559 >>> today = date.today()
560 >>> today
561 datetime.date(2007, 12, 5)
562 >>> today == date.fromtimestamp(time.time())
563 True
564 >>> my_birthday = date(today.year, 6, 24)
565 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000566 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000567 >>> my_birthday
568 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000569 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000570 >>> time_to_birthday.days
571 202
572
Christian Heimesfe337bf2008-03-23 21:54:12 +0000573Example of working with :class:`date`:
574
575.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000576
577 >>> from datetime import date
578 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
579 >>> d
580 datetime.date(2002, 3, 11)
581 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000582 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000583 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000584 2002 # year
585 3 # month
586 11 # day
587 0
588 0
589 0
590 0 # weekday (0 = Monday)
591 70 # 70th day in the year
592 -1
593 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000594 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000595 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000596 2002 # ISO year
597 11 # ISO week number
598 1 # ISO day number ( 1 = Monday )
599 >>> d.isoformat()
600 '2002-03-11'
601 >>> d.strftime("%d/%m/%y")
602 '11/03/02'
603 >>> d.strftime("%A %d. %B %Y")
604 'Monday 11. March 2002'
605
Georg Brandl116aa622007-08-15 14:28:22 +0000606
607.. _datetime-datetime:
608
609:class:`datetime` Objects
610-------------------------
611
612A :class:`datetime` object is a single object containing all the information
613from a :class:`date` object and a :class:`time` object. Like a :class:`date`
614object, :class:`datetime` assumes the current Gregorian calendar extended in
615both directions; like a time object, :class:`datetime` assumes there are exactly
6163600\*24 seconds in every day.
617
618Constructor:
619
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000620.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000621
622 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000623 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
624 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000625
626 * ``MINYEAR <= year <= MAXYEAR``
627 * ``1 <= month <= 12``
628 * ``1 <= day <= number of days in the given month and year``
629 * ``0 <= hour < 24``
630 * ``0 <= minute < 60``
631 * ``0 <= second < 60``
632 * ``0 <= microsecond < 1000000``
633
634 If an argument outside those ranges is given, :exc:`ValueError` is raised.
635
636Other constructors, all class methods:
637
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000638.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000639
640 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
641 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
642 :meth:`fromtimestamp`.
643
644
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000645.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000646
647 Return the current local date and time. If optional argument *tz* is ``None``
648 or not specified, this is like :meth:`today`, but, if possible, supplies more
649 precision than can be gotten from going through a :func:`time.time` timestamp
650 (for example, this may be possible on platforms supplying the C
651 :cfunc:`gettimeofday` function).
652
653 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
654 current date and time are converted to *tz*'s time zone. In this case the
655 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
656 See also :meth:`today`, :meth:`utcnow`.
657
658
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000659.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000660
661 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
662 :meth:`now`, but returns the current UTC date and time, as a naive
663 :class:`datetime` object. See also :meth:`now`.
664
665
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000666.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000667
668 Return the local date and time corresponding to the POSIX timestamp, such as is
669 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
670 specified, the timestamp is converted to the platform's local date and time, and
671 the returned :class:`datetime` object is naive.
672
673 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
674 timestamp is converted to *tz*'s time zone. In this case the result is
675 equivalent to
676 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
677
678 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
679 the range of values supported by the platform C :cfunc:`localtime` or
680 :cfunc:`gmtime` functions. It's common for this to be restricted to years in
681 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
682 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
683 and then it's possible to have two timestamps differing by a second that yield
684 identical :class:`datetime` objects. See also :meth:`utcfromtimestamp`.
685
686
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000687.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000688
689 Return the UTC :class:`datetime` corresponding to the POSIX timestamp, with
690 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
691 out of the range of values supported by the platform C :cfunc:`gmtime` function.
692 It's common for this to be restricted to years in 1970 through 2038. See also
693 :meth:`fromtimestamp`.
694
695
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000696.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000697
698 Return the :class:`datetime` corresponding to the proleptic Gregorian ordinal,
699 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
700 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
701 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
702
703
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000704.. classmethod:: datetime.combine(date, time)
Georg Brandl116aa622007-08-15 14:28:22 +0000705
706 Return a new :class:`datetime` object whose date members are equal to the given
707 :class:`date` object's, and whose time and :attr:`tzinfo` members are equal to
708 the given :class:`time` object's. For any :class:`datetime` object *d*, ``d ==
709 datetime.combine(d.date(), d.timetz())``. If date is a :class:`datetime`
710 object, its time and :attr:`tzinfo` members are ignored.
711
712
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000713.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000714
715 Return a :class:`datetime` corresponding to *date_string*, parsed according to
716 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
717 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
718 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 +0000719 time tuple. See section :ref:`strftime-strptime-behavior`.
720
Georg Brandl116aa622007-08-15 14:28:22 +0000721
Georg Brandl116aa622007-08-15 14:28:22 +0000722
723Class attributes:
724
Georg Brandl116aa622007-08-15 14:28:22 +0000725.. attribute:: datetime.min
726
727 The earliest representable :class:`datetime`, ``datetime(MINYEAR, 1, 1,
728 tzinfo=None)``.
729
730
731.. attribute:: datetime.max
732
733 The latest representable :class:`datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
734 59, 999999, tzinfo=None)``.
735
736
737.. attribute:: datetime.resolution
738
739 The smallest possible difference between non-equal :class:`datetime` objects,
740 ``timedelta(microseconds=1)``.
741
Georg Brandl116aa622007-08-15 14:28:22 +0000742
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000743Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000744
745.. attribute:: datetime.year
746
747 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
748
749
750.. attribute:: datetime.month
751
752 Between 1 and 12 inclusive.
753
754
755.. attribute:: datetime.day
756
757 Between 1 and the number of days in the given month of the given year.
758
759
760.. attribute:: datetime.hour
761
762 In ``range(24)``.
763
764
765.. attribute:: datetime.minute
766
767 In ``range(60)``.
768
769
770.. attribute:: datetime.second
771
772 In ``range(60)``.
773
774
775.. attribute:: datetime.microsecond
776
777 In ``range(1000000)``.
778
779
780.. attribute:: datetime.tzinfo
781
782 The object passed as the *tzinfo* argument to the :class:`datetime` constructor,
783 or ``None`` if none was passed.
784
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000785
Georg Brandl116aa622007-08-15 14:28:22 +0000786Supported operations:
787
788+---------------------------------------+-------------------------------+
789| Operation | Result |
790+=======================================+===============================+
791| ``datetime2 = datetime1 + timedelta`` | \(1) |
792+---------------------------------------+-------------------------------+
793| ``datetime2 = datetime1 - timedelta`` | \(2) |
794+---------------------------------------+-------------------------------+
795| ``timedelta = datetime1 - datetime2`` | \(3) |
796+---------------------------------------+-------------------------------+
797| ``datetime1 < datetime2`` | Compares :class:`datetime` to |
798| | :class:`datetime`. (4) |
799+---------------------------------------+-------------------------------+
800
801(1)
802 datetime2 is a duration of timedelta removed from datetime1, moving forward in
803 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
804 result has the same :attr:`tzinfo` member as the input datetime, and datetime2 -
805 datetime1 == timedelta after. :exc:`OverflowError` is raised if datetime2.year
806 would be smaller than :const:`MINYEAR` or larger than :const:`MAXYEAR`. Note
807 that no time zone adjustments are done even if the input is an aware object.
808
809(2)
810 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
811 addition, the result has the same :attr:`tzinfo` member as the input datetime,
812 and no time zone adjustments are done even if the input is aware. This isn't
813 quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation
814 can overflow in cases where datetime1 - timedelta does not.
815
816(3)
817 Subtraction of a :class:`datetime` from a :class:`datetime` is defined only if
818 both operands are naive, or if both are aware. If one is aware and the other is
819 naive, :exc:`TypeError` is raised.
820
821 If both are naive, or both are aware and have the same :attr:`tzinfo` member,
822 the :attr:`tzinfo` members are ignored, and the result is a :class:`timedelta`
823 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
824 are done in this case.
825
826 If both are aware and have different :attr:`tzinfo` members, ``a-b`` acts as if
827 *a* and *b* were first converted to naive UTC datetimes first. The result is
828 ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) -
829 b.utcoffset())`` except that the implementation never overflows.
830
831(4)
832 *datetime1* is considered less than *datetime2* when *datetime1* precedes
833 *datetime2* in time.
834
835 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
836 If both comparands are aware, and have the same :attr:`tzinfo` member, the
837 common :attr:`tzinfo` member is ignored and the base datetimes are compared. If
838 both comparands are aware and have different :attr:`tzinfo` members, the
839 comparands are first adjusted by subtracting their UTC offsets (obtained from
840 ``self.utcoffset()``).
841
842 .. note::
843
844 In order to stop comparison from falling back to the default scheme of comparing
845 object addresses, datetime comparison normally raises :exc:`TypeError` if the
846 other comparand isn't also a :class:`datetime` object. However,
847 ``NotImplemented`` is returned instead if the other comparand has a
848 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
849 chance at implementing mixed-type comparison. If not, when a :class:`datetime`
850 object is compared to an object of a different type, :exc:`TypeError` is raised
851 unless the comparison is ``==`` or ``!=``. The latter cases return
852 :const:`False` or :const:`True`, respectively.
853
854:class:`datetime` objects can be used as dictionary keys. In Boolean contexts,
855all :class:`datetime` objects are considered to be true.
856
857Instance methods:
858
Georg Brandl116aa622007-08-15 14:28:22 +0000859.. method:: datetime.date()
860
861 Return :class:`date` object with same year, month and day.
862
863
864.. method:: datetime.time()
865
866 Return :class:`time` object with same hour, minute, second and microsecond.
867 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
868
869
870.. method:: datetime.timetz()
871
872 Return :class:`time` object with same hour, minute, second, microsecond, and
873 tzinfo members. See also method :meth:`time`.
874
875
876.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
877
878 Return a datetime with the same members, except for those members given new
879 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
880 can be specified to create a naive datetime from an aware datetime with no
881 conversion of date and time members.
882
883
884.. method:: datetime.astimezone(tz)
885
886 Return a :class:`datetime` object with new :attr:`tzinfo` member *tz*, adjusting
887 the date and time members so the result is the same UTC time as *self*, but in
888 *tz*'s local time.
889
890 *tz* must be an instance of a :class:`tzinfo` subclass, and its
891 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
892 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
893 not return ``None``).
894
895 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
896 adjustment of date or time members is performed. Else the result is local time
897 in time zone *tz*, representing the same UTC time as *self*: after ``astz =
898 dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have the same date
899 and time members as ``dt - dt.utcoffset()``. The discussion of class
900 :class:`tzinfo` explains the cases at Daylight Saving Time transition boundaries
901 where this cannot be achieved (an issue only if *tz* models both standard and
902 daylight time).
903
904 If you merely want to attach a time zone object *tz* to a datetime *dt* without
905 adjustment of date and time members, use ``dt.replace(tzinfo=tz)``. If you
906 merely want to remove the time zone object from an aware datetime *dt* without
907 conversion of date and time members, use ``dt.replace(tzinfo=None)``.
908
909 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
910 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
911 Ignoring error cases, :meth:`astimezone` acts like::
912
913 def astimezone(self, tz):
914 if self.tzinfo is tz:
915 return self
916 # Convert self to UTC, and attach the new time zone object.
917 utc = (self - self.utcoffset()).replace(tzinfo=tz)
918 # Convert from UTC to tz's local time.
919 return tz.fromutc(utc)
920
921
922.. method:: datetime.utcoffset()
923
924 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
925 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
926 return ``None``, or a :class:`timedelta` object representing a whole number of
927 minutes with magnitude less than one day.
928
929
930.. method:: datetime.dst()
931
932 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
933 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
934 ``None``, or a :class:`timedelta` object representing a whole number of minutes
935 with magnitude less than one day.
936
937
938.. method:: datetime.tzname()
939
940 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
941 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
942 ``None`` or a string object,
943
944
945.. method:: datetime.timetuple()
946
947 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
948 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000949 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
950 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
951 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
952 of the result is set according to the :meth:`dst` method: :attr:`tzinfo` is
953 ``None`` or :meth:`dst`` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
954 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
955 else ``tm_isdst`` is set to ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +0000956
957
958.. method:: datetime.utctimetuple()
959
960 If :class:`datetime` instance *d* is naive, this is the same as
961 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
962 ``d.dst()`` returns. DST is never in effect for a UTC time.
963
964 If *d* is aware, *d* is normalized to UTC time, by subtracting
965 ``d.utcoffset()``, and a :class:`time.struct_time` for the normalized time is
966 returned. :attr:`tm_isdst` is forced to 0. Note that the result's
967 :attr:`tm_year` member may be :const:`MINYEAR`\ -1 or :const:`MAXYEAR`\ +1, if
968 *d*.year was ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
969 boundary.
970
971
972.. method:: datetime.toordinal()
973
974 Return the proleptic Gregorian ordinal of the date. The same as
975 ``self.date().toordinal()``.
976
977
978.. method:: datetime.weekday()
979
980 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
981 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
982
983
984.. method:: datetime.isoweekday()
985
986 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
987 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
988 :meth:`isocalendar`.
989
990
991.. method:: datetime.isocalendar()
992
993 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
994 ``self.date().isocalendar()``.
995
996
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000997.. method:: datetime.isoformat(sep='T')
Georg Brandl116aa622007-08-15 14:28:22 +0000998
999 Return a string representing the date and time in ISO 8601 format,
1000 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
1001 YYYY-MM-DDTHH:MM:SS
1002
1003 If :meth:`utcoffset` does not return ``None``, a 6-character string is
1004 appended, giving the UTC offset in (signed) hours and minutes:
1005 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
1006 YYYY-MM-DDTHH:MM:SS+HH:MM
1007
1008 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +00001009 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +00001010
1011 >>> from datetime import tzinfo, timedelta, datetime
1012 >>> class TZ(tzinfo):
1013 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1014 ...
1015 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1016 '2002-12-25 00:00:00-06:39'
1017
1018
1019.. method:: datetime.__str__()
1020
1021 For a :class:`datetime` instance *d*, ``str(d)`` is equivalent to
1022 ``d.isoformat(' ')``.
1023
1024
1025.. method:: datetime.ctime()
1026
1027 Return a string representing the date and time, for example ``datetime(2002, 12,
1028 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1029 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
1030 native C :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
1031 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1032
1033
1034.. method:: datetime.strftime(format)
1035
1036 Return a string representing the date and time, controlled by an explicit format
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001037 string. See section :ref:`strftime-strptime-behavior`.
1038
Georg Brandl116aa622007-08-15 14:28:22 +00001039
Christian Heimesfe337bf2008-03-23 21:54:12 +00001040Examples of working with datetime objects:
1041
1042.. doctest::
1043
Christian Heimes895627f2007-12-08 17:28:33 +00001044 >>> from datetime import datetime, date, time
1045 >>> # Using datetime.combine()
1046 >>> d = date(2005, 7, 14)
1047 >>> t = time(12, 30)
1048 >>> datetime.combine(d, t)
1049 datetime.datetime(2005, 7, 14, 12, 30)
1050 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001051 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001052 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001053 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001054 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1055 >>> # Using datetime.strptime()
1056 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1057 >>> dt
1058 datetime.datetime(2006, 11, 21, 16, 30)
1059 >>> # Using datetime.timetuple() to get tuple of all attributes
1060 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001061 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001062 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001063 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001064 2006 # year
1065 11 # month
1066 21 # day
1067 16 # hour
1068 30 # minute
1069 0 # second
1070 1 # weekday (0 = Monday)
1071 325 # number of days since 1st January
1072 -1 # dst - method tzinfo.dst() returned None
1073 >>> # Date in ISO format
1074 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001075 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001076 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001077 ...
1078 2006 # ISO year
1079 47 # ISO week
1080 2 # ISO weekday
1081 >>> # Formatting datetime
1082 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1083 'Tuesday, 21. November 2006 04:30PM'
1084
Christian Heimesfe337bf2008-03-23 21:54:12 +00001085Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001086
1087 >>> from datetime import timedelta, datetime, tzinfo
1088 >>> class GMT1(tzinfo):
1089 ... def __init__(self): # DST starts last Sunday in March
1090 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1091 ... 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)
Georg Brandl48310cd2009-01-03 21:18:54 +00001096 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001097 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1098 ... return timedelta(hours=1)
1099 ... else:
1100 ... return timedelta(0)
1101 ... def tzname(self,dt):
1102 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001103 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001104 >>> class GMT2(tzinfo):
1105 ... def __init__(self):
Georg Brandl48310cd2009-01-03 21:18:54 +00001106 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001107 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001108 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001109 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1110 ... def utcoffset(self, dt):
1111 ... return timedelta(hours=1) + self.dst(dt)
1112 ... def dst(self, dt):
1113 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1114 ... return timedelta(hours=2)
1115 ... else:
1116 ... return timedelta(0)
1117 ... def tzname(self,dt):
1118 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001119 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001120 >>> gmt1 = GMT1()
1121 >>> # Daylight Saving Time
1122 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1123 >>> dt1.dst()
1124 datetime.timedelta(0)
1125 >>> dt1.utcoffset()
1126 datetime.timedelta(0, 3600)
1127 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1128 >>> dt2.dst()
1129 datetime.timedelta(0, 3600)
1130 >>> dt2.utcoffset()
1131 datetime.timedelta(0, 7200)
1132 >>> # Convert datetime to another time zone
1133 >>> dt3 = dt2.astimezone(GMT2())
1134 >>> dt3 # doctest: +ELLIPSIS
1135 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1136 >>> dt2 # doctest: +ELLIPSIS
1137 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1138 >>> dt2.utctimetuple() == dt3.utctimetuple()
1139 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001140
Christian Heimes895627f2007-12-08 17:28:33 +00001141
Georg Brandl116aa622007-08-15 14:28:22 +00001142
1143.. _datetime-time:
1144
1145:class:`time` Objects
1146---------------------
1147
1148A time object represents a (local) time of day, independent of any particular
1149day, and subject to adjustment via a :class:`tzinfo` object.
1150
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001151.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001152
1153 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001154 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001155 following ranges:
1156
1157 * ``0 <= hour < 24``
1158 * ``0 <= minute < 60``
1159 * ``0 <= second < 60``
1160 * ``0 <= microsecond < 1000000``.
1161
1162 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1163 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1164
1165Class attributes:
1166
1167
1168.. attribute:: time.min
1169
1170 The earliest representable :class:`time`, ``time(0, 0, 0, 0)``.
1171
1172
1173.. attribute:: time.max
1174
1175 The latest representable :class:`time`, ``time(23, 59, 59, 999999)``.
1176
1177
1178.. attribute:: time.resolution
1179
1180 The smallest possible difference between non-equal :class:`time` objects,
1181 ``timedelta(microseconds=1)``, although note that arithmetic on :class:`time`
1182 objects is not supported.
1183
Georg Brandl116aa622007-08-15 14:28:22 +00001184
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001185Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001186
1187.. attribute:: time.hour
1188
1189 In ``range(24)``.
1190
1191
1192.. attribute:: time.minute
1193
1194 In ``range(60)``.
1195
1196
1197.. attribute:: time.second
1198
1199 In ``range(60)``.
1200
1201
1202.. attribute:: time.microsecond
1203
1204 In ``range(1000000)``.
1205
1206
1207.. attribute:: time.tzinfo
1208
1209 The object passed as the tzinfo argument to the :class:`time` constructor, or
1210 ``None`` if none was passed.
1211
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001212
Georg Brandl116aa622007-08-15 14:28:22 +00001213Supported operations:
1214
1215* comparison of :class:`time` to :class:`time`, where *a* is considered less
1216 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1217 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
1218 the same :attr:`tzinfo` member, the common :attr:`tzinfo` member is ignored and
1219 the base times are compared. If both comparands are aware and have different
1220 :attr:`tzinfo` members, the comparands are first adjusted by subtracting their
1221 UTC offsets (obtained from ``self.utcoffset()``). In order to stop mixed-type
1222 comparisons from falling back to the default comparison by object address, when
1223 a :class:`time` object is compared to an object of a different type,
1224 :exc:`TypeError` is raised unless the comparison is ``==`` or ``!=``. The
1225 latter cases return :const:`False` or :const:`True`, respectively.
1226
1227* hash, use as dict key
1228
1229* efficient pickling
1230
1231* in Boolean contexts, a :class:`time` object is considered to be true if and
1232 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1233 ``0`` if that's ``None``), the result is non-zero.
1234
Georg Brandl116aa622007-08-15 14:28:22 +00001235
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001236Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001237
1238.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1239
1240 Return a :class:`time` with the same value, except for those members given new
1241 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
1242 can be specified to create a naive :class:`time` from an aware :class:`time`,
1243 without conversion of the time members.
1244
1245
1246.. method:: time.isoformat()
1247
1248 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1249 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1250 6-character string is appended, giving the UTC offset in (signed) hours and
1251 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1252
1253
1254.. method:: time.__str__()
1255
1256 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1257
1258
1259.. method:: time.strftime(format)
1260
1261 Return a string representing the time, controlled by an explicit format string.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001262 See section :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001263
1264
1265.. method:: time.utcoffset()
1266
1267 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1268 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1269 return ``None`` or a :class:`timedelta` object representing a whole number of
1270 minutes with magnitude less than one day.
1271
1272
1273.. method:: time.dst()
1274
1275 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1276 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1277 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1278 with magnitude less than one day.
1279
1280
1281.. method:: time.tzname()
1282
1283 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1284 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1285 return ``None`` or a string object.
1286
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001287
Christian Heimesfe337bf2008-03-23 21:54:12 +00001288Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001289
Christian Heimes895627f2007-12-08 17:28:33 +00001290 >>> from datetime import time, tzinfo
1291 >>> class GMT1(tzinfo):
1292 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001293 ... return timedelta(hours=1)
1294 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001295 ... return timedelta(0)
1296 ... def tzname(self,dt):
1297 ... return "Europe/Prague"
1298 ...
1299 >>> t = time(12, 10, 30, tzinfo=GMT1())
1300 >>> t # doctest: +ELLIPSIS
1301 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1302 >>> gmt = GMT1()
1303 >>> t.isoformat()
1304 '12:10:30+01:00'
1305 >>> t.dst()
1306 datetime.timedelta(0)
1307 >>> t.tzname()
1308 'Europe/Prague'
1309 >>> t.strftime("%H:%M:%S %Z")
1310 '12:10:30 Europe/Prague'
1311
Georg Brandl116aa622007-08-15 14:28:22 +00001312
1313.. _datetime-tzinfo:
1314
1315:class:`tzinfo` Objects
1316-----------------------
1317
Brett Cannone1327f72009-01-29 04:10:21 +00001318:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001319instantiated directly. You need to derive a concrete subclass, and (at least)
1320supply implementations of the standard :class:`tzinfo` methods needed by the
1321:class:`datetime` methods you use. The :mod:`datetime` module does not supply
1322any concrete subclasses of :class:`tzinfo`.
1323
1324An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1325constructors for :class:`datetime` and :class:`time` objects. The latter objects
1326view their members as being in local time, and the :class:`tzinfo` object
1327supports methods revealing offset of local time from UTC, the name of the time
1328zone, and DST offset, all relative to a date or time object passed to them.
1329
1330Special requirement for pickling: A :class:`tzinfo` subclass must have an
1331:meth:`__init__` method that can be called with no arguments, else it can be
1332pickled but possibly not unpickled again. This is a technical requirement that
1333may be relaxed in the future.
1334
1335A concrete subclass of :class:`tzinfo` may need to implement the following
1336methods. Exactly which methods are needed depends on the uses made of aware
1337:mod:`datetime` objects. If in doubt, simply implement all of them.
1338
1339
1340.. method:: tzinfo.utcoffset(self, dt)
1341
1342 Return offset of local time from UTC, in minutes east of UTC. If local time is
1343 west of UTC, this should be negative. Note that this is intended to be the
1344 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1345 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1346 the UTC offset isn't known, return ``None``. Else the value returned must be a
1347 :class:`timedelta` object specifying a whole number of minutes in the range
1348 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1349 than one day). Most implementations of :meth:`utcoffset` will probably look
1350 like one of these two::
1351
1352 return CONSTANT # fixed-offset class
1353 return CONSTANT + self.dst(dt) # daylight-aware class
1354
1355 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1356 ``None`` either.
1357
1358 The default implementation of :meth:`utcoffset` raises
1359 :exc:`NotImplementedError`.
1360
1361
1362.. method:: tzinfo.dst(self, dt)
1363
1364 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1365 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1366 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1367 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1368 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1369 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1370 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
1371 member's :meth:`dst` method to determine how the :attr:`tm_isdst` flag should be
1372 set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for DST changes
1373 when crossing time zones.
1374
1375 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1376 daylight times must be consistent in this sense:
1377
1378 ``tz.utcoffset(dt) - tz.dst(dt)``
1379
1380 must return the same result for every :class:`datetime` *dt* with ``dt.tzinfo ==
1381 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1382 zone's "standard offset", which should not depend on the date or the time, but
1383 only on geographic location. The implementation of :meth:`datetime.astimezone`
1384 relies on this, but cannot detect violations; it's the programmer's
1385 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1386 this, it may be able to override the default implementation of
1387 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1388
1389 Most implementations of :meth:`dst` will probably look like one of these two::
1390
1391 def dst(self):
1392 # a fixed-offset class: doesn't account for DST
1393 return timedelta(0)
1394
1395 or ::
1396
1397 def dst(self):
1398 # Code to set dston and dstoff to the time zone's DST
1399 # transition times based on the input dt.year, and expressed
1400 # in standard local time. Then
1401
1402 if dston <= dt.replace(tzinfo=None) < dstoff:
1403 return timedelta(hours=1)
1404 else:
1405 return timedelta(0)
1406
1407 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1408
1409
1410.. method:: tzinfo.tzname(self, dt)
1411
1412 Return the time zone name corresponding to the :class:`datetime` object *dt*, as
1413 a string. Nothing about string names is defined by the :mod:`datetime` module,
1414 and there's no requirement that it mean anything in particular. For example,
1415 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1416 valid replies. Return ``None`` if a string name isn't known. Note that this is
1417 a method rather than a fixed string primarily because some :class:`tzinfo`
1418 subclasses will wish to return different names depending on the specific value
1419 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1420 daylight time.
1421
1422 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1423
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001424
Georg Brandl116aa622007-08-15 14:28:22 +00001425These methods are called by a :class:`datetime` or :class:`time` object, in
1426response to their methods of the same names. A :class:`datetime` object passes
1427itself as the argument, and a :class:`time` object passes ``None`` as the
1428argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
1429accept a *dt* argument of ``None``, or of class :class:`datetime`.
1430
1431When ``None`` is passed, it's up to the class designer to decide the best
1432response. For example, returning ``None`` is appropriate if the class wishes to
1433say that time objects don't participate in the :class:`tzinfo` protocols. It
1434may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1435there is no other convention for discovering the standard offset.
1436
1437When a :class:`datetime` object is passed in response to a :class:`datetime`
1438method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1439rely on this, unless user code calls :class:`tzinfo` methods directly. The
1440intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1441time, and not need worry about objects in other timezones.
1442
1443There is one more :class:`tzinfo` method that a subclass may wish to override:
1444
1445
1446.. method:: tzinfo.fromutc(self, dt)
1447
1448 This is called from the default :class:`datetime.astimezone()` implementation.
1449 When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members
1450 are to be viewed as expressing a UTC time. The purpose of :meth:`fromutc` is to
1451 adjust the date and time members, returning an equivalent datetime in *self*'s
1452 local time.
1453
1454 Most :class:`tzinfo` subclasses should be able to inherit the default
1455 :meth:`fromutc` implementation without problems. It's strong enough to handle
1456 fixed-offset time zones, and time zones accounting for both standard and
1457 daylight time, and the latter even if the DST transition times differ in
1458 different years. An example of a time zone the default :meth:`fromutc`
1459 implementation may not handle correctly in all cases is one where the standard
1460 offset (from UTC) depends on the specific date and time passed, which can happen
1461 for political reasons. The default implementations of :meth:`astimezone` and
1462 :meth:`fromutc` may not produce the result you want if the result is one of the
1463 hours straddling the moment the standard offset changes.
1464
1465 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1466 like::
1467
1468 def fromutc(self, dt):
1469 # raise ValueError error if dt.tzinfo is not self
1470 dtoff = dt.utcoffset()
1471 dtdst = dt.dst()
1472 # raise ValueError if dtoff is None or dtdst is None
1473 delta = dtoff - dtdst # this is self's standard offset
1474 if delta:
1475 dt += delta # convert to standard local time
1476 dtdst = dt.dst()
1477 # raise ValueError if dtdst is None
1478 if dtdst:
1479 return dt + dtdst
1480 else:
1481 return dt
1482
1483Example :class:`tzinfo` classes:
1484
1485.. literalinclude:: ../includes/tzinfo-examples.py
1486
1487
1488Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1489subclass accounting for both standard and daylight time, at the DST transition
1490points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00001491minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
14921:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001493
1494 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1495 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1496 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1497
1498 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1499
1500 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1501
1502When DST starts (the "start" line), the local wall clock leaps from 1:59 to
15033:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1504``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1505begins. In order for :meth:`astimezone` to make this guarantee, the
1506:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1507Eastern) to be in daylight time.
1508
1509When DST ends (the "end" line), there's a potentially worse problem: there's an
1510hour that can't be spelled unambiguously in local wall time: the last hour of
1511daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1512daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1513to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1514:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1515hours into the same local hour then. In the Eastern example, UTC times of the
1516form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1517:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1518consider times in the "repeated hour" to be in standard time. This is easily
1519arranged, as in the example, by expressing DST switch times in the time zone's
1520standard local time.
1521
1522Applications that can't bear such ambiguities should avoid using hybrid
1523:class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any
1524other fixed-offset :class:`tzinfo` subclass (such as a class representing only
1525EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
Georg Brandl48310cd2009-01-03 21:18:54 +00001526
Georg Brandl116aa622007-08-15 14:28:22 +00001527
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001528.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00001529
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001530:meth:`strftime` and :meth:`strptime` Behavior
1531----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001532
1533:class:`date`, :class:`datetime`, and :class:`time` objects all support a
1534``strftime(format)`` method, to create a string representing the time under the
1535control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1536acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1537although not all objects support a :meth:`timetuple` method.
1538
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001539Conversely, the :meth:`datetime.strptime` class method creates a
1540:class:`datetime` object from a string representing a date and time and a
1541corresponding format string. ``datetime.strptime(date_string, format)`` is
1542equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1543
Georg Brandl116aa622007-08-15 14:28:22 +00001544For :class:`time` objects, the format codes for year, month, and day should not
1545be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001546is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00001547
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001548For :class:`date` objects, the format codes for hours, minutes, seconds, and
1549microseconds should not be used, as :class:`date` objects have no such
1550values. If they're used anyway, ``0`` is substituted for them.
1551
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001552For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1553strings.
1554
1555For an aware object:
1556
1557``%z``
1558 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1559 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1560 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1561 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1562 replaced with the string ``'-0330'``.
1563
1564``%Z``
1565 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1566 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl116aa622007-08-15 14:28:22 +00001567
Georg Brandl116aa622007-08-15 14:28:22 +00001568The full set of format codes supported varies across platforms, because Python
1569calls the platform C library's :func:`strftime` function, and platform
Georg Brandl48310cd2009-01-03 21:18:54 +00001570variations are common.
Christian Heimes895627f2007-12-08 17:28:33 +00001571
1572The following is a list of all the format codes that the C standard (1989
1573version) requires, and these work on all platforms with a standard C
1574implementation. Note that the 1999 version of the C standard added additional
1575format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001576
1577The exact range of years for which :meth:`strftime` works also varies across
1578platforms. Regardless of platform, years before 1900 cannot be used.
1579
Christian Heimes895627f2007-12-08 17:28:33 +00001580+-----------+--------------------------------+-------+
1581| Directive | Meaning | Notes |
1582+===========+================================+=======+
1583| ``%a`` | Locale's abbreviated weekday | |
1584| | name. | |
1585+-----------+--------------------------------+-------+
1586| ``%A`` | Locale's full weekday name. | |
1587+-----------+--------------------------------+-------+
1588| ``%b`` | Locale's abbreviated month | |
1589| | name. | |
1590+-----------+--------------------------------+-------+
1591| ``%B`` | Locale's full month name. | |
1592+-----------+--------------------------------+-------+
1593| ``%c`` | Locale's appropriate date and | |
1594| | time representation. | |
1595+-----------+--------------------------------+-------+
1596| ``%d`` | Day of the month as a decimal | |
1597| | number [01,31]. | |
1598+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001599| ``%f`` | Microsecond as a decimal | \(1) |
1600| | number [0,999999], zero-padded | |
1601| | on the left | |
1602+-----------+--------------------------------+-------+
Christian Heimes895627f2007-12-08 17:28:33 +00001603| ``%H`` | Hour (24-hour clock) as a | |
1604| | decimal number [00,23]. | |
1605+-----------+--------------------------------+-------+
1606| ``%I`` | Hour (12-hour clock) as a | |
1607| | decimal number [01,12]. | |
1608+-----------+--------------------------------+-------+
1609| ``%j`` | Day of the year as a decimal | |
1610| | number [001,366]. | |
1611+-----------+--------------------------------+-------+
1612| ``%m`` | Month as a decimal number | |
1613| | [01,12]. | |
1614+-----------+--------------------------------+-------+
1615| ``%M`` | Minute as a decimal number | |
1616| | [00,59]. | |
1617+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001618| ``%p`` | Locale's equivalent of either | \(2) |
Christian Heimes895627f2007-12-08 17:28:33 +00001619| | AM or PM. | |
1620+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001621| ``%S`` | Second as a decimal number | \(3) |
Christian Heimes895627f2007-12-08 17:28:33 +00001622| | [00,61]. | |
1623+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001624| ``%U`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001625| | (Sunday as the first day of | |
1626| | the week) as a decimal number | |
1627| | [00,53]. All days in a new | |
1628| | year preceding the first | |
1629| | Sunday are considered to be in | |
1630| | week 0. | |
1631+-----------+--------------------------------+-------+
1632| ``%w`` | Weekday as a decimal number | |
1633| | [0(Sunday),6]. | |
1634+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001635| ``%W`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001636| | (Monday as the first day of | |
1637| | the week) as a decimal number | |
1638| | [00,53]. All days in a new | |
1639| | year preceding the first | |
1640| | Monday are considered to be in | |
1641| | week 0. | |
1642+-----------+--------------------------------+-------+
1643| ``%x`` | Locale's appropriate date | |
1644| | representation. | |
1645+-----------+--------------------------------+-------+
1646| ``%X`` | Locale's appropriate time | |
1647| | representation. | |
1648+-----------+--------------------------------+-------+
1649| ``%y`` | Year without century as a | |
1650| | decimal number [00,99]. | |
1651+-----------+--------------------------------+-------+
1652| ``%Y`` | Year with century as a decimal | |
1653| | number. | |
1654+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001655| ``%z`` | UTC offset in the form +HHMM | \(5) |
Christian Heimes895627f2007-12-08 17:28:33 +00001656| | or -HHMM (empty string if the | |
1657| | the object is naive). | |
1658+-----------+--------------------------------+-------+
1659| ``%Z`` | Time zone name (empty string | |
1660| | if the object is naive). | |
1661+-----------+--------------------------------+-------+
1662| ``%%`` | A literal ``'%'`` character. | |
1663+-----------+--------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001664
Christian Heimes895627f2007-12-08 17:28:33 +00001665Notes:
1666
1667(1)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001668 When used with the :meth:`strptime` method, the ``%f`` directive
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001669 accepts from one to six digits and zero pads on the right. ``%f`` is
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001670 an extension to the set of format characters in the C standard (but
1671 implemented separately in datetime objects, and therefore always
1672 available).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001673
1674(2)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001675 When used with the :meth:`strptime` method, the ``%p`` directive only affects
Christian Heimes895627f2007-12-08 17:28:33 +00001676 the output hour field if the ``%I`` directive is used to parse the hour.
1677
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001678(3)
R. David Murraybd25d332009-04-02 04:50:03 +00001679 The range really is ``0`` to ``61``; according to the Posix standard this
1680 accounts for leap seconds and the (very rare) double leap seconds.
1681 The :mod:`time` module may produce and does accept leap seconds since
1682 it is based on the Posix standard, but the :mod:`datetime` module
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001683 does not accept leap seconds in :meth:`strptime` input nor will it
R. David Murraybd25d332009-04-02 04:50:03 +00001684 produce them in :func:`strftime` output.
Christian Heimes895627f2007-12-08 17:28:33 +00001685
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001686(4)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001687 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in
Christian Heimes895627f2007-12-08 17:28:33 +00001688 calculations when the day of the week and the year are specified.
1689
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001690(5)
Christian Heimes895627f2007-12-08 17:28:33 +00001691 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1692 ``%z`` is replaced with the string ``'-0330'``.