blob: 908a7920274e99901daa6953eeeadf223c1cd9aa [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`datetime` --- Basic date and time types
2=============================================
3
4.. module:: datetime
5 :synopsis: Basic date and time types.
6.. moduleauthor:: Tim Peters <tim@zope.com>
7.. sectionauthor:: Tim Peters <tim@zope.com>
8.. sectionauthor:: A.M. Kuchling <amk@amk.ca>
9
Christian Heimes5b5e81c2007-12-31 16:14:33 +000010.. XXX what order should the types be discussed in?
Georg Brandl116aa622007-08-15 14:28:22 +000011
Georg Brandl116aa622007-08-15 14:28:22 +000012The :mod:`datetime` module supplies classes for manipulating dates and times in
13both simple and complex ways. While date and time arithmetic is supported, the
14focus of the implementation is on efficient member extraction for output
15formatting and manipulation. For related
16functionality, see also the :mod:`time` and :mod:`calendar` modules.
17
18There are two kinds of date and time objects: "naive" and "aware". This
19distinction refers to whether the object has any notion of time zone, daylight
20saving time, or other kind of algorithmic or political time adjustment. Whether
21a naive :class:`datetime` object represents Coordinated Universal Time (UTC),
22local time, or time in some other timezone is purely up to the program, just
23like it's up to the program whether a particular number represents metres,
24miles, or mass. Naive :class:`datetime` objects are easy to understand and to
25work with, at the cost of ignoring some aspects of reality.
26
27For applications requiring more, :class:`datetime` and :class:`time` objects
28have an optional time zone information member, :attr:`tzinfo`, that can contain
29an instance of a subclass of the abstract :class:`tzinfo` class. These
30:class:`tzinfo` objects capture information about the offset from UTC time, the
31time zone name, and whether Daylight Saving Time is in effect. Note that no
32concrete :class:`tzinfo` classes are supplied by the :mod:`datetime` module.
33Supporting timezones at whatever level of detail is required is up to the
34application. The rules for time adjustment across the world are more political
35than rational, and there is no standard suitable for every application.
36
37The :mod:`datetime` module exports the following constants:
38
Georg Brandl116aa622007-08-15 14:28:22 +000039.. data:: MINYEAR
40
41 The smallest year number allowed in a :class:`date` or :class:`datetime` object.
42 :const:`MINYEAR` is ``1``.
43
44
45.. data:: MAXYEAR
46
47 The largest year number allowed in a :class:`date` or :class:`datetime` object.
48 :const:`MAXYEAR` is ``9999``.
49
50
51.. seealso::
52
53 Module :mod:`calendar`
54 General calendar related functions.
55
56 Module :mod:`time`
57 Time access and conversions.
58
59
60Available Types
61---------------
62
Georg Brandl116aa622007-08-15 14:28:22 +000063.. class:: date
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000064 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000065
66 An idealized naive date, assuming the current Gregorian calendar always was, and
67 always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and
68 :attr:`day`.
69
70
71.. class:: time
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000072 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000073
74 An idealized time, independent of any particular day, assuming that every day
75 has exactly 24\*60\*60 seconds (there is no notion of "leap seconds" here).
76 Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
77 and :attr:`tzinfo`.
78
79
80.. class:: datetime
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000081 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000082
83 A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`,
84 :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
85 and :attr:`tzinfo`.
86
87
88.. class:: timedelta
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000089 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000090
91 A duration expressing the difference between two :class:`date`, :class:`time`,
92 or :class:`datetime` instances to microsecond resolution.
93
94
95.. class:: tzinfo
96
97 An abstract base class for time zone information objects. These are used by the
98 :class:`datetime` and :class:`time` classes to provide a customizable notion of
99 time adjustment (for example, to account for time zone and/or daylight saving
100 time).
101
102Objects of these types are immutable.
103
104Objects of the :class:`date` type are always naive.
105
106An object *d* of type :class:`time` or :class:`datetime` may be naive or aware.
107*d* is aware if ``d.tzinfo`` is not ``None`` and ``d.tzinfo.utcoffset(d)`` does
108not return ``None``. If ``d.tzinfo`` is ``None``, or if ``d.tzinfo`` is not
109``None`` but ``d.tzinfo.utcoffset(d)`` returns ``None``, *d* is naive.
110
111The distinction between naive and aware doesn't apply to :class:`timedelta`
112objects.
113
114Subclass relationships::
115
116 object
117 timedelta
118 tzinfo
119 time
120 date
121 datetime
122
123
124.. _datetime-timedelta:
125
126:class:`timedelta` Objects
127--------------------------
128
129A :class:`timedelta` object represents a duration, the difference between two
130dates or times.
131
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000132.. class:: timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000133
Georg Brandl5c106642007-11-29 17:41:05 +0000134 All arguments are optional and default to ``0``. Arguments may be integers
Georg Brandl116aa622007-08-15 14:28:22 +0000135 or floats, and may be positive or negative.
136
137 Only *days*, *seconds* and *microseconds* are stored internally. Arguments are
138 converted to those units:
139
140 * A millisecond is converted to 1000 microseconds.
141 * A minute is converted to 60 seconds.
142 * An hour is converted to 3600 seconds.
143 * A week is converted to 7 days.
144
145 and days, seconds and microseconds are then normalized so that the
146 representation is unique, with
147
148 * ``0 <= microseconds < 1000000``
149 * ``0 <= seconds < 3600*24`` (the number of seconds in one day)
150 * ``-999999999 <= days <= 999999999``
151
152 If any argument is a float and there are fractional microseconds, the fractional
153 microseconds left over from all arguments are combined and their sum is rounded
154 to the nearest microsecond. If no argument is a float, the conversion and
155 normalization processes are exact (no information is lost).
156
157 If the normalized value of days lies outside the indicated range,
158 :exc:`OverflowError` is raised.
159
160 Note that normalization of negative values may be surprising at first. For
Christian Heimesfe337bf2008-03-23 21:54:12 +0000161 example,
Georg Brandl116aa622007-08-15 14:28:22 +0000162
Christian Heimes895627f2007-12-08 17:28:33 +0000163 >>> from datetime import timedelta
Georg Brandl116aa622007-08-15 14:28:22 +0000164 >>> d = timedelta(microseconds=-1)
165 >>> (d.days, d.seconds, d.microseconds)
166 (-1, 86399, 999999)
167
Georg Brandl116aa622007-08-15 14:28:22 +0000168
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000169Class attributes are:
Georg Brandl116aa622007-08-15 14:28:22 +0000170
171.. attribute:: timedelta.min
172
173 The most negative :class:`timedelta` object, ``timedelta(-999999999)``.
174
175
176.. attribute:: timedelta.max
177
178 The most positive :class:`timedelta` object, ``timedelta(days=999999999,
179 hours=23, minutes=59, seconds=59, microseconds=999999)``.
180
181
182.. attribute:: timedelta.resolution
183
184 The smallest possible difference between non-equal :class:`timedelta` objects,
185 ``timedelta(microseconds=1)``.
186
187Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``.
188``-timedelta.max`` is not representable as a :class:`timedelta` object.
189
190Instance attributes (read-only):
191
192+------------------+--------------------------------------------+
193| Attribute | Value |
194+==================+============================================+
195| ``days`` | Between -999999999 and 999999999 inclusive |
196+------------------+--------------------------------------------+
197| ``seconds`` | Between 0 and 86399 inclusive |
198+------------------+--------------------------------------------+
199| ``microseconds`` | Between 0 and 999999 inclusive |
200+------------------+--------------------------------------------+
201
202Supported operations:
203
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000204.. XXX this table is too wide!
Georg Brandl116aa622007-08-15 14:28:22 +0000205
206+--------------------------------+-----------------------------------------------+
207| Operation | Result |
208+================================+===============================================+
209| ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == |
210| | *t3* and *t1*-*t3* == *t2* are true. (1) |
211+--------------------------------+-----------------------------------------------+
212| ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* |
213| | == *t2* - *t3* and *t2* == *t1* + *t3* are |
214| | true. (1) |
215+--------------------------------+-----------------------------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000216| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer. |
Georg Brandl116aa622007-08-15 14:28:22 +0000217| | Afterwards *t1* // i == *t2* is true, |
218| | provided ``i != 0``. |
219+--------------------------------+-----------------------------------------------+
220| | In general, *t1* \* i == *t1* \* (i-1) + *t1* |
221| | is true. (1) |
222+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000223| ``f = t2 / t3`` | Division (3) of *t2* by *t3*. Returns a |
224| | :class:`float` object. |
225+--------------------------------+-----------------------------------------------+
226| ``t1 = t2 // i`` or | The floor is computed and the remainder (if |
227| ``t1 = t2 // t3`` | any) is thrown away. In the second case, an |
228| | integer is returned (3) |
229+--------------------------------+-----------------------------------------------+
230| ``t1 = t2 % t3`` | The remainder is computed as a |
231| | :class:`timedelta` object. (3) |
232+--------------------------------+-----------------------------------------------+
233| ``q, r = divmod(t1, t2)`` | Computes the quotient and the remainder: |
234| | ``q = t1 // t2`` (3) and ``r = t1 % t2``. |
235| | q is an integer and r is a :class:`timedelta` |
236| | object. |
Georg Brandl116aa622007-08-15 14:28:22 +0000237+--------------------------------+-----------------------------------------------+
238| ``+t1`` | Returns a :class:`timedelta` object with the |
239| | same value. (2) |
240+--------------------------------+-----------------------------------------------+
241| ``-t1`` | equivalent to :class:`timedelta`\ |
242| | (-*t1.days*, -*t1.seconds*, |
243| | -*t1.microseconds*), and to *t1*\* -1. (1)(4) |
244+--------------------------------+-----------------------------------------------+
Georg Brandl495f7b52009-10-27 15:28:25 +0000245| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, and|
Georg Brandl116aa622007-08-15 14:28:22 +0000246| | to -*t* when ``t.days < 0``. (2) |
247+--------------------------------+-----------------------------------------------+
248
249Notes:
250
251(1)
252 This is exact, but may overflow.
253
254(2)
255 This is exact, and cannot overflow.
256
257(3)
258 Division by 0 raises :exc:`ZeroDivisionError`.
259
260(4)
261 -*timedelta.max* is not representable as a :class:`timedelta` object.
262
263In addition to the operations listed above :class:`timedelta` objects support
264certain additions and subtractions with :class:`date` and :class:`datetime`
265objects (see below).
266
Mark Dickinson7c186e22010-04-20 22:32:49 +0000267.. versionadded:: 3.2
268 Floor division and true division of a :class:`timedelta` object by
269 another :class:`timedelta` object are now supported, as are
270 remainder operations and the :func:`divmod` function.
271
272
Georg Brandl116aa622007-08-15 14:28:22 +0000273Comparisons of :class:`timedelta` objects are supported with the
274:class:`timedelta` object representing the smaller duration considered to be the
275smaller timedelta. In order to stop mixed-type comparisons from falling back to
276the default comparison by object address, when a :class:`timedelta` object is
277compared to an object of a different type, :exc:`TypeError` is raised unless the
278comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
279:const:`True`, respectively.
280
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000281:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl116aa622007-08-15 14:28:22 +0000282efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
283considered to be true if and only if it isn't equal to ``timedelta(0)``.
284
Antoine Pitroube6859d2009-11-25 23:02:32 +0000285Instance methods:
286
287.. method:: timedelta.total_seconds()
288
289 Return the total number of seconds contained in the duration. Equivalent to
Mark Dickinson0381e3f2010-05-08 14:35:02 +0000290 ``td / timedelta(seconds=1)``.
291
292 Note that for very large time intervals (greater than 270 years on
293 most platforms) this method will lose microsecond accuracy.
Antoine Pitroube6859d2009-11-25 23:02:32 +0000294
295 .. versionadded:: 3.2
296
297
Christian Heimesfe337bf2008-03-23 21:54:12 +0000298Example usage:
Georg Brandl48310cd2009-01-03 21:18:54 +0000299
Christian Heimes895627f2007-12-08 17:28:33 +0000300 >>> from datetime import timedelta
301 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000302 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Christian Heimes895627f2007-12-08 17:28:33 +0000303 ... minutes=50, seconds=600) # adds up to 365 days
Antoine Pitroube6859d2009-11-25 23:02:32 +0000304 >>> year.total_seconds()
305 31536000.0
Christian Heimes895627f2007-12-08 17:28:33 +0000306 >>> year == another_year
307 True
308 >>> ten_years = 10 * year
309 >>> ten_years, ten_years.days // 365
310 (datetime.timedelta(3650), 10)
311 >>> nine_years = ten_years - year
312 >>> nine_years, nine_years.days // 365
313 (datetime.timedelta(3285), 9)
314 >>> three_years = nine_years // 3;
315 >>> three_years, three_years.days // 365
316 (datetime.timedelta(1095), 3)
317 >>> abs(three_years - ten_years) == 2 * three_years + year
318 True
319
Georg Brandl116aa622007-08-15 14:28:22 +0000320
321.. _datetime-date:
322
323:class:`date` Objects
324---------------------
325
326A :class:`date` object represents a date (year, month and day) in an idealized
327calendar, the current Gregorian calendar indefinitely extended in both
328directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
329called day number 2, and so on. This matches the definition of the "proleptic
330Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
331where it's the base calendar for all computations. See the book for algorithms
332for converting between proleptic Gregorian ordinals and many other calendar
333systems.
334
335
336.. class:: date(year, month, day)
337
Georg Brandl5c106642007-11-29 17:41:05 +0000338 All arguments are required. Arguments may be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000339 ranges:
340
341 * ``MINYEAR <= year <= MAXYEAR``
342 * ``1 <= month <= 12``
343 * ``1 <= day <= number of days in the given month and year``
344
345 If an argument outside those ranges is given, :exc:`ValueError` is raised.
346
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000347
Georg Brandl116aa622007-08-15 14:28:22 +0000348Other constructors, all class methods:
349
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000350.. classmethod:: date.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000351
352 Return the current local date. This is equivalent to
353 ``date.fromtimestamp(time.time())``.
354
355
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000356.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000357
358 Return the local date corresponding to the POSIX timestamp, such as is returned
359 by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out
360 of the range of values supported by the platform C :cfunc:`localtime` function.
361 It's common for this to be restricted to years from 1970 through 2038. Note
362 that on non-POSIX systems that include leap seconds in their notion of a
363 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
364
365
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000366.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000367
368 Return the date corresponding to the proleptic Gregorian ordinal, where January
369 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
370 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
371 d``.
372
Georg Brandl116aa622007-08-15 14:28:22 +0000373
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000374Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000375
376.. attribute:: date.min
377
378 The earliest representable date, ``date(MINYEAR, 1, 1)``.
379
380
381.. attribute:: date.max
382
383 The latest representable date, ``date(MAXYEAR, 12, 31)``.
384
385
386.. attribute:: date.resolution
387
388 The smallest possible difference between non-equal date objects,
389 ``timedelta(days=1)``.
390
Georg Brandl116aa622007-08-15 14:28:22 +0000391
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000392Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000393
394.. attribute:: date.year
395
396 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
397
398
399.. attribute:: date.month
400
401 Between 1 and 12 inclusive.
402
403
404.. attribute:: date.day
405
406 Between 1 and the number of days in the given month of the given year.
407
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000408
Georg Brandl116aa622007-08-15 14:28:22 +0000409Supported operations:
410
411+-------------------------------+----------------------------------------------+
412| Operation | Result |
413+===============================+==============================================+
414| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
415| | from *date1*. (1) |
416+-------------------------------+----------------------------------------------+
417| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
418| | timedelta == date1``. (2) |
419+-------------------------------+----------------------------------------------+
420| ``timedelta = date1 - date2`` | \(3) |
421+-------------------------------+----------------------------------------------+
422| ``date1 < date2`` | *date1* is considered less than *date2* when |
423| | *date1* precedes *date2* in time. (4) |
424+-------------------------------+----------------------------------------------+
425
426Notes:
427
428(1)
429 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
430 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
431 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
432 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
433 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
434
435(2)
436 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
437 isolation can overflow in cases where date1 - timedelta does not.
438 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
439
440(3)
441 This is exact, and cannot overflow. timedelta.seconds and
442 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
443
444(4)
445 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
446 date2.toordinal()``. In order to stop comparison from falling back to the
447 default scheme of comparing object addresses, date comparison normally raises
448 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
449 However, ``NotImplemented`` is returned instead if the other comparand has a
450 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
451 chance at implementing mixed-type comparison. If not, when a :class:`date`
452 object is compared to an object of a different type, :exc:`TypeError` is raised
453 unless the comparison is ``==`` or ``!=``. The latter cases return
454 :const:`False` or :const:`True`, respectively.
455
456Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
457objects are considered to be true.
458
459Instance methods:
460
Georg Brandl116aa622007-08-15 14:28:22 +0000461.. method:: date.replace(year, month, day)
462
463 Return a date with the same value, except for those members given new values by
464 whichever keyword arguments are specified. For example, if ``d == date(2002,
465 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
466
467
468.. method:: date.timetuple()
469
470 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
471 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
472 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
473 d.weekday(), d.toordinal() - date(d.year, 1, 1).toordinal() + 1, -1))``
474
475
476.. method:: date.toordinal()
477
478 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
479 has ordinal 1. For any :class:`date` object *d*,
480 ``date.fromordinal(d.toordinal()) == d``.
481
482
483.. method:: date.weekday()
484
485 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
486 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
487 :meth:`isoweekday`.
488
489
490.. method:: date.isoweekday()
491
492 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
493 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
494 :meth:`weekday`, :meth:`isocalendar`.
495
496
497.. method:: date.isocalendar()
498
499 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
500
501 The ISO calendar is a widely used variant of the Gregorian calendar. See
Mark Dickinsonf964ac22009-11-03 16:29:10 +0000502 http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
503 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000504
505 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
506 Monday and ends on a Sunday. The first week of an ISO year is the first
507 (Gregorian) calendar week of a year containing a Thursday. This is called week
508 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
509
510 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
511 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
512 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
513 4).isocalendar() == (2004, 1, 7)``.
514
515
516.. method:: date.isoformat()
517
518 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
519 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
520
521
522.. method:: date.__str__()
523
524 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
525
526
527.. method:: date.ctime()
528
529 Return a string representing the date, for example ``date(2002, 12,
530 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
531 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
532 :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
533 :meth:`date.ctime` does not invoke) conforms to the C standard.
534
535
536.. method:: date.strftime(format)
537
538 Return a string representing the date, controlled by an explicit format string.
539 Format codes referring to hours, minutes or seconds will see 0 values. See
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000540 section :ref:`strftime-strptime-behavior`.
541
Georg Brandl116aa622007-08-15 14:28:22 +0000542
Christian Heimes895627f2007-12-08 17:28:33 +0000543Example of counting days to an event::
544
545 >>> import time
546 >>> from datetime import date
547 >>> today = date.today()
548 >>> today
549 datetime.date(2007, 12, 5)
550 >>> today == date.fromtimestamp(time.time())
551 True
552 >>> my_birthday = date(today.year, 6, 24)
553 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000554 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000555 >>> my_birthday
556 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000557 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000558 >>> time_to_birthday.days
559 202
560
Christian Heimesfe337bf2008-03-23 21:54:12 +0000561Example of working with :class:`date`:
562
563.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000564
565 >>> from datetime import date
566 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
567 >>> d
568 datetime.date(2002, 3, 11)
569 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000570 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000571 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000572 2002 # year
573 3 # month
574 11 # day
575 0
576 0
577 0
578 0 # weekday (0 = Monday)
579 70 # 70th day in the year
580 -1
581 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000582 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000583 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000584 2002 # ISO year
585 11 # ISO week number
586 1 # ISO day number ( 1 = Monday )
587 >>> d.isoformat()
588 '2002-03-11'
589 >>> d.strftime("%d/%m/%y")
590 '11/03/02'
591 >>> d.strftime("%A %d. %B %Y")
592 'Monday 11. March 2002'
593
Georg Brandl116aa622007-08-15 14:28:22 +0000594
595.. _datetime-datetime:
596
597:class:`datetime` Objects
598-------------------------
599
600A :class:`datetime` object is a single object containing all the information
601from a :class:`date` object and a :class:`time` object. Like a :class:`date`
602object, :class:`datetime` assumes the current Gregorian calendar extended in
603both directions; like a time object, :class:`datetime` assumes there are exactly
6043600\*24 seconds in every day.
605
606Constructor:
607
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000608.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000609
610 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000611 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
612 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000613
614 * ``MINYEAR <= year <= MAXYEAR``
615 * ``1 <= month <= 12``
616 * ``1 <= day <= number of days in the given month and year``
617 * ``0 <= hour < 24``
618 * ``0 <= minute < 60``
619 * ``0 <= second < 60``
620 * ``0 <= microsecond < 1000000``
621
622 If an argument outside those ranges is given, :exc:`ValueError` is raised.
623
624Other constructors, all class methods:
625
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000626.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000627
628 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
629 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
630 :meth:`fromtimestamp`.
631
632
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000633.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000634
635 Return the current local date and time. If optional argument *tz* is ``None``
636 or not specified, this is like :meth:`today`, but, if possible, supplies more
637 precision than can be gotten from going through a :func:`time.time` timestamp
638 (for example, this may be possible on platforms supplying the C
639 :cfunc:`gettimeofday` function).
640
641 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
642 current date and time are converted to *tz*'s time zone. In this case the
643 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
644 See also :meth:`today`, :meth:`utcnow`.
645
646
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000647.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000648
649 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
650 :meth:`now`, but returns the current UTC date and time, as a naive
651 :class:`datetime` object. See also :meth:`now`.
652
653
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000654.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000655
656 Return the local date and time corresponding to the POSIX timestamp, such as is
657 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
658 specified, the timestamp is converted to the platform's local date and time, and
659 the returned :class:`datetime` object is naive.
660
661 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
662 timestamp is converted to *tz*'s time zone. In this case the result is
663 equivalent to
664 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
665
666 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
667 the range of values supported by the platform C :cfunc:`localtime` or
668 :cfunc:`gmtime` functions. It's common for this to be restricted to years in
669 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
670 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
671 and then it's possible to have two timestamps differing by a second that yield
672 identical :class:`datetime` objects. See also :meth:`utcfromtimestamp`.
673
674
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000675.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000676
677 Return the UTC :class:`datetime` corresponding to the POSIX timestamp, with
678 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
679 out of the range of values supported by the platform C :cfunc:`gmtime` function.
680 It's common for this to be restricted to years in 1970 through 2038. See also
681 :meth:`fromtimestamp`.
682
683
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000684.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000685
686 Return the :class:`datetime` corresponding to the proleptic Gregorian ordinal,
687 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
688 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
689 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
690
691
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000692.. classmethod:: datetime.combine(date, time)
Georg Brandl116aa622007-08-15 14:28:22 +0000693
694 Return a new :class:`datetime` object whose date members are equal to the given
695 :class:`date` object's, and whose time and :attr:`tzinfo` members are equal to
696 the given :class:`time` object's. For any :class:`datetime` object *d*, ``d ==
697 datetime.combine(d.date(), d.timetz())``. If date is a :class:`datetime`
698 object, its time and :attr:`tzinfo` members are ignored.
699
700
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000701.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000702
703 Return a :class:`datetime` corresponding to *date_string*, parsed according to
704 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
705 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
706 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 +0000707 time tuple. See section :ref:`strftime-strptime-behavior`.
708
Georg Brandl116aa622007-08-15 14:28:22 +0000709
Georg Brandl116aa622007-08-15 14:28:22 +0000710
711Class attributes:
712
Georg Brandl116aa622007-08-15 14:28:22 +0000713.. attribute:: datetime.min
714
715 The earliest representable :class:`datetime`, ``datetime(MINYEAR, 1, 1,
716 tzinfo=None)``.
717
718
719.. attribute:: datetime.max
720
721 The latest representable :class:`datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
722 59, 999999, tzinfo=None)``.
723
724
725.. attribute:: datetime.resolution
726
727 The smallest possible difference between non-equal :class:`datetime` objects,
728 ``timedelta(microseconds=1)``.
729
Georg Brandl116aa622007-08-15 14:28:22 +0000730
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000731Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000732
733.. attribute:: datetime.year
734
735 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
736
737
738.. attribute:: datetime.month
739
740 Between 1 and 12 inclusive.
741
742
743.. attribute:: datetime.day
744
745 Between 1 and the number of days in the given month of the given year.
746
747
748.. attribute:: datetime.hour
749
750 In ``range(24)``.
751
752
753.. attribute:: datetime.minute
754
755 In ``range(60)``.
756
757
758.. attribute:: datetime.second
759
760 In ``range(60)``.
761
762
763.. attribute:: datetime.microsecond
764
765 In ``range(1000000)``.
766
767
768.. attribute:: datetime.tzinfo
769
770 The object passed as the *tzinfo* argument to the :class:`datetime` constructor,
771 or ``None`` if none was passed.
772
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000773
Georg Brandl116aa622007-08-15 14:28:22 +0000774Supported operations:
775
776+---------------------------------------+-------------------------------+
777| Operation | Result |
778+=======================================+===============================+
779| ``datetime2 = datetime1 + timedelta`` | \(1) |
780+---------------------------------------+-------------------------------+
781| ``datetime2 = datetime1 - timedelta`` | \(2) |
782+---------------------------------------+-------------------------------+
783| ``timedelta = datetime1 - datetime2`` | \(3) |
784+---------------------------------------+-------------------------------+
785| ``datetime1 < datetime2`` | Compares :class:`datetime` to |
786| | :class:`datetime`. (4) |
787+---------------------------------------+-------------------------------+
788
789(1)
790 datetime2 is a duration of timedelta removed from datetime1, moving forward in
791 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
792 result has the same :attr:`tzinfo` member as the input datetime, and datetime2 -
793 datetime1 == timedelta after. :exc:`OverflowError` is raised if datetime2.year
794 would be smaller than :const:`MINYEAR` or larger than :const:`MAXYEAR`. Note
795 that no time zone adjustments are done even if the input is an aware object.
796
797(2)
798 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
799 addition, the result has the same :attr:`tzinfo` member as the input datetime,
800 and no time zone adjustments are done even if the input is aware. This isn't
801 quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation
802 can overflow in cases where datetime1 - timedelta does not.
803
804(3)
805 Subtraction of a :class:`datetime` from a :class:`datetime` is defined only if
806 both operands are naive, or if both are aware. If one is aware and the other is
807 naive, :exc:`TypeError` is raised.
808
809 If both are naive, or both are aware and have the same :attr:`tzinfo` member,
810 the :attr:`tzinfo` members are ignored, and the result is a :class:`timedelta`
811 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
812 are done in this case.
813
814 If both are aware and have different :attr:`tzinfo` members, ``a-b`` acts as if
815 *a* and *b* were first converted to naive UTC datetimes first. The result is
816 ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) -
817 b.utcoffset())`` except that the implementation never overflows.
818
819(4)
820 *datetime1* is considered less than *datetime2* when *datetime1* precedes
821 *datetime2* in time.
822
823 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
824 If both comparands are aware, and have the same :attr:`tzinfo` member, the
825 common :attr:`tzinfo` member is ignored and the base datetimes are compared. If
826 both comparands are aware and have different :attr:`tzinfo` members, the
827 comparands are first adjusted by subtracting their UTC offsets (obtained from
828 ``self.utcoffset()``).
829
830 .. note::
831
832 In order to stop comparison from falling back to the default scheme of comparing
833 object addresses, datetime comparison normally raises :exc:`TypeError` if the
834 other comparand isn't also a :class:`datetime` object. However,
835 ``NotImplemented`` is returned instead if the other comparand has a
836 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
837 chance at implementing mixed-type comparison. If not, when a :class:`datetime`
838 object is compared to an object of a different type, :exc:`TypeError` is raised
839 unless the comparison is ``==`` or ``!=``. The latter cases return
840 :const:`False` or :const:`True`, respectively.
841
842:class:`datetime` objects can be used as dictionary keys. In Boolean contexts,
843all :class:`datetime` objects are considered to be true.
844
845Instance methods:
846
Georg Brandl116aa622007-08-15 14:28:22 +0000847.. method:: datetime.date()
848
849 Return :class:`date` object with same year, month and day.
850
851
852.. method:: datetime.time()
853
854 Return :class:`time` object with same hour, minute, second and microsecond.
855 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
856
857
858.. method:: datetime.timetz()
859
860 Return :class:`time` object with same hour, minute, second, microsecond, and
861 tzinfo members. See also method :meth:`time`.
862
863
864.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
865
866 Return a datetime with the same members, except for those members given new
867 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
868 can be specified to create a naive datetime from an aware datetime with no
869 conversion of date and time members.
870
871
872.. method:: datetime.astimezone(tz)
873
874 Return a :class:`datetime` object with new :attr:`tzinfo` member *tz*, adjusting
875 the date and time members so the result is the same UTC time as *self*, but in
876 *tz*'s local time.
877
878 *tz* must be an instance of a :class:`tzinfo` subclass, and its
879 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
880 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
881 not return ``None``).
882
883 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
884 adjustment of date or time members is performed. Else the result is local time
885 in time zone *tz*, representing the same UTC time as *self*: after ``astz =
886 dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have the same date
887 and time members as ``dt - dt.utcoffset()``. The discussion of class
888 :class:`tzinfo` explains the cases at Daylight Saving Time transition boundaries
889 where this cannot be achieved (an issue only if *tz* models both standard and
890 daylight time).
891
892 If you merely want to attach a time zone object *tz* to a datetime *dt* without
893 adjustment of date and time members, use ``dt.replace(tzinfo=tz)``. If you
894 merely want to remove the time zone object from an aware datetime *dt* without
895 conversion of date and time members, use ``dt.replace(tzinfo=None)``.
896
897 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
898 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
899 Ignoring error cases, :meth:`astimezone` acts like::
900
901 def astimezone(self, tz):
902 if self.tzinfo is tz:
903 return self
904 # Convert self to UTC, and attach the new time zone object.
905 utc = (self - self.utcoffset()).replace(tzinfo=tz)
906 # Convert from UTC to tz's local time.
907 return tz.fromutc(utc)
908
909
910.. method:: datetime.utcoffset()
911
912 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
913 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
914 return ``None``, or a :class:`timedelta` object representing a whole number of
915 minutes with magnitude less than one day.
916
917
918.. method:: datetime.dst()
919
920 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
921 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
922 ``None``, or a :class:`timedelta` object representing a whole number of minutes
923 with magnitude less than one day.
924
925
926.. method:: datetime.tzname()
927
928 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
929 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
930 ``None`` or a string object,
931
932
933.. method:: datetime.timetuple()
934
935 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
936 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
937 d.hour, d.minute, d.second, d.weekday(), d.toordinal() - date(d.year, 1,
938 1).toordinal() + 1, dst))`` The :attr:`tm_isdst` flag of the result is set
939 according to the :meth:`dst` method: :attr:`tzinfo` is ``None`` or :meth:`dst`
940 returns ``None``, :attr:`tm_isdst` is set to ``-1``; else if :meth:`dst`
941 returns a non-zero value, :attr:`tm_isdst` is set to ``1``; else ``tm_isdst`` is
942 set to ``0``.
943
944
945.. method:: datetime.utctimetuple()
946
947 If :class:`datetime` instance *d* is naive, this is the same as
948 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
949 ``d.dst()`` returns. DST is never in effect for a UTC time.
950
951 If *d* is aware, *d* is normalized to UTC time, by subtracting
952 ``d.utcoffset()``, and a :class:`time.struct_time` for the normalized time is
953 returned. :attr:`tm_isdst` is forced to 0. Note that the result's
954 :attr:`tm_year` member may be :const:`MINYEAR`\ -1 or :const:`MAXYEAR`\ +1, if
955 *d*.year was ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
956 boundary.
957
958
959.. method:: datetime.toordinal()
960
961 Return the proleptic Gregorian ordinal of the date. The same as
962 ``self.date().toordinal()``.
963
964
965.. method:: datetime.weekday()
966
967 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
968 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
969
970
971.. method:: datetime.isoweekday()
972
973 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
974 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
975 :meth:`isocalendar`.
976
977
978.. method:: datetime.isocalendar()
979
980 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
981 ``self.date().isocalendar()``.
982
983
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000984.. method:: datetime.isoformat(sep='T')
Georg Brandl116aa622007-08-15 14:28:22 +0000985
986 Return a string representing the date and time in ISO 8601 format,
987 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
988 YYYY-MM-DDTHH:MM:SS
989
990 If :meth:`utcoffset` does not return ``None``, a 6-character string is
991 appended, giving the UTC offset in (signed) hours and minutes:
992 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
993 YYYY-MM-DDTHH:MM:SS+HH:MM
994
995 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000996 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +0000997
998 >>> from datetime import tzinfo, timedelta, datetime
999 >>> class TZ(tzinfo):
1000 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1001 ...
1002 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1003 '2002-12-25 00:00:00-06:39'
1004
1005
1006.. method:: datetime.__str__()
1007
1008 For a :class:`datetime` instance *d*, ``str(d)`` is equivalent to
1009 ``d.isoformat(' ')``.
1010
1011
1012.. method:: datetime.ctime()
1013
1014 Return a string representing the date and time, for example ``datetime(2002, 12,
1015 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1016 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
1017 native C :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
1018 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1019
1020
1021.. method:: datetime.strftime(format)
1022
1023 Return a string representing the date and time, controlled by an explicit format
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001024 string. See section :ref:`strftime-strptime-behavior`.
1025
Georg Brandl116aa622007-08-15 14:28:22 +00001026
Christian Heimesfe337bf2008-03-23 21:54:12 +00001027Examples of working with datetime objects:
1028
1029.. doctest::
1030
Christian Heimes895627f2007-12-08 17:28:33 +00001031 >>> from datetime import datetime, date, time
1032 >>> # Using datetime.combine()
1033 >>> d = date(2005, 7, 14)
1034 >>> t = time(12, 30)
1035 >>> datetime.combine(d, t)
1036 datetime.datetime(2005, 7, 14, 12, 30)
1037 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001038 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001039 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001040 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001041 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1042 >>> # Using datetime.strptime()
1043 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1044 >>> dt
1045 datetime.datetime(2006, 11, 21, 16, 30)
1046 >>> # Using datetime.timetuple() to get tuple of all attributes
1047 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001048 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001049 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001050 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001051 2006 # year
1052 11 # month
1053 21 # day
1054 16 # hour
1055 30 # minute
1056 0 # second
1057 1 # weekday (0 = Monday)
1058 325 # number of days since 1st January
1059 -1 # dst - method tzinfo.dst() returned None
1060 >>> # Date in ISO format
1061 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001062 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001063 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001064 ...
1065 2006 # ISO year
1066 47 # ISO week
1067 2 # ISO weekday
1068 >>> # Formatting datetime
1069 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1070 'Tuesday, 21. November 2006 04:30PM'
1071
Christian Heimesfe337bf2008-03-23 21:54:12 +00001072Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001073
1074 >>> from datetime import timedelta, datetime, tzinfo
1075 >>> class GMT1(tzinfo):
1076 ... def __init__(self): # DST starts last Sunday in March
1077 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1078 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001079 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001080 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1081 ... def utcoffset(self, dt):
1082 ... return timedelta(hours=1) + self.dst(dt)
Georg Brandl48310cd2009-01-03 21:18:54 +00001083 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001084 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1085 ... return timedelta(hours=1)
1086 ... else:
1087 ... return timedelta(0)
1088 ... def tzname(self,dt):
1089 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001090 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001091 >>> class GMT2(tzinfo):
1092 ... def __init__(self):
Georg Brandl48310cd2009-01-03 21:18:54 +00001093 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001094 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001095 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001096 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1097 ... def utcoffset(self, dt):
1098 ... return timedelta(hours=1) + self.dst(dt)
1099 ... def dst(self, dt):
1100 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1101 ... return timedelta(hours=2)
1102 ... else:
1103 ... return timedelta(0)
1104 ... def tzname(self,dt):
1105 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001106 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001107 >>> gmt1 = GMT1()
1108 >>> # Daylight Saving Time
1109 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1110 >>> dt1.dst()
1111 datetime.timedelta(0)
1112 >>> dt1.utcoffset()
1113 datetime.timedelta(0, 3600)
1114 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1115 >>> dt2.dst()
1116 datetime.timedelta(0, 3600)
1117 >>> dt2.utcoffset()
1118 datetime.timedelta(0, 7200)
1119 >>> # Convert datetime to another time zone
1120 >>> dt3 = dt2.astimezone(GMT2())
1121 >>> dt3 # doctest: +ELLIPSIS
1122 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1123 >>> dt2 # doctest: +ELLIPSIS
1124 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1125 >>> dt2.utctimetuple() == dt3.utctimetuple()
1126 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001127
Christian Heimes895627f2007-12-08 17:28:33 +00001128
Georg Brandl116aa622007-08-15 14:28:22 +00001129
1130.. _datetime-time:
1131
1132:class:`time` Objects
1133---------------------
1134
1135A time object represents a (local) time of day, independent of any particular
1136day, and subject to adjustment via a :class:`tzinfo` object.
1137
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001138.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001139
1140 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001141 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001142 following ranges:
1143
1144 * ``0 <= hour < 24``
1145 * ``0 <= minute < 60``
1146 * ``0 <= second < 60``
1147 * ``0 <= microsecond < 1000000``.
1148
1149 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1150 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1151
1152Class attributes:
1153
1154
1155.. attribute:: time.min
1156
1157 The earliest representable :class:`time`, ``time(0, 0, 0, 0)``.
1158
1159
1160.. attribute:: time.max
1161
1162 The latest representable :class:`time`, ``time(23, 59, 59, 999999)``.
1163
1164
1165.. attribute:: time.resolution
1166
1167 The smallest possible difference between non-equal :class:`time` objects,
1168 ``timedelta(microseconds=1)``, although note that arithmetic on :class:`time`
1169 objects is not supported.
1170
Georg Brandl116aa622007-08-15 14:28:22 +00001171
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001172Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001173
1174.. attribute:: time.hour
1175
1176 In ``range(24)``.
1177
1178
1179.. attribute:: time.minute
1180
1181 In ``range(60)``.
1182
1183
1184.. attribute:: time.second
1185
1186 In ``range(60)``.
1187
1188
1189.. attribute:: time.microsecond
1190
1191 In ``range(1000000)``.
1192
1193
1194.. attribute:: time.tzinfo
1195
1196 The object passed as the tzinfo argument to the :class:`time` constructor, or
1197 ``None`` if none was passed.
1198
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001199
Georg Brandl116aa622007-08-15 14:28:22 +00001200Supported operations:
1201
1202* comparison of :class:`time` to :class:`time`, where *a* is considered less
1203 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1204 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
1205 the same :attr:`tzinfo` member, the common :attr:`tzinfo` member is ignored and
1206 the base times are compared. If both comparands are aware and have different
1207 :attr:`tzinfo` members, the comparands are first adjusted by subtracting their
1208 UTC offsets (obtained from ``self.utcoffset()``). In order to stop mixed-type
1209 comparisons from falling back to the default comparison by object address, when
1210 a :class:`time` object is compared to an object of a different type,
1211 :exc:`TypeError` is raised unless the comparison is ``==`` or ``!=``. The
1212 latter cases return :const:`False` or :const:`True`, respectively.
1213
1214* hash, use as dict key
1215
1216* efficient pickling
1217
1218* in Boolean contexts, a :class:`time` object is considered to be true if and
1219 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1220 ``0`` if that's ``None``), the result is non-zero.
1221
Georg Brandl116aa622007-08-15 14:28:22 +00001222
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001223Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001224
1225.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1226
1227 Return a :class:`time` with the same value, except for those members given new
1228 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
1229 can be specified to create a naive :class:`time` from an aware :class:`time`,
1230 without conversion of the time members.
1231
1232
1233.. method:: time.isoformat()
1234
1235 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1236 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1237 6-character string is appended, giving the UTC offset in (signed) hours and
1238 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1239
1240
1241.. method:: time.__str__()
1242
1243 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1244
1245
1246.. method:: time.strftime(format)
1247
1248 Return a string representing the time, controlled by an explicit format string.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001249 See section :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001250
1251
1252.. method:: time.utcoffset()
1253
1254 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1255 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1256 return ``None`` or a :class:`timedelta` object representing a whole number of
1257 minutes with magnitude less than one day.
1258
1259
1260.. method:: time.dst()
1261
1262 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1263 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1264 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1265 with magnitude less than one day.
1266
1267
1268.. method:: time.tzname()
1269
1270 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1271 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1272 return ``None`` or a string object.
1273
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001274
Christian Heimesfe337bf2008-03-23 21:54:12 +00001275Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001276
Christian Heimes895627f2007-12-08 17:28:33 +00001277 >>> from datetime import time, tzinfo
1278 >>> class GMT1(tzinfo):
1279 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001280 ... return timedelta(hours=1)
1281 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001282 ... return timedelta(0)
1283 ... def tzname(self,dt):
1284 ... return "Europe/Prague"
1285 ...
1286 >>> t = time(12, 10, 30, tzinfo=GMT1())
1287 >>> t # doctest: +ELLIPSIS
1288 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1289 >>> gmt = GMT1()
1290 >>> t.isoformat()
1291 '12:10:30+01:00'
1292 >>> t.dst()
1293 datetime.timedelta(0)
1294 >>> t.tzname()
1295 'Europe/Prague'
1296 >>> t.strftime("%H:%M:%S %Z")
1297 '12:10:30 Europe/Prague'
1298
Georg Brandl116aa622007-08-15 14:28:22 +00001299
1300.. _datetime-tzinfo:
1301
1302:class:`tzinfo` Objects
1303-----------------------
1304
Brett Cannone1327f72009-01-29 04:10:21 +00001305:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001306instantiated directly. You need to derive a concrete subclass, and (at least)
1307supply implementations of the standard :class:`tzinfo` methods needed by the
1308:class:`datetime` methods you use. The :mod:`datetime` module does not supply
1309any concrete subclasses of :class:`tzinfo`.
1310
1311An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1312constructors for :class:`datetime` and :class:`time` objects. The latter objects
1313view their members as being in local time, and the :class:`tzinfo` object
1314supports methods revealing offset of local time from UTC, the name of the time
1315zone, and DST offset, all relative to a date or time object passed to them.
1316
1317Special requirement for pickling: A :class:`tzinfo` subclass must have an
1318:meth:`__init__` method that can be called with no arguments, else it can be
1319pickled but possibly not unpickled again. This is a technical requirement that
1320may be relaxed in the future.
1321
1322A concrete subclass of :class:`tzinfo` may need to implement the following
1323methods. Exactly which methods are needed depends on the uses made of aware
1324:mod:`datetime` objects. If in doubt, simply implement all of them.
1325
1326
1327.. method:: tzinfo.utcoffset(self, dt)
1328
1329 Return offset of local time from UTC, in minutes east of UTC. If local time is
1330 west of UTC, this should be negative. Note that this is intended to be the
1331 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1332 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1333 the UTC offset isn't known, return ``None``. Else the value returned must be a
1334 :class:`timedelta` object specifying a whole number of minutes in the range
1335 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1336 than one day). Most implementations of :meth:`utcoffset` will probably look
1337 like one of these two::
1338
1339 return CONSTANT # fixed-offset class
1340 return CONSTANT + self.dst(dt) # daylight-aware class
1341
1342 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1343 ``None`` either.
1344
1345 The default implementation of :meth:`utcoffset` raises
1346 :exc:`NotImplementedError`.
1347
1348
1349.. method:: tzinfo.dst(self, dt)
1350
1351 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1352 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1353 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1354 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1355 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1356 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1357 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
1358 member's :meth:`dst` method to determine how the :attr:`tm_isdst` flag should be
1359 set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for DST changes
1360 when crossing time zones.
1361
1362 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1363 daylight times must be consistent in this sense:
1364
1365 ``tz.utcoffset(dt) - tz.dst(dt)``
1366
1367 must return the same result for every :class:`datetime` *dt* with ``dt.tzinfo ==
1368 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1369 zone's "standard offset", which should not depend on the date or the time, but
1370 only on geographic location. The implementation of :meth:`datetime.astimezone`
1371 relies on this, but cannot detect violations; it's the programmer's
1372 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1373 this, it may be able to override the default implementation of
1374 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1375
1376 Most implementations of :meth:`dst` will probably look like one of these two::
1377
1378 def dst(self):
1379 # a fixed-offset class: doesn't account for DST
1380 return timedelta(0)
1381
1382 or ::
1383
1384 def dst(self):
1385 # Code to set dston and dstoff to the time zone's DST
1386 # transition times based on the input dt.year, and expressed
1387 # in standard local time. Then
1388
1389 if dston <= dt.replace(tzinfo=None) < dstoff:
1390 return timedelta(hours=1)
1391 else:
1392 return timedelta(0)
1393
1394 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1395
1396
1397.. method:: tzinfo.tzname(self, dt)
1398
1399 Return the time zone name corresponding to the :class:`datetime` object *dt*, as
1400 a string. Nothing about string names is defined by the :mod:`datetime` module,
1401 and there's no requirement that it mean anything in particular. For example,
1402 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1403 valid replies. Return ``None`` if a string name isn't known. Note that this is
1404 a method rather than a fixed string primarily because some :class:`tzinfo`
1405 subclasses will wish to return different names depending on the specific value
1406 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1407 daylight time.
1408
1409 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1410
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001411
Georg Brandl116aa622007-08-15 14:28:22 +00001412These methods are called by a :class:`datetime` or :class:`time` object, in
1413response to their methods of the same names. A :class:`datetime` object passes
1414itself as the argument, and a :class:`time` object passes ``None`` as the
1415argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
1416accept a *dt* argument of ``None``, or of class :class:`datetime`.
1417
1418When ``None`` is passed, it's up to the class designer to decide the best
1419response. For example, returning ``None`` is appropriate if the class wishes to
1420say that time objects don't participate in the :class:`tzinfo` protocols. It
1421may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1422there is no other convention for discovering the standard offset.
1423
1424When a :class:`datetime` object is passed in response to a :class:`datetime`
1425method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1426rely on this, unless user code calls :class:`tzinfo` methods directly. The
1427intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1428time, and not need worry about objects in other timezones.
1429
1430There is one more :class:`tzinfo` method that a subclass may wish to override:
1431
1432
1433.. method:: tzinfo.fromutc(self, dt)
1434
1435 This is called from the default :class:`datetime.astimezone()` implementation.
1436 When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members
1437 are to be viewed as expressing a UTC time. The purpose of :meth:`fromutc` is to
1438 adjust the date and time members, returning an equivalent datetime in *self*'s
1439 local time.
1440
1441 Most :class:`tzinfo` subclasses should be able to inherit the default
1442 :meth:`fromutc` implementation without problems. It's strong enough to handle
1443 fixed-offset time zones, and time zones accounting for both standard and
1444 daylight time, and the latter even if the DST transition times differ in
1445 different years. An example of a time zone the default :meth:`fromutc`
1446 implementation may not handle correctly in all cases is one where the standard
1447 offset (from UTC) depends on the specific date and time passed, which can happen
1448 for political reasons. The default implementations of :meth:`astimezone` and
1449 :meth:`fromutc` may not produce the result you want if the result is one of the
1450 hours straddling the moment the standard offset changes.
1451
1452 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1453 like::
1454
1455 def fromutc(self, dt):
1456 # raise ValueError error if dt.tzinfo is not self
1457 dtoff = dt.utcoffset()
1458 dtdst = dt.dst()
1459 # raise ValueError if dtoff is None or dtdst is None
1460 delta = dtoff - dtdst # this is self's standard offset
1461 if delta:
1462 dt += delta # convert to standard local time
1463 dtdst = dt.dst()
1464 # raise ValueError if dtdst is None
1465 if dtdst:
1466 return dt + dtdst
1467 else:
1468 return dt
1469
1470Example :class:`tzinfo` classes:
1471
1472.. literalinclude:: ../includes/tzinfo-examples.py
1473
1474
1475Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1476subclass accounting for both standard and daylight time, at the DST transition
1477points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00001478minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
14791:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001480
1481 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1482 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1483 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1484
1485 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1486
1487 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1488
1489When DST starts (the "start" line), the local wall clock leaps from 1:59 to
14903:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1491``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1492begins. In order for :meth:`astimezone` to make this guarantee, the
1493:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1494Eastern) to be in daylight time.
1495
1496When DST ends (the "end" line), there's a potentially worse problem: there's an
1497hour that can't be spelled unambiguously in local wall time: the last hour of
1498daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1499daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1500to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1501:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1502hours into the same local hour then. In the Eastern example, UTC times of the
1503form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1504:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1505consider times in the "repeated hour" to be in standard time. This is easily
1506arranged, as in the example, by expressing DST switch times in the time zone's
1507standard local time.
1508
1509Applications that can't bear such ambiguities should avoid using hybrid
1510:class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any
1511other fixed-offset :class:`tzinfo` subclass (such as a class representing only
1512EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
Georg Brandl48310cd2009-01-03 21:18:54 +00001513
Georg Brandl116aa622007-08-15 14:28:22 +00001514
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001515.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00001516
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001517:meth:`strftime` and :meth:`strptime` Behavior
1518----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001519
1520:class:`date`, :class:`datetime`, and :class:`time` objects all support a
1521``strftime(format)`` method, to create a string representing the time under the
1522control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1523acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1524although not all objects support a :meth:`timetuple` method.
1525
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001526Conversely, the :meth:`datetime.strptime` class method creates a
1527:class:`datetime` object from a string representing a date and time and a
1528corresponding format string. ``datetime.strptime(date_string, format)`` is
1529equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1530
Georg Brandl116aa622007-08-15 14:28:22 +00001531For :class:`time` objects, the format codes for year, month, and day should not
1532be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001533is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00001534
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001535For :class:`date` objects, the format codes for hours, minutes, seconds, and
1536microseconds should not be used, as :class:`date` objects have no such
1537values. If they're used anyway, ``0`` is substituted for them.
1538
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001539For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1540strings.
1541
1542For an aware object:
1543
1544``%z``
1545 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1546 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1547 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1548 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1549 replaced with the string ``'-0330'``.
1550
1551``%Z``
1552 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1553 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl116aa622007-08-15 14:28:22 +00001554
Georg Brandl116aa622007-08-15 14:28:22 +00001555The full set of format codes supported varies across platforms, because Python
1556calls the platform C library's :func:`strftime` function, and platform
Georg Brandl48310cd2009-01-03 21:18:54 +00001557variations are common.
Christian Heimes895627f2007-12-08 17:28:33 +00001558
1559The following is a list of all the format codes that the C standard (1989
1560version) requires, and these work on all platforms with a standard C
1561implementation. Note that the 1999 version of the C standard added additional
1562format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001563
1564The exact range of years for which :meth:`strftime` works also varies across
1565platforms. Regardless of platform, years before 1900 cannot be used.
1566
Christian Heimes895627f2007-12-08 17:28:33 +00001567+-----------+--------------------------------+-------+
1568| Directive | Meaning | Notes |
1569+===========+================================+=======+
1570| ``%a`` | Locale's abbreviated weekday | |
1571| | name. | |
1572+-----------+--------------------------------+-------+
1573| ``%A`` | Locale's full weekday name. | |
1574+-----------+--------------------------------+-------+
1575| ``%b`` | Locale's abbreviated month | |
1576| | name. | |
1577+-----------+--------------------------------+-------+
1578| ``%B`` | Locale's full month name. | |
1579+-----------+--------------------------------+-------+
1580| ``%c`` | Locale's appropriate date and | |
1581| | time representation. | |
1582+-----------+--------------------------------+-------+
1583| ``%d`` | Day of the month as a decimal | |
1584| | number [01,31]. | |
1585+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001586| ``%f`` | Microsecond as a decimal | \(1) |
1587| | number [0,999999], zero-padded | |
1588| | on the left | |
1589+-----------+--------------------------------+-------+
Christian Heimes895627f2007-12-08 17:28:33 +00001590| ``%H`` | Hour (24-hour clock) as a | |
1591| | decimal number [00,23]. | |
1592+-----------+--------------------------------+-------+
1593| ``%I`` | Hour (12-hour clock) as a | |
1594| | decimal number [01,12]. | |
1595+-----------+--------------------------------+-------+
1596| ``%j`` | Day of the year as a decimal | |
1597| | number [001,366]. | |
1598+-----------+--------------------------------+-------+
1599| ``%m`` | Month as a decimal number | |
1600| | [01,12]. | |
1601+-----------+--------------------------------+-------+
1602| ``%M`` | Minute as a decimal number | |
1603| | [00,59]. | |
1604+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001605| ``%p`` | Locale's equivalent of either | \(2) |
Christian Heimes895627f2007-12-08 17:28:33 +00001606| | AM or PM. | |
1607+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001608| ``%S`` | Second as a decimal number | \(3) |
Christian Heimes895627f2007-12-08 17:28:33 +00001609| | [00,61]. | |
1610+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001611| ``%U`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001612| | (Sunday as the first day of | |
1613| | the week) as a decimal number | |
1614| | [00,53]. All days in a new | |
1615| | year preceding the first | |
1616| | Sunday are considered to be in | |
1617| | week 0. | |
1618+-----------+--------------------------------+-------+
1619| ``%w`` | Weekday as a decimal number | |
1620| | [0(Sunday),6]. | |
1621+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001622| ``%W`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001623| | (Monday as the first day of | |
1624| | the week) as a decimal number | |
1625| | [00,53]. All days in a new | |
1626| | year preceding the first | |
1627| | Monday are considered to be in | |
1628| | week 0. | |
1629+-----------+--------------------------------+-------+
1630| ``%x`` | Locale's appropriate date | |
1631| | representation. | |
1632+-----------+--------------------------------+-------+
1633| ``%X`` | Locale's appropriate time | |
1634| | representation. | |
1635+-----------+--------------------------------+-------+
1636| ``%y`` | Year without century as a | |
1637| | decimal number [00,99]. | |
1638+-----------+--------------------------------+-------+
1639| ``%Y`` | Year with century as a decimal | |
1640| | number. | |
1641+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001642| ``%z`` | UTC offset in the form +HHMM | \(5) |
Christian Heimes895627f2007-12-08 17:28:33 +00001643| | or -HHMM (empty string if the | |
1644| | the object is naive). | |
1645+-----------+--------------------------------+-------+
1646| ``%Z`` | Time zone name (empty string | |
1647| | if the object is naive). | |
1648+-----------+--------------------------------+-------+
1649| ``%%`` | A literal ``'%'`` character. | |
1650+-----------+--------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001651
Christian Heimes895627f2007-12-08 17:28:33 +00001652Notes:
1653
1654(1)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001655 When used with the :meth:`strptime` method, the ``%f`` directive
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001656 accepts from one to six digits and zero pads on the right. ``%f`` is
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001657 an extension to the set of format characters in the C standard (but
1658 implemented separately in datetime objects, and therefore always
1659 available).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001660
1661(2)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001662 When used with the :meth:`strptime` method, the ``%p`` directive only affects
Christian Heimes895627f2007-12-08 17:28:33 +00001663 the output hour field if the ``%I`` directive is used to parse the hour.
1664
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001665(3)
R. David Murraybd25d332009-04-02 04:50:03 +00001666 The range really is ``0`` to ``61``; according to the Posix standard this
1667 accounts for leap seconds and the (very rare) double leap seconds.
1668 The :mod:`time` module may produce and does accept leap seconds since
1669 it is based on the Posix standard, but the :mod:`datetime` module
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001670 does not accept leap seconds in :meth:`strptime` input nor will it
R. David Murraybd25d332009-04-02 04:50:03 +00001671 produce them in :func:`strftime` output.
Christian Heimes895627f2007-12-08 17:28:33 +00001672
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001673(4)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001674 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in
Christian Heimes895627f2007-12-08 17:28:33 +00001675 calculations when the day of the week and the year are specified.
1676
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001677(5)
Christian Heimes895627f2007-12-08 17:28:33 +00001678 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1679 ``%z`` is replaced with the string ``'-0330'``.