blob: 2a90e42ea131c306dc5f61e86ea9414fca9e3005 [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,
483 d.weekday(), d.toordinal() - date(d.year, 1, 1).toordinal() + 1, -1))``
484
485
486.. method:: date.toordinal()
487
488 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
489 has ordinal 1. For any :class:`date` object *d*,
490 ``date.fromordinal(d.toordinal()) == d``.
491
492
493.. method:: date.weekday()
494
495 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
496 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
497 :meth:`isoweekday`.
498
499
500.. method:: date.isoweekday()
501
502 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
503 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
504 :meth:`weekday`, :meth:`isocalendar`.
505
506
507.. method:: date.isocalendar()
508
509 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
510
511 The ISO calendar is a widely used variant of the Gregorian calendar. See
Mark Dickinsonf964ac22009-11-03 16:29:10 +0000512 http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
513 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000514
515 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
516 Monday and ends on a Sunday. The first week of an ISO year is the first
517 (Gregorian) calendar week of a year containing a Thursday. This is called week
518 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
519
520 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
521 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
522 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
523 4).isocalendar() == (2004, 1, 7)``.
524
525
526.. method:: date.isoformat()
527
528 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
529 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
530
531
532.. method:: date.__str__()
533
534 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
535
536
537.. method:: date.ctime()
538
539 Return a string representing the date, for example ``date(2002, 12,
540 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
541 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
542 :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
543 :meth:`date.ctime` does not invoke) conforms to the C standard.
544
545
546.. method:: date.strftime(format)
547
548 Return a string representing the date, controlled by an explicit format string.
549 Format codes referring to hours, minutes or seconds will see 0 values. See
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000550 section :ref:`strftime-strptime-behavior`.
551
Georg Brandl116aa622007-08-15 14:28:22 +0000552
Christian Heimes895627f2007-12-08 17:28:33 +0000553Example of counting days to an event::
554
555 >>> import time
556 >>> from datetime import date
557 >>> today = date.today()
558 >>> today
559 datetime.date(2007, 12, 5)
560 >>> today == date.fromtimestamp(time.time())
561 True
562 >>> my_birthday = date(today.year, 6, 24)
563 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000564 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000565 >>> my_birthday
566 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000567 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000568 >>> time_to_birthday.days
569 202
570
Christian Heimesfe337bf2008-03-23 21:54:12 +0000571Example of working with :class:`date`:
572
573.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000574
575 >>> from datetime import date
576 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
577 >>> d
578 datetime.date(2002, 3, 11)
579 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000580 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000581 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000582 2002 # year
583 3 # month
584 11 # day
585 0
586 0
587 0
588 0 # weekday (0 = Monday)
589 70 # 70th day in the year
590 -1
591 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000592 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000593 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000594 2002 # ISO year
595 11 # ISO week number
596 1 # ISO day number ( 1 = Monday )
597 >>> d.isoformat()
598 '2002-03-11'
599 >>> d.strftime("%d/%m/%y")
600 '11/03/02'
601 >>> d.strftime("%A %d. %B %Y")
602 'Monday 11. March 2002'
603
Georg Brandl116aa622007-08-15 14:28:22 +0000604
605.. _datetime-datetime:
606
607:class:`datetime` Objects
608-------------------------
609
610A :class:`datetime` object is a single object containing all the information
611from a :class:`date` object and a :class:`time` object. Like a :class:`date`
612object, :class:`datetime` assumes the current Gregorian calendar extended in
613both directions; like a time object, :class:`datetime` assumes there are exactly
6143600\*24 seconds in every day.
615
616Constructor:
617
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000618.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000619
620 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000621 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
622 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000623
624 * ``MINYEAR <= year <= MAXYEAR``
625 * ``1 <= month <= 12``
626 * ``1 <= day <= number of days in the given month and year``
627 * ``0 <= hour < 24``
628 * ``0 <= minute < 60``
629 * ``0 <= second < 60``
630 * ``0 <= microsecond < 1000000``
631
632 If an argument outside those ranges is given, :exc:`ValueError` is raised.
633
634Other constructors, all class methods:
635
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000636.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000637
638 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
639 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
640 :meth:`fromtimestamp`.
641
642
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000643.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000644
645 Return the current local date and time. If optional argument *tz* is ``None``
646 or not specified, this is like :meth:`today`, but, if possible, supplies more
647 precision than can be gotten from going through a :func:`time.time` timestamp
648 (for example, this may be possible on platforms supplying the C
649 :cfunc:`gettimeofday` function).
650
651 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
652 current date and time are converted to *tz*'s time zone. In this case the
653 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
654 See also :meth:`today`, :meth:`utcnow`.
655
656
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000657.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000658
659 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
660 :meth:`now`, but returns the current UTC date and time, as a naive
661 :class:`datetime` object. See also :meth:`now`.
662
663
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000664.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000665
666 Return the local date and time corresponding to the POSIX timestamp, such as is
667 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
668 specified, the timestamp is converted to the platform's local date and time, and
669 the returned :class:`datetime` object is naive.
670
671 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
672 timestamp is converted to *tz*'s time zone. In this case the result is
673 equivalent to
674 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
675
676 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
677 the range of values supported by the platform C :cfunc:`localtime` or
678 :cfunc:`gmtime` functions. It's common for this to be restricted to years in
679 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
680 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
681 and then it's possible to have two timestamps differing by a second that yield
682 identical :class:`datetime` objects. See also :meth:`utcfromtimestamp`.
683
684
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000685.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000686
687 Return the UTC :class:`datetime` corresponding to the POSIX timestamp, with
688 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
689 out of the range of values supported by the platform C :cfunc:`gmtime` function.
690 It's common for this to be restricted to years in 1970 through 2038. See also
691 :meth:`fromtimestamp`.
692
693
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000694.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000695
696 Return the :class:`datetime` corresponding to the proleptic Gregorian ordinal,
697 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
698 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
699 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
700
701
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000702.. classmethod:: datetime.combine(date, time)
Georg Brandl116aa622007-08-15 14:28:22 +0000703
704 Return a new :class:`datetime` object whose date members are equal to the given
705 :class:`date` object's, and whose time and :attr:`tzinfo` members are equal to
706 the given :class:`time` object's. For any :class:`datetime` object *d*, ``d ==
707 datetime.combine(d.date(), d.timetz())``. If date is a :class:`datetime`
708 object, its time and :attr:`tzinfo` members are ignored.
709
710
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000711.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000712
713 Return a :class:`datetime` corresponding to *date_string*, parsed according to
714 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
715 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
716 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 +0000717 time tuple. See section :ref:`strftime-strptime-behavior`.
718
Georg Brandl116aa622007-08-15 14:28:22 +0000719
Georg Brandl116aa622007-08-15 14:28:22 +0000720
721Class attributes:
722
Georg Brandl116aa622007-08-15 14:28:22 +0000723.. attribute:: datetime.min
724
725 The earliest representable :class:`datetime`, ``datetime(MINYEAR, 1, 1,
726 tzinfo=None)``.
727
728
729.. attribute:: datetime.max
730
731 The latest representable :class:`datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
732 59, 999999, tzinfo=None)``.
733
734
735.. attribute:: datetime.resolution
736
737 The smallest possible difference between non-equal :class:`datetime` objects,
738 ``timedelta(microseconds=1)``.
739
Georg Brandl116aa622007-08-15 14:28:22 +0000740
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000741Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000742
743.. attribute:: datetime.year
744
745 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
746
747
748.. attribute:: datetime.month
749
750 Between 1 and 12 inclusive.
751
752
753.. attribute:: datetime.day
754
755 Between 1 and the number of days in the given month of the given year.
756
757
758.. attribute:: datetime.hour
759
760 In ``range(24)``.
761
762
763.. attribute:: datetime.minute
764
765 In ``range(60)``.
766
767
768.. attribute:: datetime.second
769
770 In ``range(60)``.
771
772
773.. attribute:: datetime.microsecond
774
775 In ``range(1000000)``.
776
777
778.. attribute:: datetime.tzinfo
779
780 The object passed as the *tzinfo* argument to the :class:`datetime` constructor,
781 or ``None`` if none was passed.
782
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000783
Georg Brandl116aa622007-08-15 14:28:22 +0000784Supported operations:
785
786+---------------------------------------+-------------------------------+
787| Operation | Result |
788+=======================================+===============================+
789| ``datetime2 = datetime1 + timedelta`` | \(1) |
790+---------------------------------------+-------------------------------+
791| ``datetime2 = datetime1 - timedelta`` | \(2) |
792+---------------------------------------+-------------------------------+
793| ``timedelta = datetime1 - datetime2`` | \(3) |
794+---------------------------------------+-------------------------------+
795| ``datetime1 < datetime2`` | Compares :class:`datetime` to |
796| | :class:`datetime`. (4) |
797+---------------------------------------+-------------------------------+
798
799(1)
800 datetime2 is a duration of timedelta removed from datetime1, moving forward in
801 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
802 result has the same :attr:`tzinfo` member as the input datetime, and datetime2 -
803 datetime1 == timedelta after. :exc:`OverflowError` is raised if datetime2.year
804 would be smaller than :const:`MINYEAR` or larger than :const:`MAXYEAR`. Note
805 that no time zone adjustments are done even if the input is an aware object.
806
807(2)
808 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
809 addition, the result has the same :attr:`tzinfo` member as the input datetime,
810 and no time zone adjustments are done even if the input is aware. This isn't
811 quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation
812 can overflow in cases where datetime1 - timedelta does not.
813
814(3)
815 Subtraction of a :class:`datetime` from a :class:`datetime` is defined only if
816 both operands are naive, or if both are aware. If one is aware and the other is
817 naive, :exc:`TypeError` is raised.
818
819 If both are naive, or both are aware and have the same :attr:`tzinfo` member,
820 the :attr:`tzinfo` members are ignored, and the result is a :class:`timedelta`
821 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
822 are done in this case.
823
824 If both are aware and have different :attr:`tzinfo` members, ``a-b`` acts as if
825 *a* and *b* were first converted to naive UTC datetimes first. The result is
826 ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) -
827 b.utcoffset())`` except that the implementation never overflows.
828
829(4)
830 *datetime1* is considered less than *datetime2* when *datetime1* precedes
831 *datetime2* in time.
832
833 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
834 If both comparands are aware, and have the same :attr:`tzinfo` member, the
835 common :attr:`tzinfo` member is ignored and the base datetimes are compared. If
836 both comparands are aware and have different :attr:`tzinfo` members, the
837 comparands are first adjusted by subtracting their UTC offsets (obtained from
838 ``self.utcoffset()``).
839
840 .. note::
841
842 In order to stop comparison from falling back to the default scheme of comparing
843 object addresses, datetime comparison normally raises :exc:`TypeError` if the
844 other comparand isn't also a :class:`datetime` object. However,
845 ``NotImplemented`` is returned instead if the other comparand has a
846 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
847 chance at implementing mixed-type comparison. If not, when a :class:`datetime`
848 object is compared to an object of a different type, :exc:`TypeError` is raised
849 unless the comparison is ``==`` or ``!=``. The latter cases return
850 :const:`False` or :const:`True`, respectively.
851
852:class:`datetime` objects can be used as dictionary keys. In Boolean contexts,
853all :class:`datetime` objects are considered to be true.
854
855Instance methods:
856
Georg Brandl116aa622007-08-15 14:28:22 +0000857.. method:: datetime.date()
858
859 Return :class:`date` object with same year, month and day.
860
861
862.. method:: datetime.time()
863
864 Return :class:`time` object with same hour, minute, second and microsecond.
865 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
866
867
868.. method:: datetime.timetz()
869
870 Return :class:`time` object with same hour, minute, second, microsecond, and
871 tzinfo members. See also method :meth:`time`.
872
873
874.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
875
876 Return a datetime with the same members, except for those members given new
877 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
878 can be specified to create a naive datetime from an aware datetime with no
879 conversion of date and time members.
880
881
882.. method:: datetime.astimezone(tz)
883
884 Return a :class:`datetime` object with new :attr:`tzinfo` member *tz*, adjusting
885 the date and time members so the result is the same UTC time as *self*, but in
886 *tz*'s local time.
887
888 *tz* must be an instance of a :class:`tzinfo` subclass, and its
889 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
890 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
891 not return ``None``).
892
893 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
894 adjustment of date or time members is performed. Else the result is local time
895 in time zone *tz*, representing the same UTC time as *self*: after ``astz =
896 dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have the same date
897 and time members as ``dt - dt.utcoffset()``. The discussion of class
898 :class:`tzinfo` explains the cases at Daylight Saving Time transition boundaries
899 where this cannot be achieved (an issue only if *tz* models both standard and
900 daylight time).
901
902 If you merely want to attach a time zone object *tz* to a datetime *dt* without
903 adjustment of date and time members, use ``dt.replace(tzinfo=tz)``. If you
904 merely want to remove the time zone object from an aware datetime *dt* without
905 conversion of date and time members, use ``dt.replace(tzinfo=None)``.
906
907 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
908 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
909 Ignoring error cases, :meth:`astimezone` acts like::
910
911 def astimezone(self, tz):
912 if self.tzinfo is tz:
913 return self
914 # Convert self to UTC, and attach the new time zone object.
915 utc = (self - self.utcoffset()).replace(tzinfo=tz)
916 # Convert from UTC to tz's local time.
917 return tz.fromutc(utc)
918
919
920.. method:: datetime.utcoffset()
921
922 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
923 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
924 return ``None``, or a :class:`timedelta` object representing a whole number of
925 minutes with magnitude less than one day.
926
927
928.. method:: datetime.dst()
929
930 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
931 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
932 ``None``, or a :class:`timedelta` object representing a whole number of minutes
933 with magnitude less than one day.
934
935
936.. method:: datetime.tzname()
937
938 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
939 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
940 ``None`` or a string object,
941
942
943.. method:: datetime.timetuple()
944
945 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
946 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
947 d.hour, d.minute, d.second, d.weekday(), d.toordinal() - date(d.year, 1,
948 1).toordinal() + 1, dst))`` The :attr:`tm_isdst` flag of the result is set
949 according to the :meth:`dst` method: :attr:`tzinfo` is ``None`` or :meth:`dst`
950 returns ``None``, :attr:`tm_isdst` is set to ``-1``; else if :meth:`dst`
951 returns a non-zero value, :attr:`tm_isdst` is set to ``1``; else ``tm_isdst`` is
952 set to ``0``.
953
954
955.. method:: datetime.utctimetuple()
956
957 If :class:`datetime` instance *d* is naive, this is the same as
958 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
959 ``d.dst()`` returns. DST is never in effect for a UTC time.
960
961 If *d* is aware, *d* is normalized to UTC time, by subtracting
962 ``d.utcoffset()``, and a :class:`time.struct_time` for the normalized time is
963 returned. :attr:`tm_isdst` is forced to 0. Note that the result's
964 :attr:`tm_year` member may be :const:`MINYEAR`\ -1 or :const:`MAXYEAR`\ +1, if
965 *d*.year was ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
966 boundary.
967
968
969.. method:: datetime.toordinal()
970
971 Return the proleptic Gregorian ordinal of the date. The same as
972 ``self.date().toordinal()``.
973
974
975.. method:: datetime.weekday()
976
977 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
978 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
979
980
981.. method:: datetime.isoweekday()
982
983 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
984 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
985 :meth:`isocalendar`.
986
987
988.. method:: datetime.isocalendar()
989
990 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
991 ``self.date().isocalendar()``.
992
993
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000994.. method:: datetime.isoformat(sep='T')
Georg Brandl116aa622007-08-15 14:28:22 +0000995
996 Return a string representing the date and time in ISO 8601 format,
997 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
998 YYYY-MM-DDTHH:MM:SS
999
1000 If :meth:`utcoffset` does not return ``None``, a 6-character string is
1001 appended, giving the UTC offset in (signed) hours and minutes:
1002 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
1003 YYYY-MM-DDTHH:MM:SS+HH:MM
1004
1005 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +00001006 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +00001007
1008 >>> from datetime import tzinfo, timedelta, datetime
1009 >>> class TZ(tzinfo):
1010 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1011 ...
1012 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1013 '2002-12-25 00:00:00-06:39'
1014
1015
1016.. method:: datetime.__str__()
1017
1018 For a :class:`datetime` instance *d*, ``str(d)`` is equivalent to
1019 ``d.isoformat(' ')``.
1020
1021
1022.. method:: datetime.ctime()
1023
1024 Return a string representing the date and time, for example ``datetime(2002, 12,
1025 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1026 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
1027 native C :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
1028 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1029
1030
1031.. method:: datetime.strftime(format)
1032
1033 Return a string representing the date and time, controlled by an explicit format
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001034 string. See section :ref:`strftime-strptime-behavior`.
1035
Georg Brandl116aa622007-08-15 14:28:22 +00001036
Christian Heimesfe337bf2008-03-23 21:54:12 +00001037Examples of working with datetime objects:
1038
1039.. doctest::
1040
Christian Heimes895627f2007-12-08 17:28:33 +00001041 >>> from datetime import datetime, date, time
1042 >>> # Using datetime.combine()
1043 >>> d = date(2005, 7, 14)
1044 >>> t = time(12, 30)
1045 >>> datetime.combine(d, t)
1046 datetime.datetime(2005, 7, 14, 12, 30)
1047 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001048 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001049 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001050 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001051 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1052 >>> # Using datetime.strptime()
1053 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1054 >>> dt
1055 datetime.datetime(2006, 11, 21, 16, 30)
1056 >>> # Using datetime.timetuple() to get tuple of all attributes
1057 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001058 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001059 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001060 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001061 2006 # year
1062 11 # month
1063 21 # day
1064 16 # hour
1065 30 # minute
1066 0 # second
1067 1 # weekday (0 = Monday)
1068 325 # number of days since 1st January
1069 -1 # dst - method tzinfo.dst() returned None
1070 >>> # Date in ISO format
1071 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001072 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001073 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001074 ...
1075 2006 # ISO year
1076 47 # ISO week
1077 2 # ISO weekday
1078 >>> # Formatting datetime
1079 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1080 'Tuesday, 21. November 2006 04:30PM'
1081
Christian Heimesfe337bf2008-03-23 21:54:12 +00001082Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001083
1084 >>> from datetime import timedelta, datetime, tzinfo
1085 >>> class GMT1(tzinfo):
1086 ... def __init__(self): # DST starts last Sunday in March
1087 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1088 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001089 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001090 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1091 ... def utcoffset(self, dt):
1092 ... return timedelta(hours=1) + self.dst(dt)
Georg Brandl48310cd2009-01-03 21:18:54 +00001093 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001094 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1095 ... return timedelta(hours=1)
1096 ... else:
1097 ... return timedelta(0)
1098 ... def tzname(self,dt):
1099 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001100 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001101 >>> class GMT2(tzinfo):
1102 ... def __init__(self):
Georg Brandl48310cd2009-01-03 21:18:54 +00001103 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001104 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001105 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001106 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1107 ... def utcoffset(self, dt):
1108 ... return timedelta(hours=1) + self.dst(dt)
1109 ... def dst(self, dt):
1110 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1111 ... return timedelta(hours=2)
1112 ... else:
1113 ... return timedelta(0)
1114 ... def tzname(self,dt):
1115 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001116 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001117 >>> gmt1 = GMT1()
1118 >>> # Daylight Saving Time
1119 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1120 >>> dt1.dst()
1121 datetime.timedelta(0)
1122 >>> dt1.utcoffset()
1123 datetime.timedelta(0, 3600)
1124 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1125 >>> dt2.dst()
1126 datetime.timedelta(0, 3600)
1127 >>> dt2.utcoffset()
1128 datetime.timedelta(0, 7200)
1129 >>> # Convert datetime to another time zone
1130 >>> dt3 = dt2.astimezone(GMT2())
1131 >>> dt3 # doctest: +ELLIPSIS
1132 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1133 >>> dt2 # doctest: +ELLIPSIS
1134 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1135 >>> dt2.utctimetuple() == dt3.utctimetuple()
1136 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001137
Christian Heimes895627f2007-12-08 17:28:33 +00001138
Georg Brandl116aa622007-08-15 14:28:22 +00001139
1140.. _datetime-time:
1141
1142:class:`time` Objects
1143---------------------
1144
1145A time object represents a (local) time of day, independent of any particular
1146day, and subject to adjustment via a :class:`tzinfo` object.
1147
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001148.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001149
1150 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001151 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001152 following ranges:
1153
1154 * ``0 <= hour < 24``
1155 * ``0 <= minute < 60``
1156 * ``0 <= second < 60``
1157 * ``0 <= microsecond < 1000000``.
1158
1159 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1160 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1161
1162Class attributes:
1163
1164
1165.. attribute:: time.min
1166
1167 The earliest representable :class:`time`, ``time(0, 0, 0, 0)``.
1168
1169
1170.. attribute:: time.max
1171
1172 The latest representable :class:`time`, ``time(23, 59, 59, 999999)``.
1173
1174
1175.. attribute:: time.resolution
1176
1177 The smallest possible difference between non-equal :class:`time` objects,
1178 ``timedelta(microseconds=1)``, although note that arithmetic on :class:`time`
1179 objects is not supported.
1180
Georg Brandl116aa622007-08-15 14:28:22 +00001181
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001182Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001183
1184.. attribute:: time.hour
1185
1186 In ``range(24)``.
1187
1188
1189.. attribute:: time.minute
1190
1191 In ``range(60)``.
1192
1193
1194.. attribute:: time.second
1195
1196 In ``range(60)``.
1197
1198
1199.. attribute:: time.microsecond
1200
1201 In ``range(1000000)``.
1202
1203
1204.. attribute:: time.tzinfo
1205
1206 The object passed as the tzinfo argument to the :class:`time` constructor, or
1207 ``None`` if none was passed.
1208
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001209
Georg Brandl116aa622007-08-15 14:28:22 +00001210Supported operations:
1211
1212* comparison of :class:`time` to :class:`time`, where *a* is considered less
1213 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1214 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
1215 the same :attr:`tzinfo` member, the common :attr:`tzinfo` member is ignored and
1216 the base times are compared. If both comparands are aware and have different
1217 :attr:`tzinfo` members, the comparands are first adjusted by subtracting their
1218 UTC offsets (obtained from ``self.utcoffset()``). In order to stop mixed-type
1219 comparisons from falling back to the default comparison by object address, when
1220 a :class:`time` object is compared to an object of a different type,
1221 :exc:`TypeError` is raised unless the comparison is ``==`` or ``!=``. The
1222 latter cases return :const:`False` or :const:`True`, respectively.
1223
1224* hash, use as dict key
1225
1226* efficient pickling
1227
1228* in Boolean contexts, a :class:`time` object is considered to be true if and
1229 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1230 ``0`` if that's ``None``), the result is non-zero.
1231
Georg Brandl116aa622007-08-15 14:28:22 +00001232
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001233Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001234
1235.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1236
1237 Return a :class:`time` with the same value, except for those members given new
1238 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
1239 can be specified to create a naive :class:`time` from an aware :class:`time`,
1240 without conversion of the time members.
1241
1242
1243.. method:: time.isoformat()
1244
1245 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1246 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1247 6-character string is appended, giving the UTC offset in (signed) hours and
1248 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1249
1250
1251.. method:: time.__str__()
1252
1253 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1254
1255
1256.. method:: time.strftime(format)
1257
1258 Return a string representing the time, controlled by an explicit format string.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001259 See section :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001260
1261
1262.. method:: time.utcoffset()
1263
1264 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1265 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1266 return ``None`` or a :class:`timedelta` object representing a whole number of
1267 minutes with magnitude less than one day.
1268
1269
1270.. method:: time.dst()
1271
1272 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1273 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1274 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1275 with magnitude less than one day.
1276
1277
1278.. method:: time.tzname()
1279
1280 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1281 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1282 return ``None`` or a string object.
1283
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001284
Christian Heimesfe337bf2008-03-23 21:54:12 +00001285Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001286
Christian Heimes895627f2007-12-08 17:28:33 +00001287 >>> from datetime import time, tzinfo
1288 >>> class GMT1(tzinfo):
1289 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001290 ... return timedelta(hours=1)
1291 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001292 ... return timedelta(0)
1293 ... def tzname(self,dt):
1294 ... return "Europe/Prague"
1295 ...
1296 >>> t = time(12, 10, 30, tzinfo=GMT1())
1297 >>> t # doctest: +ELLIPSIS
1298 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1299 >>> gmt = GMT1()
1300 >>> t.isoformat()
1301 '12:10:30+01:00'
1302 >>> t.dst()
1303 datetime.timedelta(0)
1304 >>> t.tzname()
1305 'Europe/Prague'
1306 >>> t.strftime("%H:%M:%S %Z")
1307 '12:10:30 Europe/Prague'
1308
Georg Brandl116aa622007-08-15 14:28:22 +00001309
1310.. _datetime-tzinfo:
1311
1312:class:`tzinfo` Objects
1313-----------------------
1314
Brett Cannone1327f72009-01-29 04:10:21 +00001315:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001316instantiated directly. You need to derive a concrete subclass, and (at least)
1317supply implementations of the standard :class:`tzinfo` methods needed by the
1318:class:`datetime` methods you use. The :mod:`datetime` module does not supply
1319any concrete subclasses of :class:`tzinfo`.
1320
1321An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1322constructors for :class:`datetime` and :class:`time` objects. The latter objects
1323view their members as being in local time, and the :class:`tzinfo` object
1324supports methods revealing offset of local time from UTC, the name of the time
1325zone, and DST offset, all relative to a date or time object passed to them.
1326
1327Special requirement for pickling: A :class:`tzinfo` subclass must have an
1328:meth:`__init__` method that can be called with no arguments, else it can be
1329pickled but possibly not unpickled again. This is a technical requirement that
1330may be relaxed in the future.
1331
1332A concrete subclass of :class:`tzinfo` may need to implement the following
1333methods. Exactly which methods are needed depends on the uses made of aware
1334:mod:`datetime` objects. If in doubt, simply implement all of them.
1335
1336
1337.. method:: tzinfo.utcoffset(self, dt)
1338
1339 Return offset of local time from UTC, in minutes east of UTC. If local time is
1340 west of UTC, this should be negative. Note that this is intended to be the
1341 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1342 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1343 the UTC offset isn't known, return ``None``. Else the value returned must be a
1344 :class:`timedelta` object specifying a whole number of minutes in the range
1345 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1346 than one day). Most implementations of :meth:`utcoffset` will probably look
1347 like one of these two::
1348
1349 return CONSTANT # fixed-offset class
1350 return CONSTANT + self.dst(dt) # daylight-aware class
1351
1352 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1353 ``None`` either.
1354
1355 The default implementation of :meth:`utcoffset` raises
1356 :exc:`NotImplementedError`.
1357
1358
1359.. method:: tzinfo.dst(self, dt)
1360
1361 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1362 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1363 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1364 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1365 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1366 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1367 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
1368 member's :meth:`dst` method to determine how the :attr:`tm_isdst` flag should be
1369 set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for DST changes
1370 when crossing time zones.
1371
1372 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1373 daylight times must be consistent in this sense:
1374
1375 ``tz.utcoffset(dt) - tz.dst(dt)``
1376
1377 must return the same result for every :class:`datetime` *dt* with ``dt.tzinfo ==
1378 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1379 zone's "standard offset", which should not depend on the date or the time, but
1380 only on geographic location. The implementation of :meth:`datetime.astimezone`
1381 relies on this, but cannot detect violations; it's the programmer's
1382 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1383 this, it may be able to override the default implementation of
1384 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1385
1386 Most implementations of :meth:`dst` will probably look like one of these two::
1387
1388 def dst(self):
1389 # a fixed-offset class: doesn't account for DST
1390 return timedelta(0)
1391
1392 or ::
1393
1394 def dst(self):
1395 # Code to set dston and dstoff to the time zone's DST
1396 # transition times based on the input dt.year, and expressed
1397 # in standard local time. Then
1398
1399 if dston <= dt.replace(tzinfo=None) < dstoff:
1400 return timedelta(hours=1)
1401 else:
1402 return timedelta(0)
1403
1404 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1405
1406
1407.. method:: tzinfo.tzname(self, dt)
1408
1409 Return the time zone name corresponding to the :class:`datetime` object *dt*, as
1410 a string. Nothing about string names is defined by the :mod:`datetime` module,
1411 and there's no requirement that it mean anything in particular. For example,
1412 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1413 valid replies. Return ``None`` if a string name isn't known. Note that this is
1414 a method rather than a fixed string primarily because some :class:`tzinfo`
1415 subclasses will wish to return different names depending on the specific value
1416 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1417 daylight time.
1418
1419 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1420
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001421
Georg Brandl116aa622007-08-15 14:28:22 +00001422These methods are called by a :class:`datetime` or :class:`time` object, in
1423response to their methods of the same names. A :class:`datetime` object passes
1424itself as the argument, and a :class:`time` object passes ``None`` as the
1425argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
1426accept a *dt* argument of ``None``, or of class :class:`datetime`.
1427
1428When ``None`` is passed, it's up to the class designer to decide the best
1429response. For example, returning ``None`` is appropriate if the class wishes to
1430say that time objects don't participate in the :class:`tzinfo` protocols. It
1431may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1432there is no other convention for discovering the standard offset.
1433
1434When a :class:`datetime` object is passed in response to a :class:`datetime`
1435method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1436rely on this, unless user code calls :class:`tzinfo` methods directly. The
1437intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1438time, and not need worry about objects in other timezones.
1439
1440There is one more :class:`tzinfo` method that a subclass may wish to override:
1441
1442
1443.. method:: tzinfo.fromutc(self, dt)
1444
1445 This is called from the default :class:`datetime.astimezone()` implementation.
1446 When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members
1447 are to be viewed as expressing a UTC time. The purpose of :meth:`fromutc` is to
1448 adjust the date and time members, returning an equivalent datetime in *self*'s
1449 local time.
1450
1451 Most :class:`tzinfo` subclasses should be able to inherit the default
1452 :meth:`fromutc` implementation without problems. It's strong enough to handle
1453 fixed-offset time zones, and time zones accounting for both standard and
1454 daylight time, and the latter even if the DST transition times differ in
1455 different years. An example of a time zone the default :meth:`fromutc`
1456 implementation may not handle correctly in all cases is one where the standard
1457 offset (from UTC) depends on the specific date and time passed, which can happen
1458 for political reasons. The default implementations of :meth:`astimezone` and
1459 :meth:`fromutc` may not produce the result you want if the result is one of the
1460 hours straddling the moment the standard offset changes.
1461
1462 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1463 like::
1464
1465 def fromutc(self, dt):
1466 # raise ValueError error if dt.tzinfo is not self
1467 dtoff = dt.utcoffset()
1468 dtdst = dt.dst()
1469 # raise ValueError if dtoff is None or dtdst is None
1470 delta = dtoff - dtdst # this is self's standard offset
1471 if delta:
1472 dt += delta # convert to standard local time
1473 dtdst = dt.dst()
1474 # raise ValueError if dtdst is None
1475 if dtdst:
1476 return dt + dtdst
1477 else:
1478 return dt
1479
1480Example :class:`tzinfo` classes:
1481
1482.. literalinclude:: ../includes/tzinfo-examples.py
1483
1484
1485Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1486subclass accounting for both standard and daylight time, at the DST transition
1487points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00001488minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
14891:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001490
1491 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1492 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1493 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1494
1495 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1496
1497 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1498
1499When DST starts (the "start" line), the local wall clock leaps from 1:59 to
15003:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1501``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1502begins. In order for :meth:`astimezone` to make this guarantee, the
1503:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1504Eastern) to be in daylight time.
1505
1506When DST ends (the "end" line), there's a potentially worse problem: there's an
1507hour that can't be spelled unambiguously in local wall time: the last hour of
1508daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1509daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1510to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1511:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1512hours into the same local hour then. In the Eastern example, UTC times of the
1513form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1514:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1515consider times in the "repeated hour" to be in standard time. This is easily
1516arranged, as in the example, by expressing DST switch times in the time zone's
1517standard local time.
1518
1519Applications that can't bear such ambiguities should avoid using hybrid
1520:class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any
1521other fixed-offset :class:`tzinfo` subclass (such as a class representing only
1522EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
Georg Brandl48310cd2009-01-03 21:18:54 +00001523
Georg Brandl116aa622007-08-15 14:28:22 +00001524
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001525.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00001526
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001527:meth:`strftime` and :meth:`strptime` Behavior
1528----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001529
1530:class:`date`, :class:`datetime`, and :class:`time` objects all support a
1531``strftime(format)`` method, to create a string representing the time under the
1532control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1533acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1534although not all objects support a :meth:`timetuple` method.
1535
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001536Conversely, the :meth:`datetime.strptime` class method creates a
1537:class:`datetime` object from a string representing a date and time and a
1538corresponding format string. ``datetime.strptime(date_string, format)`` is
1539equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1540
Georg Brandl116aa622007-08-15 14:28:22 +00001541For :class:`time` objects, the format codes for year, month, and day should not
1542be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001543is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00001544
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001545For :class:`date` objects, the format codes for hours, minutes, seconds, and
1546microseconds should not be used, as :class:`date` objects have no such
1547values. If they're used anyway, ``0`` is substituted for them.
1548
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001549For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1550strings.
1551
1552For an aware object:
1553
1554``%z``
1555 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1556 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1557 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1558 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1559 replaced with the string ``'-0330'``.
1560
1561``%Z``
1562 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1563 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl116aa622007-08-15 14:28:22 +00001564
Georg Brandl116aa622007-08-15 14:28:22 +00001565The full set of format codes supported varies across platforms, because Python
1566calls the platform C library's :func:`strftime` function, and platform
Georg Brandl48310cd2009-01-03 21:18:54 +00001567variations are common.
Christian Heimes895627f2007-12-08 17:28:33 +00001568
1569The following is a list of all the format codes that the C standard (1989
1570version) requires, and these work on all platforms with a standard C
1571implementation. Note that the 1999 version of the C standard added additional
1572format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001573
1574The exact range of years for which :meth:`strftime` works also varies across
1575platforms. Regardless of platform, years before 1900 cannot be used.
1576
Christian Heimes895627f2007-12-08 17:28:33 +00001577+-----------+--------------------------------+-------+
1578| Directive | Meaning | Notes |
1579+===========+================================+=======+
1580| ``%a`` | Locale's abbreviated weekday | |
1581| | name. | |
1582+-----------+--------------------------------+-------+
1583| ``%A`` | Locale's full weekday name. | |
1584+-----------+--------------------------------+-------+
1585| ``%b`` | Locale's abbreviated month | |
1586| | name. | |
1587+-----------+--------------------------------+-------+
1588| ``%B`` | Locale's full month name. | |
1589+-----------+--------------------------------+-------+
1590| ``%c`` | Locale's appropriate date and | |
1591| | time representation. | |
1592+-----------+--------------------------------+-------+
1593| ``%d`` | Day of the month as a decimal | |
1594| | number [01,31]. | |
1595+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001596| ``%f`` | Microsecond as a decimal | \(1) |
1597| | number [0,999999], zero-padded | |
1598| | on the left | |
1599+-----------+--------------------------------+-------+
Christian Heimes895627f2007-12-08 17:28:33 +00001600| ``%H`` | Hour (24-hour clock) as a | |
1601| | decimal number [00,23]. | |
1602+-----------+--------------------------------+-------+
1603| ``%I`` | Hour (12-hour clock) as a | |
1604| | decimal number [01,12]. | |
1605+-----------+--------------------------------+-------+
1606| ``%j`` | Day of the year as a decimal | |
1607| | number [001,366]. | |
1608+-----------+--------------------------------+-------+
1609| ``%m`` | Month as a decimal number | |
1610| | [01,12]. | |
1611+-----------+--------------------------------+-------+
1612| ``%M`` | Minute as a decimal number | |
1613| | [00,59]. | |
1614+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001615| ``%p`` | Locale's equivalent of either | \(2) |
Christian Heimes895627f2007-12-08 17:28:33 +00001616| | AM or PM. | |
1617+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001618| ``%S`` | Second as a decimal number | \(3) |
Christian Heimes895627f2007-12-08 17:28:33 +00001619| | [00,61]. | |
1620+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001621| ``%U`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001622| | (Sunday as the first day of | |
1623| | the week) as a decimal number | |
1624| | [00,53]. All days in a new | |
1625| | year preceding the first | |
1626| | Sunday are considered to be in | |
1627| | week 0. | |
1628+-----------+--------------------------------+-------+
1629| ``%w`` | Weekday as a decimal number | |
1630| | [0(Sunday),6]. | |
1631+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001632| ``%W`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001633| | (Monday as the first day of | |
1634| | the week) as a decimal number | |
1635| | [00,53]. All days in a new | |
1636| | year preceding the first | |
1637| | Monday are considered to be in | |
1638| | week 0. | |
1639+-----------+--------------------------------+-------+
1640| ``%x`` | Locale's appropriate date | |
1641| | representation. | |
1642+-----------+--------------------------------+-------+
1643| ``%X`` | Locale's appropriate time | |
1644| | representation. | |
1645+-----------+--------------------------------+-------+
1646| ``%y`` | Year without century as a | |
1647| | decimal number [00,99]. | |
1648+-----------+--------------------------------+-------+
1649| ``%Y`` | Year with century as a decimal | |
1650| | number. | |
1651+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001652| ``%z`` | UTC offset in the form +HHMM | \(5) |
Christian Heimes895627f2007-12-08 17:28:33 +00001653| | or -HHMM (empty string if the | |
1654| | the object is naive). | |
1655+-----------+--------------------------------+-------+
1656| ``%Z`` | Time zone name (empty string | |
1657| | if the object is naive). | |
1658+-----------+--------------------------------+-------+
1659| ``%%`` | A literal ``'%'`` character. | |
1660+-----------+--------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001661
Christian Heimes895627f2007-12-08 17:28:33 +00001662Notes:
1663
1664(1)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001665 When used with the :meth:`strptime` method, the ``%f`` directive
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001666 accepts from one to six digits and zero pads on the right. ``%f`` is
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001667 an extension to the set of format characters in the C standard (but
1668 implemented separately in datetime objects, and therefore always
1669 available).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001670
1671(2)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001672 When used with the :meth:`strptime` method, the ``%p`` directive only affects
Christian Heimes895627f2007-12-08 17:28:33 +00001673 the output hour field if the ``%I`` directive is used to parse the hour.
1674
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001675(3)
R. David Murraybd25d332009-04-02 04:50:03 +00001676 The range really is ``0`` to ``61``; according to the Posix standard this
1677 accounts for leap seconds and the (very rare) double leap seconds.
1678 The :mod:`time` module may produce and does accept leap seconds since
1679 it is based on the Posix standard, but the :mod:`datetime` module
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001680 does not accept leap seconds in :meth:`strptime` input nor will it
R. David Murraybd25d332009-04-02 04:50:03 +00001681 produce them in :func:`strftime` output.
Christian Heimes895627f2007-12-08 17:28:33 +00001682
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001683(4)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001684 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in
Christian Heimes895627f2007-12-08 17:28:33 +00001685 calculations when the day of the week and the year are specified.
1686
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001687(5)
Christian Heimes895627f2007-12-08 17:28:33 +00001688 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1689 ``%z`` is replaced with the string ``'-0330'``.