blob: 8371bde8596978e0baf4ed20e592cc23dcf2f12c [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
Alexander Belopolsky4e749a12010-06-14 14:15:50 +000031time zone name, and whether Daylight Saving Time is in effect. Note that only
32one concrete :class:`tzinfo` class, the :class:`timezone` class, is supplied by the
33:mod:`datetime` module. The :class:`timezone` class can reprsent simple
34timezones with fixed offset from UTC such as UTC itself or North American EST and
35EDT timezones. Supporting timezones at whatever level of detail is
36required is up to the application. The rules for time adjustment across the
37world are more political than rational, change frequently, and there is no
38standard suitable for every application aside from UTC.
Georg Brandl116aa622007-08-15 14:28:22 +000039
40The :mod:`datetime` module exports the following constants:
41
Georg Brandl116aa622007-08-15 14:28:22 +000042.. data:: MINYEAR
43
44 The smallest year number allowed in a :class:`date` or :class:`datetime` object.
45 :const:`MINYEAR` is ``1``.
46
47
48.. data:: MAXYEAR
49
50 The largest year number allowed in a :class:`date` or :class:`datetime` object.
51 :const:`MAXYEAR` is ``9999``.
52
53
54.. seealso::
55
56 Module :mod:`calendar`
57 General calendar related functions.
58
59 Module :mod:`time`
60 Time access and conversions.
61
62
63Available Types
64---------------
65
Georg Brandl116aa622007-08-15 14:28:22 +000066.. class:: date
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000067 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000068
69 An idealized naive date, assuming the current Gregorian calendar always was, and
70 always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and
71 :attr:`day`.
72
73
74.. class:: time
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000075 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000076
77 An idealized time, independent of any particular day, assuming that every day
78 has exactly 24\*60\*60 seconds (there is no notion of "leap seconds" here).
79 Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
80 and :attr:`tzinfo`.
81
82
83.. class:: datetime
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000084 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000085
86 A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`,
87 :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
88 and :attr:`tzinfo`.
89
90
91.. class:: timedelta
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000092 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000093
94 A duration expressing the difference between two :class:`date`, :class:`time`,
95 or :class:`datetime` instances to microsecond resolution.
96
97
98.. class:: tzinfo
99
100 An abstract base class for time zone information objects. These are used by the
101 :class:`datetime` and :class:`time` classes to provide a customizable notion of
102 time adjustment (for example, to account for time zone and/or daylight saving
103 time).
104
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000105.. class:: timezone
106
107 A class that implements the :class:`tzinfo` abstract base class as a
108 fixed offset from the UTC.
109
110 .. versionadded:: 3.2
111
112
Georg Brandl116aa622007-08-15 14:28:22 +0000113Objects of these types are immutable.
114
115Objects of the :class:`date` type are always naive.
116
117An object *d* of type :class:`time` or :class:`datetime` may be naive or aware.
118*d* is aware if ``d.tzinfo`` is not ``None`` and ``d.tzinfo.utcoffset(d)`` does
119not return ``None``. If ``d.tzinfo`` is ``None``, or if ``d.tzinfo`` is not
120``None`` but ``d.tzinfo.utcoffset(d)`` returns ``None``, *d* is naive.
121
122The distinction between naive and aware doesn't apply to :class:`timedelta`
123objects.
124
125Subclass relationships::
126
127 object
128 timedelta
129 tzinfo
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000130 timezone
Georg Brandl116aa622007-08-15 14:28:22 +0000131 time
132 date
133 datetime
134
135
136.. _datetime-timedelta:
137
138:class:`timedelta` Objects
139--------------------------
140
141A :class:`timedelta` object represents a duration, the difference between two
142dates or times.
143
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000144.. class:: timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000145
Georg Brandl5c106642007-11-29 17:41:05 +0000146 All arguments are optional and default to ``0``. Arguments may be integers
Georg Brandl116aa622007-08-15 14:28:22 +0000147 or floats, and may be positive or negative.
148
149 Only *days*, *seconds* and *microseconds* are stored internally. Arguments are
150 converted to those units:
151
152 * A millisecond is converted to 1000 microseconds.
153 * A minute is converted to 60 seconds.
154 * An hour is converted to 3600 seconds.
155 * A week is converted to 7 days.
156
157 and days, seconds and microseconds are then normalized so that the
158 representation is unique, with
159
160 * ``0 <= microseconds < 1000000``
161 * ``0 <= seconds < 3600*24`` (the number of seconds in one day)
162 * ``-999999999 <= days <= 999999999``
163
164 If any argument is a float and there are fractional microseconds, the fractional
165 microseconds left over from all arguments are combined and their sum is rounded
166 to the nearest microsecond. If no argument is a float, the conversion and
167 normalization processes are exact (no information is lost).
168
169 If the normalized value of days lies outside the indicated range,
170 :exc:`OverflowError` is raised.
171
172 Note that normalization of negative values may be surprising at first. For
Christian Heimesfe337bf2008-03-23 21:54:12 +0000173 example,
Georg Brandl116aa622007-08-15 14:28:22 +0000174
Christian Heimes895627f2007-12-08 17:28:33 +0000175 >>> from datetime import timedelta
Georg Brandl116aa622007-08-15 14:28:22 +0000176 >>> d = timedelta(microseconds=-1)
177 >>> (d.days, d.seconds, d.microseconds)
178 (-1, 86399, 999999)
179
Georg Brandl116aa622007-08-15 14:28:22 +0000180
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000181Class attributes are:
Georg Brandl116aa622007-08-15 14:28:22 +0000182
183.. attribute:: timedelta.min
184
185 The most negative :class:`timedelta` object, ``timedelta(-999999999)``.
186
187
188.. attribute:: timedelta.max
189
190 The most positive :class:`timedelta` object, ``timedelta(days=999999999,
191 hours=23, minutes=59, seconds=59, microseconds=999999)``.
192
193
194.. attribute:: timedelta.resolution
195
196 The smallest possible difference between non-equal :class:`timedelta` objects,
197 ``timedelta(microseconds=1)``.
198
199Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``.
200``-timedelta.max`` is not representable as a :class:`timedelta` object.
201
202Instance attributes (read-only):
203
204+------------------+--------------------------------------------+
205| Attribute | Value |
206+==================+============================================+
207| ``days`` | Between -999999999 and 999999999 inclusive |
208+------------------+--------------------------------------------+
209| ``seconds`` | Between 0 and 86399 inclusive |
210+------------------+--------------------------------------------+
211| ``microseconds`` | Between 0 and 999999 inclusive |
212+------------------+--------------------------------------------+
213
214Supported operations:
215
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000216.. XXX this table is too wide!
Georg Brandl116aa622007-08-15 14:28:22 +0000217
218+--------------------------------+-----------------------------------------------+
219| Operation | Result |
220+================================+===============================================+
221| ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == |
222| | *t3* and *t1*-*t3* == *t2* are true. (1) |
223+--------------------------------+-----------------------------------------------+
224| ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* |
225| | == *t2* - *t3* and *t2* == *t1* + *t3* are |
226| | true. (1) |
227+--------------------------------+-----------------------------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000228| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer. |
Georg Brandl116aa622007-08-15 14:28:22 +0000229| | Afterwards *t1* // i == *t2* is true, |
230| | provided ``i != 0``. |
231+--------------------------------+-----------------------------------------------+
232| | In general, *t1* \* i == *t1* \* (i-1) + *t1* |
233| | is true. (1) |
234+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000235| ``t1 = t2 * f or t1 = f * t2`` | Delta multiplied by a float. The result is |
236| | rounded to the nearest multiple of |
237| | timedelta.resolution using round-half-to-even.|
238+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000239| ``f = t2 / t3`` | Division (3) of *t2* by *t3*. Returns a |
240| | :class:`float` object. |
241+--------------------------------+-----------------------------------------------+
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000242| ``t1 = t2 / f or t1 = t2 / i`` | Delta divided by a float or an int. The result|
243| | is rounded to the nearest multiple of |
244| | timedelta.resolution using round-half-to-even.|
245+--------------------------------+-----------------------------------------------+
Mark Dickinson7c186e22010-04-20 22:32:49 +0000246| ``t1 = t2 // i`` or | The floor is computed and the remainder (if |
247| ``t1 = t2 // t3`` | any) is thrown away. In the second case, an |
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000248| | integer is returned. (3) |
Mark Dickinson7c186e22010-04-20 22:32:49 +0000249+--------------------------------+-----------------------------------------------+
250| ``t1 = t2 % t3`` | The remainder is computed as a |
251| | :class:`timedelta` object. (3) |
252+--------------------------------+-----------------------------------------------+
253| ``q, r = divmod(t1, t2)`` | Computes the quotient and the remainder: |
254| | ``q = t1 // t2`` (3) and ``r = t1 % t2``. |
255| | q is an integer and r is a :class:`timedelta` |
256| | object. |
Georg Brandl116aa622007-08-15 14:28:22 +0000257+--------------------------------+-----------------------------------------------+
258| ``+t1`` | Returns a :class:`timedelta` object with the |
259| | same value. (2) |
260+--------------------------------+-----------------------------------------------+
261| ``-t1`` | equivalent to :class:`timedelta`\ |
262| | (-*t1.days*, -*t1.seconds*, |
263| | -*t1.microseconds*), and to *t1*\* -1. (1)(4) |
264+--------------------------------+-----------------------------------------------+
Georg Brandl495f7b52009-10-27 15:28:25 +0000265| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, and|
Georg Brandl116aa622007-08-15 14:28:22 +0000266| | to -*t* when ``t.days < 0``. (2) |
267+--------------------------------+-----------------------------------------------+
Georg Brandlf55c3152010-07-31 11:40:07 +0000268| ``str(t)`` | Returns a string in the form |
269| | ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D |
270| | is negative for negative ``t``. (5) |
271+--------------------------------+-----------------------------------------------+
272| ``repr(t)`` | Returns a string in the form |
273| | ``datetime.timedelta(D[, S[, U]])``, where D |
274| | is negative for negative ``t``. (5) |
275+--------------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000276
277Notes:
278
279(1)
280 This is exact, but may overflow.
281
282(2)
283 This is exact, and cannot overflow.
284
285(3)
286 Division by 0 raises :exc:`ZeroDivisionError`.
287
288(4)
289 -*timedelta.max* is not representable as a :class:`timedelta` object.
290
Georg Brandlf55c3152010-07-31 11:40:07 +0000291(5)
292 String representations of :class:`timedelta` objects are normalized
293 similarly to their internal representation. This leads to somewhat
294 unusual results for negative timedeltas. For example:
295
296 >>> timedelta(hours=-5)
297 datetime.timedelta(-1, 68400)
298 >>> print(_)
299 -1 day, 19:00:00
300
Georg Brandl116aa622007-08-15 14:28:22 +0000301In addition to the operations listed above :class:`timedelta` objects support
302certain additions and subtractions with :class:`date` and :class:`datetime`
303objects (see below).
304
Georg Brandl67b21b72010-08-17 15:07:14 +0000305.. versionchanged:: 3.2
306 Floor division and true division of a :class:`timedelta` object by another
307 :class:`timedelta` object are now supported, as are remainder operations and
308 the :func:`divmod` function. True division and multiplication of a
309 :class:`timedelta` object by a :class:`float` object are now supported.
Mark Dickinson7c186e22010-04-20 22:32:49 +0000310
311
Georg Brandl116aa622007-08-15 14:28:22 +0000312Comparisons of :class:`timedelta` objects are supported with the
313:class:`timedelta` object representing the smaller duration considered to be the
314smaller timedelta. In order to stop mixed-type comparisons from falling back to
315the default comparison by object address, when a :class:`timedelta` object is
316compared to an object of a different type, :exc:`TypeError` is raised unless the
317comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
318:const:`True`, respectively.
319
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000320:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl116aa622007-08-15 14:28:22 +0000321efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
322considered to be true if and only if it isn't equal to ``timedelta(0)``.
323
Antoine Pitroube6859d2009-11-25 23:02:32 +0000324Instance methods:
325
326.. method:: timedelta.total_seconds()
327
328 Return the total number of seconds contained in the duration. Equivalent to
Mark Dickinson0381e3f2010-05-08 14:35:02 +0000329 ``td / timedelta(seconds=1)``.
330
331 Note that for very large time intervals (greater than 270 years on
332 most platforms) this method will lose microsecond accuracy.
Antoine Pitroube6859d2009-11-25 23:02:32 +0000333
334 .. versionadded:: 3.2
335
336
Christian Heimesfe337bf2008-03-23 21:54:12 +0000337Example usage:
Georg Brandl48310cd2009-01-03 21:18:54 +0000338
Christian Heimes895627f2007-12-08 17:28:33 +0000339 >>> from datetime import timedelta
340 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000341 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Christian Heimes895627f2007-12-08 17:28:33 +0000342 ... minutes=50, seconds=600) # adds up to 365 days
Antoine Pitroube6859d2009-11-25 23:02:32 +0000343 >>> year.total_seconds()
344 31536000.0
Christian Heimes895627f2007-12-08 17:28:33 +0000345 >>> year == another_year
346 True
347 >>> ten_years = 10 * year
348 >>> ten_years, ten_years.days // 365
349 (datetime.timedelta(3650), 10)
350 >>> nine_years = ten_years - year
351 >>> nine_years, nine_years.days // 365
352 (datetime.timedelta(3285), 9)
353 >>> three_years = nine_years // 3;
354 >>> three_years, three_years.days // 365
355 (datetime.timedelta(1095), 3)
356 >>> abs(three_years - ten_years) == 2 * three_years + year
357 True
358
Georg Brandl116aa622007-08-15 14:28:22 +0000359
360.. _datetime-date:
361
362:class:`date` Objects
363---------------------
364
365A :class:`date` object represents a date (year, month and day) in an idealized
366calendar, the current Gregorian calendar indefinitely extended in both
367directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
368called day number 2, and so on. This matches the definition of the "proleptic
369Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
370where it's the base calendar for all computations. See the book for algorithms
371for converting between proleptic Gregorian ordinals and many other calendar
372systems.
373
374
375.. class:: date(year, month, day)
376
Georg Brandl5c106642007-11-29 17:41:05 +0000377 All arguments are required. Arguments may be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000378 ranges:
379
380 * ``MINYEAR <= year <= MAXYEAR``
381 * ``1 <= month <= 12``
382 * ``1 <= day <= number of days in the given month and year``
383
384 If an argument outside those ranges is given, :exc:`ValueError` is raised.
385
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000386
Georg Brandl116aa622007-08-15 14:28:22 +0000387Other constructors, all class methods:
388
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000389.. classmethod:: date.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000390
391 Return the current local date. This is equivalent to
392 ``date.fromtimestamp(time.time())``.
393
394
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000395.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000396
397 Return the local date corresponding to the POSIX timestamp, such as is returned
398 by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out
Georg Brandl60203b42010-10-06 10:11:56 +0000399 of the range of values supported by the platform C :c:func:`localtime` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000400 It's common for this to be restricted to years from 1970 through 2038. Note
401 that on non-POSIX systems that include leap seconds in their notion of a
402 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
403
404
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000405.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000406
407 Return the date corresponding to the proleptic Gregorian ordinal, where January
408 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
409 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
410 d``.
411
Georg Brandl116aa622007-08-15 14:28:22 +0000412
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000413Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000414
415.. attribute:: date.min
416
417 The earliest representable date, ``date(MINYEAR, 1, 1)``.
418
419
420.. attribute:: date.max
421
422 The latest representable date, ``date(MAXYEAR, 12, 31)``.
423
424
425.. attribute:: date.resolution
426
427 The smallest possible difference between non-equal date objects,
428 ``timedelta(days=1)``.
429
Georg Brandl116aa622007-08-15 14:28:22 +0000430
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000431Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000432
433.. attribute:: date.year
434
435 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
436
437
438.. attribute:: date.month
439
440 Between 1 and 12 inclusive.
441
442
443.. attribute:: date.day
444
445 Between 1 and the number of days in the given month of the given year.
446
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000447
Georg Brandl116aa622007-08-15 14:28:22 +0000448Supported operations:
449
450+-------------------------------+----------------------------------------------+
451| Operation | Result |
452+===============================+==============================================+
453| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
454| | from *date1*. (1) |
455+-------------------------------+----------------------------------------------+
456| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
457| | timedelta == date1``. (2) |
458+-------------------------------+----------------------------------------------+
459| ``timedelta = date1 - date2`` | \(3) |
460+-------------------------------+----------------------------------------------+
461| ``date1 < date2`` | *date1* is considered less than *date2* when |
462| | *date1* precedes *date2* in time. (4) |
463+-------------------------------+----------------------------------------------+
464
465Notes:
466
467(1)
468 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
469 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
470 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
471 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
472 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
473
474(2)
475 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
476 isolation can overflow in cases where date1 - timedelta does not.
477 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
478
479(3)
480 This is exact, and cannot overflow. timedelta.seconds and
481 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
482
483(4)
484 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
485 date2.toordinal()``. In order to stop comparison from falling back to the
486 default scheme of comparing object addresses, date comparison normally raises
487 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
488 However, ``NotImplemented`` is returned instead if the other comparand has a
489 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
490 chance at implementing mixed-type comparison. If not, when a :class:`date`
491 object is compared to an object of a different type, :exc:`TypeError` is raised
492 unless the comparison is ``==`` or ``!=``. The latter cases return
493 :const:`False` or :const:`True`, respectively.
494
495Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
496objects are considered to be true.
497
498Instance methods:
499
Georg Brandl116aa622007-08-15 14:28:22 +0000500.. method:: date.replace(year, month, day)
501
502 Return a date with the same value, except for those members given new values by
503 whichever keyword arguments are specified. For example, if ``d == date(2002,
504 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
505
506
507.. method:: date.timetuple()
508
509 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
510 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
511 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000512 d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1,
513 1).toordinal() + 1`` is the day number within the current year starting with
514 ``1`` for January 1st.
Georg Brandl116aa622007-08-15 14:28:22 +0000515
516
517.. method:: date.toordinal()
518
519 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
520 has ordinal 1. For any :class:`date` object *d*,
521 ``date.fromordinal(d.toordinal()) == d``.
522
523
524.. method:: date.weekday()
525
526 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
527 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
528 :meth:`isoweekday`.
529
530
531.. method:: date.isoweekday()
532
533 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
534 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
535 :meth:`weekday`, :meth:`isocalendar`.
536
537
538.. method:: date.isocalendar()
539
540 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
541
542 The ISO calendar is a widely used variant of the Gregorian calendar. See
Mark Dickinsonf964ac22009-11-03 16:29:10 +0000543 http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
544 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000545
546 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
547 Monday and ends on a Sunday. The first week of an ISO year is the first
548 (Gregorian) calendar week of a year containing a Thursday. This is called week
549 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
550
551 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
552 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
553 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
554 4).isocalendar() == (2004, 1, 7)``.
555
556
557.. method:: date.isoformat()
558
559 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
560 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
561
562
563.. method:: date.__str__()
564
565 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
566
567
568.. method:: date.ctime()
569
570 Return a string representing the date, for example ``date(2002, 12,
571 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
572 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
Georg Brandl60203b42010-10-06 10:11:56 +0000573 :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +0000574 :meth:`date.ctime` does not invoke) conforms to the C standard.
575
576
577.. method:: date.strftime(format)
578
579 Return a string representing the date, controlled by an explicit format string.
580 Format codes referring to hours, minutes or seconds will see 0 values. See
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000581 section :ref:`strftime-strptime-behavior`.
582
Georg Brandl116aa622007-08-15 14:28:22 +0000583
Christian Heimes895627f2007-12-08 17:28:33 +0000584Example of counting days to an event::
585
586 >>> import time
587 >>> from datetime import date
588 >>> today = date.today()
589 >>> today
590 datetime.date(2007, 12, 5)
591 >>> today == date.fromtimestamp(time.time())
592 True
593 >>> my_birthday = date(today.year, 6, 24)
594 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000595 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000596 >>> my_birthday
597 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000598 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000599 >>> time_to_birthday.days
600 202
601
Christian Heimesfe337bf2008-03-23 21:54:12 +0000602Example of working with :class:`date`:
603
604.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000605
606 >>> from datetime import date
607 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
608 >>> d
609 datetime.date(2002, 3, 11)
610 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000611 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000612 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000613 2002 # year
614 3 # month
615 11 # day
616 0
617 0
618 0
619 0 # weekday (0 = Monday)
620 70 # 70th day in the year
621 -1
622 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000623 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000624 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000625 2002 # ISO year
626 11 # ISO week number
627 1 # ISO day number ( 1 = Monday )
628 >>> d.isoformat()
629 '2002-03-11'
630 >>> d.strftime("%d/%m/%y")
631 '11/03/02'
632 >>> d.strftime("%A %d. %B %Y")
633 'Monday 11. March 2002'
634
Georg Brandl116aa622007-08-15 14:28:22 +0000635
636.. _datetime-datetime:
637
638:class:`datetime` Objects
639-------------------------
640
641A :class:`datetime` object is a single object containing all the information
642from a :class:`date` object and a :class:`time` object. Like a :class:`date`
643object, :class:`datetime` assumes the current Gregorian calendar extended in
644both directions; like a time object, :class:`datetime` assumes there are exactly
6453600\*24 seconds in every day.
646
647Constructor:
648
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000649.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000650
651 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000652 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
653 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000654
655 * ``MINYEAR <= year <= MAXYEAR``
656 * ``1 <= month <= 12``
657 * ``1 <= day <= number of days in the given month and year``
658 * ``0 <= hour < 24``
659 * ``0 <= minute < 60``
660 * ``0 <= second < 60``
661 * ``0 <= microsecond < 1000000``
662
663 If an argument outside those ranges is given, :exc:`ValueError` is raised.
664
665Other constructors, all class methods:
666
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000667.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000668
669 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
670 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
671 :meth:`fromtimestamp`.
672
673
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000674.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000675
676 Return the current local date and time. If optional argument *tz* is ``None``
677 or not specified, this is like :meth:`today`, but, if possible, supplies more
678 precision than can be gotten from going through a :func:`time.time` timestamp
679 (for example, this may be possible on platforms supplying the C
Georg Brandl60203b42010-10-06 10:11:56 +0000680 :c:func:`gettimeofday` function).
Georg Brandl116aa622007-08-15 14:28:22 +0000681
682 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
683 current date and time are converted to *tz*'s time zone. In this case the
684 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
685 See also :meth:`today`, :meth:`utcnow`.
686
687
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000688.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000689
690 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
691 :meth:`now`, but returns the current UTC date and time, as a naive
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000692 :class:`datetime` object. An aware current UTC datetime can be obtained by
693 calling ``datetime.now(timezone.utc)``. See also :meth:`now`.
Georg Brandl116aa622007-08-15 14:28:22 +0000694
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000695.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000696
697 Return the local date and time corresponding to the POSIX timestamp, such as is
698 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
699 specified, the timestamp is converted to the platform's local date and time, and
700 the returned :class:`datetime` object is naive.
701
702 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
703 timestamp is converted to *tz*'s time zone. In this case the result is
704 equivalent to
705 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
706
707 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
Georg Brandl60203b42010-10-06 10:11:56 +0000708 the range of values supported by the platform C :c:func:`localtime` or
709 :c:func:`gmtime` functions. It's common for this to be restricted to years in
Georg Brandl116aa622007-08-15 14:28:22 +0000710 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
711 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
712 and then it's possible to have two timestamps differing by a second that yield
713 identical :class:`datetime` objects. See also :meth:`utcfromtimestamp`.
714
715
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000716.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000717
718 Return the UTC :class:`datetime` corresponding to the POSIX timestamp, with
719 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
Georg Brandl60203b42010-10-06 10:11:56 +0000720 out of the range of values supported by the platform C :c:func:`gmtime` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000721 It's common for this to be restricted to years in 1970 through 2038. See also
722 :meth:`fromtimestamp`.
723
Alexander Belopolsky54afa552011-04-25 13:00:40 -0400724 On the POSIX compliant platforms, ``utcfromtimestamp(timestamp)``
725 is equivalent to the following expression::
726
727 datetime(1970, 1, 1) + timedelta(seconds=timestamp)
728
729 There is no method to obtain the timestamp from a :class:`datetime`
730 instance, but POSIX timestamp corresponding to a :class:`datetime`
731 instance ``dt`` can be easily calculated as follows. For a naive
732 ``dt``::
733
734 timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
735
736 And for an aware ``dt``::
737
738 timestamp = (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)) / timedelta(seconds=1)
739
Georg Brandl116aa622007-08-15 14:28:22 +0000740
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000741.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000742
743 Return the :class:`datetime` corresponding to the proleptic Gregorian ordinal,
744 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
745 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
746 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
747
748
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000749.. classmethod:: datetime.combine(date, time)
Georg Brandl116aa622007-08-15 14:28:22 +0000750
751 Return a new :class:`datetime` object whose date members are equal to the given
752 :class:`date` object's, and whose time and :attr:`tzinfo` members are equal to
753 the given :class:`time` object's. For any :class:`datetime` object *d*, ``d ==
754 datetime.combine(d.date(), d.timetz())``. If date is a :class:`datetime`
755 object, its time and :attr:`tzinfo` members are ignored.
756
757
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000758.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000759
760 Return a :class:`datetime` corresponding to *date_string*, parsed according to
761 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
762 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
763 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 +0000764 time tuple. See section :ref:`strftime-strptime-behavior`.
765
Georg Brandl116aa622007-08-15 14:28:22 +0000766
Georg Brandl116aa622007-08-15 14:28:22 +0000767
768Class attributes:
769
Georg Brandl116aa622007-08-15 14:28:22 +0000770.. attribute:: datetime.min
771
772 The earliest representable :class:`datetime`, ``datetime(MINYEAR, 1, 1,
773 tzinfo=None)``.
774
775
776.. attribute:: datetime.max
777
778 The latest representable :class:`datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
779 59, 999999, tzinfo=None)``.
780
781
782.. attribute:: datetime.resolution
783
784 The smallest possible difference between non-equal :class:`datetime` objects,
785 ``timedelta(microseconds=1)``.
786
Georg Brandl116aa622007-08-15 14:28:22 +0000787
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000788Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000789
790.. attribute:: datetime.year
791
792 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
793
794
795.. attribute:: datetime.month
796
797 Between 1 and 12 inclusive.
798
799
800.. attribute:: datetime.day
801
802 Between 1 and the number of days in the given month of the given year.
803
804
805.. attribute:: datetime.hour
806
807 In ``range(24)``.
808
809
810.. attribute:: datetime.minute
811
812 In ``range(60)``.
813
814
815.. attribute:: datetime.second
816
817 In ``range(60)``.
818
819
820.. attribute:: datetime.microsecond
821
822 In ``range(1000000)``.
823
824
825.. attribute:: datetime.tzinfo
826
827 The object passed as the *tzinfo* argument to the :class:`datetime` constructor,
828 or ``None`` if none was passed.
829
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000830
Georg Brandl116aa622007-08-15 14:28:22 +0000831Supported operations:
832
833+---------------------------------------+-------------------------------+
834| Operation | Result |
835+=======================================+===============================+
836| ``datetime2 = datetime1 + timedelta`` | \(1) |
837+---------------------------------------+-------------------------------+
838| ``datetime2 = datetime1 - timedelta`` | \(2) |
839+---------------------------------------+-------------------------------+
840| ``timedelta = datetime1 - datetime2`` | \(3) |
841+---------------------------------------+-------------------------------+
842| ``datetime1 < datetime2`` | Compares :class:`datetime` to |
843| | :class:`datetime`. (4) |
844+---------------------------------------+-------------------------------+
845
846(1)
847 datetime2 is a duration of timedelta removed from datetime1, moving forward in
848 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
849 result has the same :attr:`tzinfo` member as the input datetime, and datetime2 -
850 datetime1 == timedelta after. :exc:`OverflowError` is raised if datetime2.year
851 would be smaller than :const:`MINYEAR` or larger than :const:`MAXYEAR`. Note
852 that no time zone adjustments are done even if the input is an aware object.
853
854(2)
855 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
856 addition, the result has the same :attr:`tzinfo` member as the input datetime,
857 and no time zone adjustments are done even if the input is aware. This isn't
858 quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation
859 can overflow in cases where datetime1 - timedelta does not.
860
861(3)
862 Subtraction of a :class:`datetime` from a :class:`datetime` is defined only if
863 both operands are naive, or if both are aware. If one is aware and the other is
864 naive, :exc:`TypeError` is raised.
865
866 If both are naive, or both are aware and have the same :attr:`tzinfo` member,
867 the :attr:`tzinfo` members are ignored, and the result is a :class:`timedelta`
868 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
869 are done in this case.
870
871 If both are aware and have different :attr:`tzinfo` members, ``a-b`` acts as if
872 *a* and *b* were first converted to naive UTC datetimes first. The result is
873 ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) -
874 b.utcoffset())`` except that the implementation never overflows.
875
876(4)
877 *datetime1* is considered less than *datetime2* when *datetime1* precedes
878 *datetime2* in time.
879
880 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
881 If both comparands are aware, and have the same :attr:`tzinfo` member, the
882 common :attr:`tzinfo` member is ignored and the base datetimes are compared. If
883 both comparands are aware and have different :attr:`tzinfo` members, the
884 comparands are first adjusted by subtracting their UTC offsets (obtained from
885 ``self.utcoffset()``).
886
887 .. note::
888
889 In order to stop comparison from falling back to the default scheme of comparing
890 object addresses, datetime comparison normally raises :exc:`TypeError` if the
891 other comparand isn't also a :class:`datetime` object. However,
892 ``NotImplemented`` is returned instead if the other comparand has a
893 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
894 chance at implementing mixed-type comparison. If not, when a :class:`datetime`
895 object is compared to an object of a different type, :exc:`TypeError` is raised
896 unless the comparison is ``==`` or ``!=``. The latter cases return
897 :const:`False` or :const:`True`, respectively.
898
899:class:`datetime` objects can be used as dictionary keys. In Boolean contexts,
900all :class:`datetime` objects are considered to be true.
901
902Instance methods:
903
Georg Brandl116aa622007-08-15 14:28:22 +0000904.. method:: datetime.date()
905
906 Return :class:`date` object with same year, month and day.
907
908
909.. method:: datetime.time()
910
911 Return :class:`time` object with same hour, minute, second and microsecond.
912 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
913
914
915.. method:: datetime.timetz()
916
917 Return :class:`time` object with same hour, minute, second, microsecond, and
918 tzinfo members. See also method :meth:`time`.
919
920
921.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
922
923 Return a datetime with the same members, except for those members given new
924 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
925 can be specified to create a naive datetime from an aware datetime with no
926 conversion of date and time members.
927
928
929.. method:: datetime.astimezone(tz)
930
931 Return a :class:`datetime` object with new :attr:`tzinfo` member *tz*, adjusting
932 the date and time members so the result is the same UTC time as *self*, but in
933 *tz*'s local time.
934
935 *tz* must be an instance of a :class:`tzinfo` subclass, and its
936 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
937 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
938 not return ``None``).
939
940 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
941 adjustment of date or time members is performed. Else the result is local time
942 in time zone *tz*, representing the same UTC time as *self*: after ``astz =
943 dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have the same date
944 and time members as ``dt - dt.utcoffset()``. The discussion of class
945 :class:`tzinfo` explains the cases at Daylight Saving Time transition boundaries
946 where this cannot be achieved (an issue only if *tz* models both standard and
947 daylight time).
948
949 If you merely want to attach a time zone object *tz* to a datetime *dt* without
950 adjustment of date and time members, use ``dt.replace(tzinfo=tz)``. If you
951 merely want to remove the time zone object from an aware datetime *dt* without
952 conversion of date and time members, use ``dt.replace(tzinfo=None)``.
953
954 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
955 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
956 Ignoring error cases, :meth:`astimezone` acts like::
957
958 def astimezone(self, tz):
959 if self.tzinfo is tz:
960 return self
961 # Convert self to UTC, and attach the new time zone object.
962 utc = (self - self.utcoffset()).replace(tzinfo=tz)
963 # Convert from UTC to tz's local time.
964 return tz.fromutc(utc)
965
966
967.. method:: datetime.utcoffset()
968
969 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
970 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
971 return ``None``, or a :class:`timedelta` object representing a whole number of
972 minutes with magnitude less than one day.
973
974
975.. method:: datetime.dst()
976
977 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
978 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
979 ``None``, or a :class:`timedelta` object representing a whole number of minutes
980 with magnitude less than one day.
981
982
983.. method:: datetime.tzname()
984
985 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
986 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
987 ``None`` or a string object,
988
989
990.. method:: datetime.timetuple()
991
992 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
993 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000994 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
995 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
996 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
997 of the result is set according to the :meth:`dst` method: :attr:`tzinfo` is
Georg Brandl682d7e02010-10-06 10:26:05 +0000998 ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
Alexander Belopolsky64912482010-06-08 18:59:20 +0000999 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
Alexander Belopolskyda62f2f2010-06-09 17:11:01 +00001000 else :attr:`tm_isdst` is set to ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +00001001
1002
1003.. method:: datetime.utctimetuple()
1004
1005 If :class:`datetime` instance *d* is naive, this is the same as
1006 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
1007 ``d.dst()`` returns. DST is never in effect for a UTC time.
1008
1009 If *d* is aware, *d* is normalized to UTC time, by subtracting
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00001010 ``d.utcoffset()``, and a :class:`time.struct_time` for the
1011 normalized time is returned. :attr:`tm_isdst` is forced to 0. Note
1012 that an :exc:`OverflowError` may be raised if *d*.year was
1013 ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
Georg Brandl116aa622007-08-15 14:28:22 +00001014 boundary.
1015
1016
1017.. method:: datetime.toordinal()
1018
1019 Return the proleptic Gregorian ordinal of the date. The same as
1020 ``self.date().toordinal()``.
1021
1022
1023.. method:: datetime.weekday()
1024
1025 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
1026 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
1027
1028
1029.. method:: datetime.isoweekday()
1030
1031 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
1032 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
1033 :meth:`isocalendar`.
1034
1035
1036.. method:: datetime.isocalendar()
1037
1038 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
1039 ``self.date().isocalendar()``.
1040
1041
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001042.. method:: datetime.isoformat(sep='T')
Georg Brandl116aa622007-08-15 14:28:22 +00001043
1044 Return a string representing the date and time in ISO 8601 format,
1045 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
1046 YYYY-MM-DDTHH:MM:SS
1047
1048 If :meth:`utcoffset` does not return ``None``, a 6-character string is
1049 appended, giving the UTC offset in (signed) hours and minutes:
1050 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
1051 YYYY-MM-DDTHH:MM:SS+HH:MM
1052
1053 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +00001054 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +00001055
1056 >>> from datetime import tzinfo, timedelta, datetime
1057 >>> class TZ(tzinfo):
1058 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1059 ...
1060 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1061 '2002-12-25 00:00:00-06:39'
1062
1063
1064.. method:: datetime.__str__()
1065
1066 For a :class:`datetime` instance *d*, ``str(d)`` is equivalent to
1067 ``d.isoformat(' ')``.
1068
1069
1070.. method:: datetime.ctime()
1071
1072 Return a string representing the date and time, for example ``datetime(2002, 12,
1073 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1074 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
Georg Brandl60203b42010-10-06 10:11:56 +00001075 native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl116aa622007-08-15 14:28:22 +00001076 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1077
1078
1079.. method:: datetime.strftime(format)
1080
1081 Return a string representing the date and time, controlled by an explicit format
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001082 string. See section :ref:`strftime-strptime-behavior`.
1083
Georg Brandl116aa622007-08-15 14:28:22 +00001084
Christian Heimesfe337bf2008-03-23 21:54:12 +00001085Examples of working with datetime objects:
1086
1087.. doctest::
1088
Christian Heimes895627f2007-12-08 17:28:33 +00001089 >>> from datetime import datetime, date, time
1090 >>> # Using datetime.combine()
1091 >>> d = date(2005, 7, 14)
1092 >>> t = time(12, 30)
1093 >>> datetime.combine(d, t)
1094 datetime.datetime(2005, 7, 14, 12, 30)
1095 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001096 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001097 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001098 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001099 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1100 >>> # Using datetime.strptime()
1101 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1102 >>> dt
1103 datetime.datetime(2006, 11, 21, 16, 30)
1104 >>> # Using datetime.timetuple() to get tuple of all attributes
1105 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001106 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001107 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001108 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001109 2006 # year
1110 11 # month
1111 21 # day
1112 16 # hour
1113 30 # minute
1114 0 # second
1115 1 # weekday (0 = Monday)
1116 325 # number of days since 1st January
1117 -1 # dst - method tzinfo.dst() returned None
1118 >>> # Date in ISO format
1119 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001120 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001121 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001122 ...
1123 2006 # ISO year
1124 47 # ISO week
1125 2 # ISO weekday
1126 >>> # Formatting datetime
1127 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1128 'Tuesday, 21. November 2006 04:30PM'
1129
Christian Heimesfe337bf2008-03-23 21:54:12 +00001130Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001131
1132 >>> from datetime import timedelta, datetime, tzinfo
1133 >>> class GMT1(tzinfo):
1134 ... def __init__(self): # DST starts last Sunday in March
1135 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1136 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001137 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001138 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1139 ... def utcoffset(self, dt):
1140 ... return timedelta(hours=1) + self.dst(dt)
Georg Brandl48310cd2009-01-03 21:18:54 +00001141 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001142 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1143 ... return timedelta(hours=1)
1144 ... else:
1145 ... return timedelta(0)
1146 ... def tzname(self,dt):
1147 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001148 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001149 >>> class GMT2(tzinfo):
1150 ... def __init__(self):
Georg Brandl48310cd2009-01-03 21:18:54 +00001151 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001152 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001153 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001154 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1155 ... def utcoffset(self, dt):
1156 ... return timedelta(hours=1) + self.dst(dt)
1157 ... def dst(self, dt):
1158 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1159 ... return timedelta(hours=2)
1160 ... else:
1161 ... return timedelta(0)
1162 ... def tzname(self,dt):
1163 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001164 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001165 >>> gmt1 = GMT1()
1166 >>> # Daylight Saving Time
1167 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1168 >>> dt1.dst()
1169 datetime.timedelta(0)
1170 >>> dt1.utcoffset()
1171 datetime.timedelta(0, 3600)
1172 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1173 >>> dt2.dst()
1174 datetime.timedelta(0, 3600)
1175 >>> dt2.utcoffset()
1176 datetime.timedelta(0, 7200)
1177 >>> # Convert datetime to another time zone
1178 >>> dt3 = dt2.astimezone(GMT2())
1179 >>> dt3 # doctest: +ELLIPSIS
1180 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1181 >>> dt2 # doctest: +ELLIPSIS
1182 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1183 >>> dt2.utctimetuple() == dt3.utctimetuple()
1184 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001185
Christian Heimes895627f2007-12-08 17:28:33 +00001186
Georg Brandl116aa622007-08-15 14:28:22 +00001187
1188.. _datetime-time:
1189
1190:class:`time` Objects
1191---------------------
1192
1193A time object represents a (local) time of day, independent of any particular
1194day, and subject to adjustment via a :class:`tzinfo` object.
1195
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001196.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001197
1198 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001199 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001200 following ranges:
1201
1202 * ``0 <= hour < 24``
1203 * ``0 <= minute < 60``
1204 * ``0 <= second < 60``
1205 * ``0 <= microsecond < 1000000``.
1206
1207 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1208 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1209
1210Class attributes:
1211
1212
1213.. attribute:: time.min
1214
1215 The earliest representable :class:`time`, ``time(0, 0, 0, 0)``.
1216
1217
1218.. attribute:: time.max
1219
1220 The latest representable :class:`time`, ``time(23, 59, 59, 999999)``.
1221
1222
1223.. attribute:: time.resolution
1224
1225 The smallest possible difference between non-equal :class:`time` objects,
1226 ``timedelta(microseconds=1)``, although note that arithmetic on :class:`time`
1227 objects is not supported.
1228
Georg Brandl116aa622007-08-15 14:28:22 +00001229
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001230Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001231
1232.. attribute:: time.hour
1233
1234 In ``range(24)``.
1235
1236
1237.. attribute:: time.minute
1238
1239 In ``range(60)``.
1240
1241
1242.. attribute:: time.second
1243
1244 In ``range(60)``.
1245
1246
1247.. attribute:: time.microsecond
1248
1249 In ``range(1000000)``.
1250
1251
1252.. attribute:: time.tzinfo
1253
1254 The object passed as the tzinfo argument to the :class:`time` constructor, or
1255 ``None`` if none was passed.
1256
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001257
Georg Brandl116aa622007-08-15 14:28:22 +00001258Supported operations:
1259
1260* comparison of :class:`time` to :class:`time`, where *a* is considered less
1261 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1262 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
1263 the same :attr:`tzinfo` member, the common :attr:`tzinfo` member is ignored and
1264 the base times are compared. If both comparands are aware and have different
1265 :attr:`tzinfo` members, the comparands are first adjusted by subtracting their
1266 UTC offsets (obtained from ``self.utcoffset()``). In order to stop mixed-type
1267 comparisons from falling back to the default comparison by object address, when
1268 a :class:`time` object is compared to an object of a different type,
1269 :exc:`TypeError` is raised unless the comparison is ``==`` or ``!=``. The
1270 latter cases return :const:`False` or :const:`True`, respectively.
1271
1272* hash, use as dict key
1273
1274* efficient pickling
1275
1276* in Boolean contexts, a :class:`time` object is considered to be true if and
1277 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1278 ``0`` if that's ``None``), the result is non-zero.
1279
Georg Brandl116aa622007-08-15 14:28:22 +00001280
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001281Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001282
1283.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1284
1285 Return a :class:`time` with the same value, except for those members given new
1286 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
1287 can be specified to create a naive :class:`time` from an aware :class:`time`,
1288 without conversion of the time members.
1289
1290
1291.. method:: time.isoformat()
1292
1293 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1294 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1295 6-character string is appended, giving the UTC offset in (signed) hours and
1296 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1297
1298
1299.. method:: time.__str__()
1300
1301 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1302
1303
1304.. method:: time.strftime(format)
1305
1306 Return a string representing the time, controlled by an explicit format string.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001307 See section :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001308
1309
1310.. method:: time.utcoffset()
1311
1312 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1313 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1314 return ``None`` or a :class:`timedelta` object representing a whole number of
1315 minutes with magnitude less than one day.
1316
1317
1318.. method:: time.dst()
1319
1320 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1321 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1322 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1323 with magnitude less than one day.
1324
1325
1326.. method:: time.tzname()
1327
1328 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1329 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1330 return ``None`` or a string object.
1331
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001332
Christian Heimesfe337bf2008-03-23 21:54:12 +00001333Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001334
Christian Heimes895627f2007-12-08 17:28:33 +00001335 >>> from datetime import time, tzinfo
1336 >>> class GMT1(tzinfo):
1337 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001338 ... return timedelta(hours=1)
1339 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001340 ... return timedelta(0)
1341 ... def tzname(self,dt):
1342 ... return "Europe/Prague"
1343 ...
1344 >>> t = time(12, 10, 30, tzinfo=GMT1())
1345 >>> t # doctest: +ELLIPSIS
1346 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1347 >>> gmt = GMT1()
1348 >>> t.isoformat()
1349 '12:10:30+01:00'
1350 >>> t.dst()
1351 datetime.timedelta(0)
1352 >>> t.tzname()
1353 'Europe/Prague'
1354 >>> t.strftime("%H:%M:%S %Z")
1355 '12:10:30 Europe/Prague'
1356
Georg Brandl116aa622007-08-15 14:28:22 +00001357
1358.. _datetime-tzinfo:
1359
1360:class:`tzinfo` Objects
1361-----------------------
1362
Brett Cannone1327f72009-01-29 04:10:21 +00001363:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001364instantiated directly. You need to derive a concrete subclass, and (at least)
1365supply implementations of the standard :class:`tzinfo` methods needed by the
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001366:class:`datetime` methods you use. The :mod:`datetime` module supplies
1367a simple concrete subclass of :class:`tzinfo` :class:`timezone` which can reprsent
1368timezones with fixed offset from UTC such as UTC itself or North American EST and
1369EDT.
Georg Brandl116aa622007-08-15 14:28:22 +00001370
1371An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1372constructors for :class:`datetime` and :class:`time` objects. The latter objects
1373view their members as being in local time, and the :class:`tzinfo` object
1374supports methods revealing offset of local time from UTC, the name of the time
1375zone, and DST offset, all relative to a date or time object passed to them.
1376
1377Special requirement for pickling: A :class:`tzinfo` subclass must have an
1378:meth:`__init__` method that can be called with no arguments, else it can be
1379pickled but possibly not unpickled again. This is a technical requirement that
1380may be relaxed in the future.
1381
1382A concrete subclass of :class:`tzinfo` may need to implement the following
1383methods. Exactly which methods are needed depends on the uses made of aware
1384:mod:`datetime` objects. If in doubt, simply implement all of them.
1385
1386
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001387.. method:: tzinfo.utcoffset(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001388
1389 Return offset of local time from UTC, in minutes east of UTC. If local time is
1390 west of UTC, this should be negative. Note that this is intended to be the
1391 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1392 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1393 the UTC offset isn't known, return ``None``. Else the value returned must be a
1394 :class:`timedelta` object specifying a whole number of minutes in the range
1395 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1396 than one day). Most implementations of :meth:`utcoffset` will probably look
1397 like one of these two::
1398
1399 return CONSTANT # fixed-offset class
1400 return CONSTANT + self.dst(dt) # daylight-aware class
1401
1402 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1403 ``None`` either.
1404
1405 The default implementation of :meth:`utcoffset` raises
1406 :exc:`NotImplementedError`.
1407
1408
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001409.. method:: tzinfo.dst(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001410
1411 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1412 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1413 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1414 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1415 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1416 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1417 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
1418 member's :meth:`dst` method to determine how the :attr:`tm_isdst` flag should be
1419 set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for DST changes
1420 when crossing time zones.
1421
1422 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1423 daylight times must be consistent in this sense:
1424
1425 ``tz.utcoffset(dt) - tz.dst(dt)``
1426
1427 must return the same result for every :class:`datetime` *dt* with ``dt.tzinfo ==
1428 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1429 zone's "standard offset", which should not depend on the date or the time, but
1430 only on geographic location. The implementation of :meth:`datetime.astimezone`
1431 relies on this, but cannot detect violations; it's the programmer's
1432 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1433 this, it may be able to override the default implementation of
1434 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1435
1436 Most implementations of :meth:`dst` will probably look like one of these two::
1437
1438 def dst(self):
1439 # a fixed-offset class: doesn't account for DST
1440 return timedelta(0)
1441
1442 or ::
1443
1444 def dst(self):
1445 # Code to set dston and dstoff to the time zone's DST
1446 # transition times based on the input dt.year, and expressed
1447 # in standard local time. Then
1448
1449 if dston <= dt.replace(tzinfo=None) < dstoff:
1450 return timedelta(hours=1)
1451 else:
1452 return timedelta(0)
1453
1454 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1455
1456
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001457.. method:: tzinfo.tzname(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001458
1459 Return the time zone name corresponding to the :class:`datetime` object *dt*, as
1460 a string. Nothing about string names is defined by the :mod:`datetime` module,
1461 and there's no requirement that it mean anything in particular. For example,
1462 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1463 valid replies. Return ``None`` if a string name isn't known. Note that this is
1464 a method rather than a fixed string primarily because some :class:`tzinfo`
1465 subclasses will wish to return different names depending on the specific value
1466 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1467 daylight time.
1468
1469 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1470
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001471
Georg Brandl116aa622007-08-15 14:28:22 +00001472These methods are called by a :class:`datetime` or :class:`time` object, in
1473response to their methods of the same names. A :class:`datetime` object passes
1474itself as the argument, and a :class:`time` object passes ``None`` as the
1475argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
1476accept a *dt* argument of ``None``, or of class :class:`datetime`.
1477
1478When ``None`` is passed, it's up to the class designer to decide the best
1479response. For example, returning ``None`` is appropriate if the class wishes to
1480say that time objects don't participate in the :class:`tzinfo` protocols. It
1481may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1482there is no other convention for discovering the standard offset.
1483
1484When a :class:`datetime` object is passed in response to a :class:`datetime`
1485method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1486rely on this, unless user code calls :class:`tzinfo` methods directly. The
1487intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1488time, and not need worry about objects in other timezones.
1489
1490There is one more :class:`tzinfo` method that a subclass may wish to override:
1491
1492
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001493.. method:: tzinfo.fromutc(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001494
1495 This is called from the default :class:`datetime.astimezone()` implementation.
1496 When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members
1497 are to be viewed as expressing a UTC time. The purpose of :meth:`fromutc` is to
1498 adjust the date and time members, returning an equivalent datetime in *self*'s
1499 local time.
1500
1501 Most :class:`tzinfo` subclasses should be able to inherit the default
1502 :meth:`fromutc` implementation without problems. It's strong enough to handle
1503 fixed-offset time zones, and time zones accounting for both standard and
1504 daylight time, and the latter even if the DST transition times differ in
1505 different years. An example of a time zone the default :meth:`fromutc`
1506 implementation may not handle correctly in all cases is one where the standard
1507 offset (from UTC) depends on the specific date and time passed, which can happen
1508 for political reasons. The default implementations of :meth:`astimezone` and
1509 :meth:`fromutc` may not produce the result you want if the result is one of the
1510 hours straddling the moment the standard offset changes.
1511
1512 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1513 like::
1514
1515 def fromutc(self, dt):
1516 # raise ValueError error if dt.tzinfo is not self
1517 dtoff = dt.utcoffset()
1518 dtdst = dt.dst()
1519 # raise ValueError if dtoff is None or dtdst is None
1520 delta = dtoff - dtdst # this is self's standard offset
1521 if delta:
1522 dt += delta # convert to standard local time
1523 dtdst = dt.dst()
1524 # raise ValueError if dtdst is None
1525 if dtdst:
1526 return dt + dtdst
1527 else:
1528 return dt
1529
1530Example :class:`tzinfo` classes:
1531
1532.. literalinclude:: ../includes/tzinfo-examples.py
1533
1534
1535Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1536subclass accounting for both standard and daylight time, at the DST transition
1537points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00001538minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
15391:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001540
1541 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1542 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1543 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1544
1545 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1546
1547 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1548
1549When DST starts (the "start" line), the local wall clock leaps from 1:59 to
15503:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1551``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1552begins. In order for :meth:`astimezone` to make this guarantee, the
1553:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1554Eastern) to be in daylight time.
1555
1556When DST ends (the "end" line), there's a potentially worse problem: there's an
1557hour that can't be spelled unambiguously in local wall time: the last hour of
1558daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1559daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1560to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1561:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1562hours into the same local hour then. In the Eastern example, UTC times of the
1563form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1564:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1565consider times in the "repeated hour" to be in standard time. This is easily
1566arranged, as in the example, by expressing DST switch times in the time zone's
1567standard local time.
1568
1569Applications that can't bear such ambiguities should avoid using hybrid
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001570:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`,
1571or any other fixed-offset :class:`tzinfo` subclass (such as a class representing
1572only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
1573
1574
1575.. _datetime-timezone:
1576
1577:class:`timezone` Objects
1578--------------------------
1579
Alexander Belopolsky6d3c9a62011-05-04 10:28:26 -04001580The :class:`timezone` class is a subclass of :class:`tzinfo`, each
1581instance of which represents a timezone defined by a fixed offset from
1582UTC. Note that objects of this class cannot be used to represent
1583timezone information in the locations where different offsets are used
1584in different days of the year or where historical changes have been
1585made to civil time.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001586
1587
1588.. class:: timezone(offset[, name])
1589
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001590 The *offset* argument must be specified as a :class:`timedelta`
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001591 object representing the difference between the local time and UTC. It must
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001592 be strictly between ``-timedelta(hours=24)`` and
1593 ``timedelta(hours=24)`` and represent a whole number of minutes,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001594 otherwise :exc:`ValueError` is raised.
1595
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001596 The *name* argument is optional. If specified it must be a string that
1597 is used as the value returned by the ``tzname(dt)`` method. Otherwise,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001598 ``tzname(dt)`` returns a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001599 *offset*, HH and MM are two digits of ``offset.hours`` and
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001600 ``offset.minutes`` respectively.
1601
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001602.. method:: timezone.utcoffset(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001603
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001604 Return the fixed value specified when the :class:`timezone` instance is
1605 constructed. The *dt* argument is ignored. The return value is a
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001606 :class:`timedelta` instance equal to the difference between the
1607 local time and UTC.
1608
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001609.. method:: timezone.tzname(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001610
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001611 Return the fixed value specified when the :class:`timezone` instance is
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001612 constructed or a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001613 *offset*, HH and MM are two digits of ``offset.hours`` and
1614 ``offset.minutes`` respectively.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001615
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001616.. method:: timezone.dst(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001617
1618 Always returns ``None``.
1619
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001620.. method:: timezone.fromutc(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001621
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001622 Return ``dt + offset``. The *dt* argument must be an aware
1623 :class:`datetime` instance, with ``tzinfo`` set to ``self``.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001624
1625Class attributes:
1626
1627.. attribute:: timezone.utc
1628
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001629 The UTC timezone, ``timezone(timedelta(0))``.
Georg Brandl48310cd2009-01-03 21:18:54 +00001630
Georg Brandl116aa622007-08-15 14:28:22 +00001631
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001632.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00001633
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001634:meth:`strftime` and :meth:`strptime` Behavior
1635----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001636
1637:class:`date`, :class:`datetime`, and :class:`time` objects all support a
1638``strftime(format)`` method, to create a string representing the time under the
1639control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1640acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1641although not all objects support a :meth:`timetuple` method.
1642
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001643Conversely, the :meth:`datetime.strptime` class method creates a
1644:class:`datetime` object from a string representing a date and time and a
1645corresponding format string. ``datetime.strptime(date_string, format)`` is
1646equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1647
Georg Brandl116aa622007-08-15 14:28:22 +00001648For :class:`time` objects, the format codes for year, month, and day should not
1649be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001650is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00001651
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001652For :class:`date` objects, the format codes for hours, minutes, seconds, and
1653microseconds should not be used, as :class:`date` objects have no such
1654values. If they're used anyway, ``0`` is substituted for them.
1655
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001656For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1657strings.
1658
1659For an aware object:
1660
1661``%z``
1662 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1663 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1664 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1665 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1666 replaced with the string ``'-0330'``.
1667
1668``%Z``
1669 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1670 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl116aa622007-08-15 14:28:22 +00001671
Georg Brandl116aa622007-08-15 14:28:22 +00001672The full set of format codes supported varies across platforms, because Python
1673calls the platform C library's :func:`strftime` function, and platform
Georg Brandl48310cd2009-01-03 21:18:54 +00001674variations are common.
Christian Heimes895627f2007-12-08 17:28:33 +00001675
1676The following is a list of all the format codes that the C standard (1989
1677version) requires, and these work on all platforms with a standard C
1678implementation. Note that the 1999 version of the C standard added additional
1679format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001680
Christian Heimes895627f2007-12-08 17:28:33 +00001681+-----------+--------------------------------+-------+
1682| Directive | Meaning | Notes |
1683+===========+================================+=======+
1684| ``%a`` | Locale's abbreviated weekday | |
1685| | name. | |
1686+-----------+--------------------------------+-------+
1687| ``%A`` | Locale's full weekday name. | |
1688+-----------+--------------------------------+-------+
1689| ``%b`` | Locale's abbreviated month | |
1690| | name. | |
1691+-----------+--------------------------------+-------+
1692| ``%B`` | Locale's full month name. | |
1693+-----------+--------------------------------+-------+
1694| ``%c`` | Locale's appropriate date and | |
1695| | time representation. | |
1696+-----------+--------------------------------+-------+
1697| ``%d`` | Day of the month as a decimal | |
1698| | number [01,31]. | |
1699+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001700| ``%f`` | Microsecond as a decimal | \(1) |
1701| | number [0,999999], zero-padded | |
1702| | on the left | |
1703+-----------+--------------------------------+-------+
Christian Heimes895627f2007-12-08 17:28:33 +00001704| ``%H`` | Hour (24-hour clock) as a | |
1705| | decimal number [00,23]. | |
1706+-----------+--------------------------------+-------+
1707| ``%I`` | Hour (12-hour clock) as a | |
1708| | decimal number [01,12]. | |
1709+-----------+--------------------------------+-------+
1710| ``%j`` | Day of the year as a decimal | |
1711| | number [001,366]. | |
1712+-----------+--------------------------------+-------+
1713| ``%m`` | Month as a decimal number | |
1714| | [01,12]. | |
1715+-----------+--------------------------------+-------+
1716| ``%M`` | Minute as a decimal number | |
1717| | [00,59]. | |
1718+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001719| ``%p`` | Locale's equivalent of either | \(2) |
Christian Heimes895627f2007-12-08 17:28:33 +00001720| | AM or PM. | |
1721+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001722| ``%S`` | Second as a decimal number | \(3) |
Alexander Belopolsky9971e002011-01-10 22:56:14 +00001723| | [00,59]. | |
Christian Heimes895627f2007-12-08 17:28:33 +00001724+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001725| ``%U`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001726| | (Sunday as the first day of | |
1727| | the week) as a decimal number | |
1728| | [00,53]. All days in a new | |
1729| | year preceding the first | |
1730| | Sunday are considered to be in | |
1731| | week 0. | |
1732+-----------+--------------------------------+-------+
1733| ``%w`` | Weekday as a decimal number | |
1734| | [0(Sunday),6]. | |
1735+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001736| ``%W`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001737| | (Monday as the first day of | |
1738| | the week) as a decimal number | |
1739| | [00,53]. All days in a new | |
1740| | year preceding the first | |
1741| | Monday are considered to be in | |
1742| | week 0. | |
1743+-----------+--------------------------------+-------+
1744| ``%x`` | Locale's appropriate date | |
1745| | representation. | |
1746+-----------+--------------------------------+-------+
1747| ``%X`` | Locale's appropriate time | |
1748| | representation. | |
1749+-----------+--------------------------------+-------+
1750| ``%y`` | Year without century as a | |
1751| | decimal number [00,99]. | |
1752+-----------+--------------------------------+-------+
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001753| ``%Y`` | Year with century as a decimal | \(5) |
Alexander Belopolsky89da3492011-05-02 13:14:24 -04001754| | number [0001,9999]. | |
Christian Heimes895627f2007-12-08 17:28:33 +00001755+-----------+--------------------------------+-------+
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001756| ``%z`` | UTC offset in the form +HHMM | \(6) |
Christian Heimes895627f2007-12-08 17:28:33 +00001757| | or -HHMM (empty string if the | |
1758| | the object is naive). | |
1759+-----------+--------------------------------+-------+
1760| ``%Z`` | Time zone name (empty string | |
1761| | if the object is naive). | |
1762+-----------+--------------------------------+-------+
1763| ``%%`` | A literal ``'%'`` character. | |
1764+-----------+--------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001765
Christian Heimes895627f2007-12-08 17:28:33 +00001766Notes:
1767
1768(1)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001769 When used with the :meth:`strptime` method, the ``%f`` directive
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001770 accepts from one to six digits and zero pads on the right. ``%f`` is
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001771 an extension to the set of format characters in the C standard (but
1772 implemented separately in datetime objects, and therefore always
1773 available).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001774
1775(2)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001776 When used with the :meth:`strptime` method, the ``%p`` directive only affects
Christian Heimes895627f2007-12-08 17:28:33 +00001777 the output hour field if the ``%I`` directive is used to parse the hour.
1778
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001779(3)
Alexander Belopolsky9971e002011-01-10 22:56:14 +00001780 Unlike :mod:`time` module, :mod:`datetime` module does not support
1781 leap seconds.
Christian Heimes895627f2007-12-08 17:28:33 +00001782
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001783(4)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001784 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in
Christian Heimes895627f2007-12-08 17:28:33 +00001785 calculations when the day of the week and the year are specified.
1786
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001787(5)
Alexander Belopolsky89da3492011-05-02 13:14:24 -04001788 The :meth:`strptime` method can
Alexander Belopolsky5fc850b2011-01-10 23:31:51 +00001789 parse years in the full [1, 9999] range, but years < 1000 must be
1790 zero-filled to 4-digit width.
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001791
1792 .. versionchanged:: 3.2
1793 In previous versions, :meth:`strftime` method was restricted to
1794 years >= 1900.
1795
Alexander Belopolsky5611a1c2011-05-02 14:14:48 -04001796 .. versionchanged:: 3.3
1797 In version 3.2, :meth:`strftime` method was restricted to
1798 years >= 1000.
1799
Alexander Belopolsky085556a2011-01-10 23:28:33 +00001800(6)
Christian Heimes895627f2007-12-08 17:28:33 +00001801 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1802 ``%z`` is replaced with the string ``'-0330'``.
Alexander Belopolskyca94f552010-06-17 18:30:34 +00001803
Georg Brandl67b21b72010-08-17 15:07:14 +00001804.. versionchanged:: 3.2
1805 When the ``%z`` directive is provided to the :meth:`strptime` method, an
1806 aware :class:`datetime` object will be produced. The ``tzinfo`` of the
1807 result will be set to a :class:`timezone` instance.