blob: 22c82e812797068bb83b9e36a8ffb5cf7fa12cbc [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
Mark Dickinson7c186e22010-04-20 22:32:49 +0000305.. versionadded:: 3.2
306 Floor division and true division of a :class:`timedelta` object by
307 another :class:`timedelta` object are now supported, as are
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000308 remainder operations and the :func:`divmod` function. True
309 division and multiplication of a :class:`timedelta` object by
310 a :class:`float` object are now supported.
Mark Dickinson7c186e22010-04-20 22:32:49 +0000311
312
Georg Brandl116aa622007-08-15 14:28:22 +0000313Comparisons of :class:`timedelta` objects are supported with the
314:class:`timedelta` object representing the smaller duration considered to be the
315smaller timedelta. In order to stop mixed-type comparisons from falling back to
316the default comparison by object address, when a :class:`timedelta` object is
317compared to an object of a different type, :exc:`TypeError` is raised unless the
318comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
319:const:`True`, respectively.
320
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000321:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl116aa622007-08-15 14:28:22 +0000322efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
323considered to be true if and only if it isn't equal to ``timedelta(0)``.
324
Antoine Pitroube6859d2009-11-25 23:02:32 +0000325Instance methods:
326
327.. method:: timedelta.total_seconds()
328
329 Return the total number of seconds contained in the duration. Equivalent to
Mark Dickinson0381e3f2010-05-08 14:35:02 +0000330 ``td / timedelta(seconds=1)``.
331
332 Note that for very large time intervals (greater than 270 years on
333 most platforms) this method will lose microsecond accuracy.
Antoine Pitroube6859d2009-11-25 23:02:32 +0000334
335 .. versionadded:: 3.2
336
337
Christian Heimesfe337bf2008-03-23 21:54:12 +0000338Example usage:
Georg Brandl48310cd2009-01-03 21:18:54 +0000339
Christian Heimes895627f2007-12-08 17:28:33 +0000340 >>> from datetime import timedelta
341 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000342 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Christian Heimes895627f2007-12-08 17:28:33 +0000343 ... minutes=50, seconds=600) # adds up to 365 days
Antoine Pitroube6859d2009-11-25 23:02:32 +0000344 >>> year.total_seconds()
345 31536000.0
Christian Heimes895627f2007-12-08 17:28:33 +0000346 >>> year == another_year
347 True
348 >>> ten_years = 10 * year
349 >>> ten_years, ten_years.days // 365
350 (datetime.timedelta(3650), 10)
351 >>> nine_years = ten_years - year
352 >>> nine_years, nine_years.days // 365
353 (datetime.timedelta(3285), 9)
354 >>> three_years = nine_years // 3;
355 >>> three_years, three_years.days // 365
356 (datetime.timedelta(1095), 3)
357 >>> abs(three_years - ten_years) == 2 * three_years + year
358 True
359
Georg Brandl116aa622007-08-15 14:28:22 +0000360
361.. _datetime-date:
362
363:class:`date` Objects
364---------------------
365
366A :class:`date` object represents a date (year, month and day) in an idealized
367calendar, the current Gregorian calendar indefinitely extended in both
368directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
369called day number 2, and so on. This matches the definition of the "proleptic
370Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
371where it's the base calendar for all computations. See the book for algorithms
372for converting between proleptic Gregorian ordinals and many other calendar
373systems.
374
375
376.. class:: date(year, month, day)
377
Georg Brandl5c106642007-11-29 17:41:05 +0000378 All arguments are required. Arguments may be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000379 ranges:
380
381 * ``MINYEAR <= year <= MAXYEAR``
382 * ``1 <= month <= 12``
383 * ``1 <= day <= number of days in the given month and year``
384
385 If an argument outside those ranges is given, :exc:`ValueError` is raised.
386
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000387
Georg Brandl116aa622007-08-15 14:28:22 +0000388Other constructors, all class methods:
389
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000390.. classmethod:: date.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000391
392 Return the current local date. This is equivalent to
393 ``date.fromtimestamp(time.time())``.
394
395
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000396.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000397
398 Return the local date corresponding to the POSIX timestamp, such as is returned
399 by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out
400 of the range of values supported by the platform C :cfunc:`localtime` function.
401 It's common for this to be restricted to years from 1970 through 2038. Note
402 that on non-POSIX systems that include leap seconds in their notion of a
403 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
404
405
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000406.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000407
408 Return the date corresponding to the proleptic Gregorian ordinal, where January
409 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
410 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
411 d``.
412
Georg Brandl116aa622007-08-15 14:28:22 +0000413
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000414Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000415
416.. attribute:: date.min
417
418 The earliest representable date, ``date(MINYEAR, 1, 1)``.
419
420
421.. attribute:: date.max
422
423 The latest representable date, ``date(MAXYEAR, 12, 31)``.
424
425
426.. attribute:: date.resolution
427
428 The smallest possible difference between non-equal date objects,
429 ``timedelta(days=1)``.
430
Georg Brandl116aa622007-08-15 14:28:22 +0000431
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000432Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000433
434.. attribute:: date.year
435
436 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
437
438
439.. attribute:: date.month
440
441 Between 1 and 12 inclusive.
442
443
444.. attribute:: date.day
445
446 Between 1 and the number of days in the given month of the given year.
447
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000448
Georg Brandl116aa622007-08-15 14:28:22 +0000449Supported operations:
450
451+-------------------------------+----------------------------------------------+
452| Operation | Result |
453+===============================+==============================================+
454| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
455| | from *date1*. (1) |
456+-------------------------------+----------------------------------------------+
457| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
458| | timedelta == date1``. (2) |
459+-------------------------------+----------------------------------------------+
460| ``timedelta = date1 - date2`` | \(3) |
461+-------------------------------+----------------------------------------------+
462| ``date1 < date2`` | *date1* is considered less than *date2* when |
463| | *date1* precedes *date2* in time. (4) |
464+-------------------------------+----------------------------------------------+
465
466Notes:
467
468(1)
469 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
470 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
471 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
472 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
473 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
474
475(2)
476 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
477 isolation can overflow in cases where date1 - timedelta does not.
478 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
479
480(3)
481 This is exact, and cannot overflow. timedelta.seconds and
482 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
483
484(4)
485 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
486 date2.toordinal()``. In order to stop comparison from falling back to the
487 default scheme of comparing object addresses, date comparison normally raises
488 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
489 However, ``NotImplemented`` is returned instead if the other comparand has a
490 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
491 chance at implementing mixed-type comparison. If not, when a :class:`date`
492 object is compared to an object of a different type, :exc:`TypeError` is raised
493 unless the comparison is ``==`` or ``!=``. The latter cases return
494 :const:`False` or :const:`True`, respectively.
495
496Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
497objects are considered to be true.
498
499Instance methods:
500
Georg Brandl116aa622007-08-15 14:28:22 +0000501.. method:: date.replace(year, month, day)
502
503 Return a date with the same value, except for those members given new values by
504 whichever keyword arguments are specified. For example, if ``d == date(2002,
505 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
506
507
508.. method:: date.timetuple()
509
510 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
511 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
512 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000513 d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1,
514 1).toordinal() + 1`` is the day number within the current year starting with
515 ``1`` for January 1st.
Georg Brandl116aa622007-08-15 14:28:22 +0000516
517
518.. method:: date.toordinal()
519
520 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
521 has ordinal 1. For any :class:`date` object *d*,
522 ``date.fromordinal(d.toordinal()) == d``.
523
524
525.. method:: date.weekday()
526
527 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
528 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
529 :meth:`isoweekday`.
530
531
532.. method:: date.isoweekday()
533
534 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
535 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
536 :meth:`weekday`, :meth:`isocalendar`.
537
538
539.. method:: date.isocalendar()
540
541 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
542
543 The ISO calendar is a widely used variant of the Gregorian calendar. See
Mark Dickinsonf964ac22009-11-03 16:29:10 +0000544 http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
545 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000546
547 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
548 Monday and ends on a Sunday. The first week of an ISO year is the first
549 (Gregorian) calendar week of a year containing a Thursday. This is called week
550 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
551
552 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
553 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
554 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
555 4).isocalendar() == (2004, 1, 7)``.
556
557
558.. method:: date.isoformat()
559
560 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
561 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
562
563
564.. method:: date.__str__()
565
566 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
567
568
569.. method:: date.ctime()
570
571 Return a string representing the date, for example ``date(2002, 12,
572 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
573 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
574 :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
575 :meth:`date.ctime` does not invoke) conforms to the C standard.
576
577
578.. method:: date.strftime(format)
579
580 Return a string representing the date, controlled by an explicit format string.
581 Format codes referring to hours, minutes or seconds will see 0 values. See
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000582 section :ref:`strftime-strptime-behavior`.
583
Georg Brandl116aa622007-08-15 14:28:22 +0000584
Christian Heimes895627f2007-12-08 17:28:33 +0000585Example of counting days to an event::
586
587 >>> import time
588 >>> from datetime import date
589 >>> today = date.today()
590 >>> today
591 datetime.date(2007, 12, 5)
592 >>> today == date.fromtimestamp(time.time())
593 True
594 >>> my_birthday = date(today.year, 6, 24)
595 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000596 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000597 >>> my_birthday
598 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000599 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000600 >>> time_to_birthday.days
601 202
602
Christian Heimesfe337bf2008-03-23 21:54:12 +0000603Example of working with :class:`date`:
604
605.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000606
607 >>> from datetime import date
608 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
609 >>> d
610 datetime.date(2002, 3, 11)
611 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000612 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000613 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000614 2002 # year
615 3 # month
616 11 # day
617 0
618 0
619 0
620 0 # weekday (0 = Monday)
621 70 # 70th day in the year
622 -1
623 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000624 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000625 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000626 2002 # ISO year
627 11 # ISO week number
628 1 # ISO day number ( 1 = Monday )
629 >>> d.isoformat()
630 '2002-03-11'
631 >>> d.strftime("%d/%m/%y")
632 '11/03/02'
633 >>> d.strftime("%A %d. %B %Y")
634 'Monday 11. March 2002'
635
Georg Brandl116aa622007-08-15 14:28:22 +0000636
637.. _datetime-datetime:
638
639:class:`datetime` Objects
640-------------------------
641
642A :class:`datetime` object is a single object containing all the information
643from a :class:`date` object and a :class:`time` object. Like a :class:`date`
644object, :class:`datetime` assumes the current Gregorian calendar extended in
645both directions; like a time object, :class:`datetime` assumes there are exactly
6463600\*24 seconds in every day.
647
648Constructor:
649
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000650.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000651
652 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000653 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
654 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000655
656 * ``MINYEAR <= year <= MAXYEAR``
657 * ``1 <= month <= 12``
658 * ``1 <= day <= number of days in the given month and year``
659 * ``0 <= hour < 24``
660 * ``0 <= minute < 60``
661 * ``0 <= second < 60``
662 * ``0 <= microsecond < 1000000``
663
664 If an argument outside those ranges is given, :exc:`ValueError` is raised.
665
666Other constructors, all class methods:
667
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000668.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000669
670 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
671 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
672 :meth:`fromtimestamp`.
673
674
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000675.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000676
677 Return the current local date and time. If optional argument *tz* is ``None``
678 or not specified, this is like :meth:`today`, but, if possible, supplies more
679 precision than can be gotten from going through a :func:`time.time` timestamp
680 (for example, this may be possible on platforms supplying the C
681 :cfunc:`gettimeofday` function).
682
683 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
684 current date and time are converted to *tz*'s time zone. In this case the
685 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
686 See also :meth:`today`, :meth:`utcnow`.
687
688
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000689.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000690
691 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
692 :meth:`now`, but returns the current UTC date and time, as a naive
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000693 :class:`datetime` object. An aware current UTC datetime can be obtained by
694 calling ``datetime.now(timezone.utc)``. See also :meth:`now`.
Georg Brandl116aa622007-08-15 14:28:22 +0000695
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000696.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000697
698 Return the local date and time corresponding to the POSIX timestamp, such as is
699 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
700 specified, the timestamp is converted to the platform's local date and time, and
701 the returned :class:`datetime` object is naive.
702
703 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
704 timestamp is converted to *tz*'s time zone. In this case the result is
705 equivalent to
706 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
707
708 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
709 the range of values supported by the platform C :cfunc:`localtime` or
710 :cfunc:`gmtime` functions. It's common for this to be restricted to years in
711 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
712 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
713 and then it's possible to have two timestamps differing by a second that yield
714 identical :class:`datetime` objects. See also :meth:`utcfromtimestamp`.
715
716
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000717.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000718
719 Return the UTC :class:`datetime` corresponding to the POSIX timestamp, with
720 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
721 out of the range of values supported by the platform C :cfunc:`gmtime` function.
722 It's common for this to be restricted to years in 1970 through 2038. See also
723 :meth:`fromtimestamp`.
724
725
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000726.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000727
728 Return the :class:`datetime` corresponding to the proleptic Gregorian ordinal,
729 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
730 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
731 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
732
733
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000734.. classmethod:: datetime.combine(date, time)
Georg Brandl116aa622007-08-15 14:28:22 +0000735
736 Return a new :class:`datetime` object whose date members are equal to the given
737 :class:`date` object's, and whose time and :attr:`tzinfo` members are equal to
738 the given :class:`time` object's. For any :class:`datetime` object *d*, ``d ==
739 datetime.combine(d.date(), d.timetz())``. If date is a :class:`datetime`
740 object, its time and :attr:`tzinfo` members are ignored.
741
742
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000743.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000744
745 Return a :class:`datetime` corresponding to *date_string*, parsed according to
746 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
747 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
748 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 +0000749 time tuple. See section :ref:`strftime-strptime-behavior`.
750
Georg Brandl116aa622007-08-15 14:28:22 +0000751
Georg Brandl116aa622007-08-15 14:28:22 +0000752
753Class attributes:
754
Georg Brandl116aa622007-08-15 14:28:22 +0000755.. attribute:: datetime.min
756
757 The earliest representable :class:`datetime`, ``datetime(MINYEAR, 1, 1,
758 tzinfo=None)``.
759
760
761.. attribute:: datetime.max
762
763 The latest representable :class:`datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
764 59, 999999, tzinfo=None)``.
765
766
767.. attribute:: datetime.resolution
768
769 The smallest possible difference between non-equal :class:`datetime` objects,
770 ``timedelta(microseconds=1)``.
771
Georg Brandl116aa622007-08-15 14:28:22 +0000772
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000773Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000774
775.. attribute:: datetime.year
776
777 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
778
779
780.. attribute:: datetime.month
781
782 Between 1 and 12 inclusive.
783
784
785.. attribute:: datetime.day
786
787 Between 1 and the number of days in the given month of the given year.
788
789
790.. attribute:: datetime.hour
791
792 In ``range(24)``.
793
794
795.. attribute:: datetime.minute
796
797 In ``range(60)``.
798
799
800.. attribute:: datetime.second
801
802 In ``range(60)``.
803
804
805.. attribute:: datetime.microsecond
806
807 In ``range(1000000)``.
808
809
810.. attribute:: datetime.tzinfo
811
812 The object passed as the *tzinfo* argument to the :class:`datetime` constructor,
813 or ``None`` if none was passed.
814
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000815
Georg Brandl116aa622007-08-15 14:28:22 +0000816Supported operations:
817
818+---------------------------------------+-------------------------------+
819| Operation | Result |
820+=======================================+===============================+
821| ``datetime2 = datetime1 + timedelta`` | \(1) |
822+---------------------------------------+-------------------------------+
823| ``datetime2 = datetime1 - timedelta`` | \(2) |
824+---------------------------------------+-------------------------------+
825| ``timedelta = datetime1 - datetime2`` | \(3) |
826+---------------------------------------+-------------------------------+
827| ``datetime1 < datetime2`` | Compares :class:`datetime` to |
828| | :class:`datetime`. (4) |
829+---------------------------------------+-------------------------------+
830
831(1)
832 datetime2 is a duration of timedelta removed from datetime1, moving forward in
833 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
834 result has the same :attr:`tzinfo` member as the input datetime, and datetime2 -
835 datetime1 == timedelta after. :exc:`OverflowError` is raised if datetime2.year
836 would be smaller than :const:`MINYEAR` or larger than :const:`MAXYEAR`. Note
837 that no time zone adjustments are done even if the input is an aware object.
838
839(2)
840 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
841 addition, the result has the same :attr:`tzinfo` member as the input datetime,
842 and no time zone adjustments are done even if the input is aware. This isn't
843 quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation
844 can overflow in cases where datetime1 - timedelta does not.
845
846(3)
847 Subtraction of a :class:`datetime` from a :class:`datetime` is defined only if
848 both operands are naive, or if both are aware. If one is aware and the other is
849 naive, :exc:`TypeError` is raised.
850
851 If both are naive, or both are aware and have the same :attr:`tzinfo` member,
852 the :attr:`tzinfo` members are ignored, and the result is a :class:`timedelta`
853 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
854 are done in this case.
855
856 If both are aware and have different :attr:`tzinfo` members, ``a-b`` acts as if
857 *a* and *b* were first converted to naive UTC datetimes first. The result is
858 ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) -
859 b.utcoffset())`` except that the implementation never overflows.
860
861(4)
862 *datetime1* is considered less than *datetime2* when *datetime1* precedes
863 *datetime2* in time.
864
865 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
866 If both comparands are aware, and have the same :attr:`tzinfo` member, the
867 common :attr:`tzinfo` member is ignored and the base datetimes are compared. If
868 both comparands are aware and have different :attr:`tzinfo` members, the
869 comparands are first adjusted by subtracting their UTC offsets (obtained from
870 ``self.utcoffset()``).
871
872 .. note::
873
874 In order to stop comparison from falling back to the default scheme of comparing
875 object addresses, datetime comparison normally raises :exc:`TypeError` if the
876 other comparand isn't also a :class:`datetime` object. However,
877 ``NotImplemented`` is returned instead if the other comparand has a
878 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
879 chance at implementing mixed-type comparison. If not, when a :class:`datetime`
880 object is compared to an object of a different type, :exc:`TypeError` is raised
881 unless the comparison is ``==`` or ``!=``. The latter cases return
882 :const:`False` or :const:`True`, respectively.
883
884:class:`datetime` objects can be used as dictionary keys. In Boolean contexts,
885all :class:`datetime` objects are considered to be true.
886
887Instance methods:
888
Georg Brandl116aa622007-08-15 14:28:22 +0000889.. method:: datetime.date()
890
891 Return :class:`date` object with same year, month and day.
892
893
894.. method:: datetime.time()
895
896 Return :class:`time` object with same hour, minute, second and microsecond.
897 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
898
899
900.. method:: datetime.timetz()
901
902 Return :class:`time` object with same hour, minute, second, microsecond, and
903 tzinfo members. See also method :meth:`time`.
904
905
906.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
907
908 Return a datetime with the same members, except for those members given new
909 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
910 can be specified to create a naive datetime from an aware datetime with no
911 conversion of date and time members.
912
913
914.. method:: datetime.astimezone(tz)
915
916 Return a :class:`datetime` object with new :attr:`tzinfo` member *tz*, adjusting
917 the date and time members so the result is the same UTC time as *self*, but in
918 *tz*'s local time.
919
920 *tz* must be an instance of a :class:`tzinfo` subclass, and its
921 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
922 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
923 not return ``None``).
924
925 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
926 adjustment of date or time members is performed. Else the result is local time
927 in time zone *tz*, representing the same UTC time as *self*: after ``astz =
928 dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have the same date
929 and time members as ``dt - dt.utcoffset()``. The discussion of class
930 :class:`tzinfo` explains the cases at Daylight Saving Time transition boundaries
931 where this cannot be achieved (an issue only if *tz* models both standard and
932 daylight time).
933
934 If you merely want to attach a time zone object *tz* to a datetime *dt* without
935 adjustment of date and time members, use ``dt.replace(tzinfo=tz)``. If you
936 merely want to remove the time zone object from an aware datetime *dt* without
937 conversion of date and time members, use ``dt.replace(tzinfo=None)``.
938
939 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
940 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
941 Ignoring error cases, :meth:`astimezone` acts like::
942
943 def astimezone(self, tz):
944 if self.tzinfo is tz:
945 return self
946 # Convert self to UTC, and attach the new time zone object.
947 utc = (self - self.utcoffset()).replace(tzinfo=tz)
948 # Convert from UTC to tz's local time.
949 return tz.fromutc(utc)
950
951
952.. method:: datetime.utcoffset()
953
954 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
955 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
956 return ``None``, or a :class:`timedelta` object representing a whole number of
957 minutes with magnitude less than one day.
958
959
960.. method:: datetime.dst()
961
962 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
963 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
964 ``None``, or a :class:`timedelta` object representing a whole number of minutes
965 with magnitude less than one day.
966
967
968.. method:: datetime.tzname()
969
970 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
971 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
972 ``None`` or a string object,
973
974
975.. method:: datetime.timetuple()
976
977 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
978 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000979 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
980 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
981 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
982 of the result is set according to the :meth:`dst` method: :attr:`tzinfo` is
983 ``None`` or :meth:`dst`` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
984 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
Alexander Belopolskyda62f2f2010-06-09 17:11:01 +0000985 else :attr:`tm_isdst` is set to ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +0000986
987
988.. method:: datetime.utctimetuple()
989
990 If :class:`datetime` instance *d* is naive, this is the same as
991 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
992 ``d.dst()`` returns. DST is never in effect for a UTC time.
993
994 If *d* is aware, *d* is normalized to UTC time, by subtracting
Alexander Belopolsky75f94c22010-06-21 15:21:14 +0000995 ``d.utcoffset()``, and a :class:`time.struct_time` for the
996 normalized time is returned. :attr:`tm_isdst` is forced to 0. Note
997 that an :exc:`OverflowError` may be raised if *d*.year was
998 ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
Georg Brandl116aa622007-08-15 14:28:22 +0000999 boundary.
1000
1001
1002.. method:: datetime.toordinal()
1003
1004 Return the proleptic Gregorian ordinal of the date. The same as
1005 ``self.date().toordinal()``.
1006
1007
1008.. method:: datetime.weekday()
1009
1010 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
1011 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
1012
1013
1014.. method:: datetime.isoweekday()
1015
1016 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
1017 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
1018 :meth:`isocalendar`.
1019
1020
1021.. method:: datetime.isocalendar()
1022
1023 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
1024 ``self.date().isocalendar()``.
1025
1026
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001027.. method:: datetime.isoformat(sep='T')
Georg Brandl116aa622007-08-15 14:28:22 +00001028
1029 Return a string representing the date and time in ISO 8601 format,
1030 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
1031 YYYY-MM-DDTHH:MM:SS
1032
1033 If :meth:`utcoffset` does not return ``None``, a 6-character string is
1034 appended, giving the UTC offset in (signed) hours and minutes:
1035 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
1036 YYYY-MM-DDTHH:MM:SS+HH:MM
1037
1038 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +00001039 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +00001040
1041 >>> from datetime import tzinfo, timedelta, datetime
1042 >>> class TZ(tzinfo):
1043 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1044 ...
1045 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1046 '2002-12-25 00:00:00-06:39'
1047
1048
1049.. method:: datetime.__str__()
1050
1051 For a :class:`datetime` instance *d*, ``str(d)`` is equivalent to
1052 ``d.isoformat(' ')``.
1053
1054
1055.. method:: datetime.ctime()
1056
1057 Return a string representing the date and time, for example ``datetime(2002, 12,
1058 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1059 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
1060 native C :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
1061 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1062
1063
1064.. method:: datetime.strftime(format)
1065
1066 Return a string representing the date and time, controlled by an explicit format
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001067 string. See section :ref:`strftime-strptime-behavior`.
1068
Georg Brandl116aa622007-08-15 14:28:22 +00001069
Christian Heimesfe337bf2008-03-23 21:54:12 +00001070Examples of working with datetime objects:
1071
1072.. doctest::
1073
Christian Heimes895627f2007-12-08 17:28:33 +00001074 >>> from datetime import datetime, date, time
1075 >>> # Using datetime.combine()
1076 >>> d = date(2005, 7, 14)
1077 >>> t = time(12, 30)
1078 >>> datetime.combine(d, t)
1079 datetime.datetime(2005, 7, 14, 12, 30)
1080 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001081 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001082 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001083 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001084 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1085 >>> # Using datetime.strptime()
1086 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1087 >>> dt
1088 datetime.datetime(2006, 11, 21, 16, 30)
1089 >>> # Using datetime.timetuple() to get tuple of all attributes
1090 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001091 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001092 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001093 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001094 2006 # year
1095 11 # month
1096 21 # day
1097 16 # hour
1098 30 # minute
1099 0 # second
1100 1 # weekday (0 = Monday)
1101 325 # number of days since 1st January
1102 -1 # dst - method tzinfo.dst() returned None
1103 >>> # Date in ISO format
1104 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001105 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001106 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001107 ...
1108 2006 # ISO year
1109 47 # ISO week
1110 2 # ISO weekday
1111 >>> # Formatting datetime
1112 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1113 'Tuesday, 21. November 2006 04:30PM'
1114
Christian Heimesfe337bf2008-03-23 21:54:12 +00001115Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001116
1117 >>> from datetime import timedelta, datetime, tzinfo
1118 >>> class GMT1(tzinfo):
1119 ... def __init__(self): # DST starts last Sunday in March
1120 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1121 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001122 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001123 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1124 ... def utcoffset(self, dt):
1125 ... return timedelta(hours=1) + self.dst(dt)
Georg Brandl48310cd2009-01-03 21:18:54 +00001126 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001127 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1128 ... return timedelta(hours=1)
1129 ... else:
1130 ... return timedelta(0)
1131 ... def tzname(self,dt):
1132 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001133 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001134 >>> class GMT2(tzinfo):
1135 ... def __init__(self):
Georg Brandl48310cd2009-01-03 21:18:54 +00001136 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001137 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001138 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001139 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1140 ... def utcoffset(self, dt):
1141 ... return timedelta(hours=1) + self.dst(dt)
1142 ... def dst(self, dt):
1143 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1144 ... return timedelta(hours=2)
1145 ... else:
1146 ... return timedelta(0)
1147 ... def tzname(self,dt):
1148 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001149 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001150 >>> gmt1 = GMT1()
1151 >>> # Daylight Saving Time
1152 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1153 >>> dt1.dst()
1154 datetime.timedelta(0)
1155 >>> dt1.utcoffset()
1156 datetime.timedelta(0, 3600)
1157 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1158 >>> dt2.dst()
1159 datetime.timedelta(0, 3600)
1160 >>> dt2.utcoffset()
1161 datetime.timedelta(0, 7200)
1162 >>> # Convert datetime to another time zone
1163 >>> dt3 = dt2.astimezone(GMT2())
1164 >>> dt3 # doctest: +ELLIPSIS
1165 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1166 >>> dt2 # doctest: +ELLIPSIS
1167 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1168 >>> dt2.utctimetuple() == dt3.utctimetuple()
1169 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001170
Christian Heimes895627f2007-12-08 17:28:33 +00001171
Georg Brandl116aa622007-08-15 14:28:22 +00001172
1173.. _datetime-time:
1174
1175:class:`time` Objects
1176---------------------
1177
1178A time object represents a (local) time of day, independent of any particular
1179day, and subject to adjustment via a :class:`tzinfo` object.
1180
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001181.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001182
1183 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001184 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001185 following ranges:
1186
1187 * ``0 <= hour < 24``
1188 * ``0 <= minute < 60``
1189 * ``0 <= second < 60``
1190 * ``0 <= microsecond < 1000000``.
1191
1192 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1193 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1194
1195Class attributes:
1196
1197
1198.. attribute:: time.min
1199
1200 The earliest representable :class:`time`, ``time(0, 0, 0, 0)``.
1201
1202
1203.. attribute:: time.max
1204
1205 The latest representable :class:`time`, ``time(23, 59, 59, 999999)``.
1206
1207
1208.. attribute:: time.resolution
1209
1210 The smallest possible difference between non-equal :class:`time` objects,
1211 ``timedelta(microseconds=1)``, although note that arithmetic on :class:`time`
1212 objects is not supported.
1213
Georg Brandl116aa622007-08-15 14:28:22 +00001214
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001215Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001216
1217.. attribute:: time.hour
1218
1219 In ``range(24)``.
1220
1221
1222.. attribute:: time.minute
1223
1224 In ``range(60)``.
1225
1226
1227.. attribute:: time.second
1228
1229 In ``range(60)``.
1230
1231
1232.. attribute:: time.microsecond
1233
1234 In ``range(1000000)``.
1235
1236
1237.. attribute:: time.tzinfo
1238
1239 The object passed as the tzinfo argument to the :class:`time` constructor, or
1240 ``None`` if none was passed.
1241
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001242
Georg Brandl116aa622007-08-15 14:28:22 +00001243Supported operations:
1244
1245* comparison of :class:`time` to :class:`time`, where *a* is considered less
1246 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1247 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
1248 the same :attr:`tzinfo` member, the common :attr:`tzinfo` member is ignored and
1249 the base times are compared. If both comparands are aware and have different
1250 :attr:`tzinfo` members, the comparands are first adjusted by subtracting their
1251 UTC offsets (obtained from ``self.utcoffset()``). In order to stop mixed-type
1252 comparisons from falling back to the default comparison by object address, when
1253 a :class:`time` object is compared to an object of a different type,
1254 :exc:`TypeError` is raised unless the comparison is ``==`` or ``!=``. The
1255 latter cases return :const:`False` or :const:`True`, respectively.
1256
1257* hash, use as dict key
1258
1259* efficient pickling
1260
1261* in Boolean contexts, a :class:`time` object is considered to be true if and
1262 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1263 ``0`` if that's ``None``), the result is non-zero.
1264
Georg Brandl116aa622007-08-15 14:28:22 +00001265
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001266Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001267
1268.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1269
1270 Return a :class:`time` with the same value, except for those members given new
1271 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
1272 can be specified to create a naive :class:`time` from an aware :class:`time`,
1273 without conversion of the time members.
1274
1275
1276.. method:: time.isoformat()
1277
1278 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1279 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1280 6-character string is appended, giving the UTC offset in (signed) hours and
1281 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1282
1283
1284.. method:: time.__str__()
1285
1286 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1287
1288
1289.. method:: time.strftime(format)
1290
1291 Return a string representing the time, controlled by an explicit format string.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001292 See section :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001293
1294
1295.. method:: time.utcoffset()
1296
1297 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1298 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1299 return ``None`` or a :class:`timedelta` object representing a whole number of
1300 minutes with magnitude less than one day.
1301
1302
1303.. method:: time.dst()
1304
1305 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1306 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1307 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1308 with magnitude less than one day.
1309
1310
1311.. method:: time.tzname()
1312
1313 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1314 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1315 return ``None`` or a string object.
1316
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001317
Christian Heimesfe337bf2008-03-23 21:54:12 +00001318Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001319
Christian Heimes895627f2007-12-08 17:28:33 +00001320 >>> from datetime import time, tzinfo
1321 >>> class GMT1(tzinfo):
1322 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001323 ... return timedelta(hours=1)
1324 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001325 ... return timedelta(0)
1326 ... def tzname(self,dt):
1327 ... return "Europe/Prague"
1328 ...
1329 >>> t = time(12, 10, 30, tzinfo=GMT1())
1330 >>> t # doctest: +ELLIPSIS
1331 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1332 >>> gmt = GMT1()
1333 >>> t.isoformat()
1334 '12:10:30+01:00'
1335 >>> t.dst()
1336 datetime.timedelta(0)
1337 >>> t.tzname()
1338 'Europe/Prague'
1339 >>> t.strftime("%H:%M:%S %Z")
1340 '12:10:30 Europe/Prague'
1341
Georg Brandl116aa622007-08-15 14:28:22 +00001342
1343.. _datetime-tzinfo:
1344
1345:class:`tzinfo` Objects
1346-----------------------
1347
Brett Cannone1327f72009-01-29 04:10:21 +00001348:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001349instantiated directly. You need to derive a concrete subclass, and (at least)
1350supply implementations of the standard :class:`tzinfo` methods needed by the
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001351:class:`datetime` methods you use. The :mod:`datetime` module supplies
1352a simple concrete subclass of :class:`tzinfo` :class:`timezone` which can reprsent
1353timezones with fixed offset from UTC such as UTC itself or North American EST and
1354EDT.
Georg Brandl116aa622007-08-15 14:28:22 +00001355
1356An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1357constructors for :class:`datetime` and :class:`time` objects. The latter objects
1358view their members as being in local time, and the :class:`tzinfo` object
1359supports methods revealing offset of local time from UTC, the name of the time
1360zone, and DST offset, all relative to a date or time object passed to them.
1361
1362Special requirement for pickling: A :class:`tzinfo` subclass must have an
1363:meth:`__init__` method that can be called with no arguments, else it can be
1364pickled but possibly not unpickled again. This is a technical requirement that
1365may be relaxed in the future.
1366
1367A concrete subclass of :class:`tzinfo` may need to implement the following
1368methods. Exactly which methods are needed depends on the uses made of aware
1369:mod:`datetime` objects. If in doubt, simply implement all of them.
1370
1371
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001372.. method:: tzinfo.utcoffset(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001373
1374 Return offset of local time from UTC, in minutes east of UTC. If local time is
1375 west of UTC, this should be negative. Note that this is intended to be the
1376 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1377 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1378 the UTC offset isn't known, return ``None``. Else the value returned must be a
1379 :class:`timedelta` object specifying a whole number of minutes in the range
1380 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1381 than one day). Most implementations of :meth:`utcoffset` will probably look
1382 like one of these two::
1383
1384 return CONSTANT # fixed-offset class
1385 return CONSTANT + self.dst(dt) # daylight-aware class
1386
1387 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1388 ``None`` either.
1389
1390 The default implementation of :meth:`utcoffset` raises
1391 :exc:`NotImplementedError`.
1392
1393
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001394.. method:: tzinfo.dst(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001395
1396 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1397 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1398 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1399 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1400 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1401 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1402 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
1403 member's :meth:`dst` method to determine how the :attr:`tm_isdst` flag should be
1404 set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for DST changes
1405 when crossing time zones.
1406
1407 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1408 daylight times must be consistent in this sense:
1409
1410 ``tz.utcoffset(dt) - tz.dst(dt)``
1411
1412 must return the same result for every :class:`datetime` *dt* with ``dt.tzinfo ==
1413 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1414 zone's "standard offset", which should not depend on the date or the time, but
1415 only on geographic location. The implementation of :meth:`datetime.astimezone`
1416 relies on this, but cannot detect violations; it's the programmer's
1417 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1418 this, it may be able to override the default implementation of
1419 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1420
1421 Most implementations of :meth:`dst` will probably look like one of these two::
1422
1423 def dst(self):
1424 # a fixed-offset class: doesn't account for DST
1425 return timedelta(0)
1426
1427 or ::
1428
1429 def dst(self):
1430 # Code to set dston and dstoff to the time zone's DST
1431 # transition times based on the input dt.year, and expressed
1432 # in standard local time. Then
1433
1434 if dston <= dt.replace(tzinfo=None) < dstoff:
1435 return timedelta(hours=1)
1436 else:
1437 return timedelta(0)
1438
1439 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1440
1441
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001442.. method:: tzinfo.tzname(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001443
1444 Return the time zone name corresponding to the :class:`datetime` object *dt*, as
1445 a string. Nothing about string names is defined by the :mod:`datetime` module,
1446 and there's no requirement that it mean anything in particular. For example,
1447 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1448 valid replies. Return ``None`` if a string name isn't known. Note that this is
1449 a method rather than a fixed string primarily because some :class:`tzinfo`
1450 subclasses will wish to return different names depending on the specific value
1451 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1452 daylight time.
1453
1454 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1455
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001456
Georg Brandl116aa622007-08-15 14:28:22 +00001457These methods are called by a :class:`datetime` or :class:`time` object, in
1458response to their methods of the same names. A :class:`datetime` object passes
1459itself as the argument, and a :class:`time` object passes ``None`` as the
1460argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
1461accept a *dt* argument of ``None``, or of class :class:`datetime`.
1462
1463When ``None`` is passed, it's up to the class designer to decide the best
1464response. For example, returning ``None`` is appropriate if the class wishes to
1465say that time objects don't participate in the :class:`tzinfo` protocols. It
1466may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1467there is no other convention for discovering the standard offset.
1468
1469When a :class:`datetime` object is passed in response to a :class:`datetime`
1470method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1471rely on this, unless user code calls :class:`tzinfo` methods directly. The
1472intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1473time, and not need worry about objects in other timezones.
1474
1475There is one more :class:`tzinfo` method that a subclass may wish to override:
1476
1477
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001478.. method:: tzinfo.fromutc(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001479
1480 This is called from the default :class:`datetime.astimezone()` implementation.
1481 When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members
1482 are to be viewed as expressing a UTC time. The purpose of :meth:`fromutc` is to
1483 adjust the date and time members, returning an equivalent datetime in *self*'s
1484 local time.
1485
1486 Most :class:`tzinfo` subclasses should be able to inherit the default
1487 :meth:`fromutc` implementation without problems. It's strong enough to handle
1488 fixed-offset time zones, and time zones accounting for both standard and
1489 daylight time, and the latter even if the DST transition times differ in
1490 different years. An example of a time zone the default :meth:`fromutc`
1491 implementation may not handle correctly in all cases is one where the standard
1492 offset (from UTC) depends on the specific date and time passed, which can happen
1493 for political reasons. The default implementations of :meth:`astimezone` and
1494 :meth:`fromutc` may not produce the result you want if the result is one of the
1495 hours straddling the moment the standard offset changes.
1496
1497 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1498 like::
1499
1500 def fromutc(self, dt):
1501 # raise ValueError error if dt.tzinfo is not self
1502 dtoff = dt.utcoffset()
1503 dtdst = dt.dst()
1504 # raise ValueError if dtoff is None or dtdst is None
1505 delta = dtoff - dtdst # this is self's standard offset
1506 if delta:
1507 dt += delta # convert to standard local time
1508 dtdst = dt.dst()
1509 # raise ValueError if dtdst is None
1510 if dtdst:
1511 return dt + dtdst
1512 else:
1513 return dt
1514
1515Example :class:`tzinfo` classes:
1516
1517.. literalinclude:: ../includes/tzinfo-examples.py
1518
1519
1520Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1521subclass accounting for both standard and daylight time, at the DST transition
1522points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00001523minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
15241:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001525
1526 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1527 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1528 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1529
1530 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1531
1532 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1533
1534When DST starts (the "start" line), the local wall clock leaps from 1:59 to
15353:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1536``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1537begins. In order for :meth:`astimezone` to make this guarantee, the
1538:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1539Eastern) to be in daylight time.
1540
1541When DST ends (the "end" line), there's a potentially worse problem: there's an
1542hour that can't be spelled unambiguously in local wall time: the last hour of
1543daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1544daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1545to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1546:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1547hours into the same local hour then. In the Eastern example, UTC times of the
1548form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1549:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1550consider times in the "repeated hour" to be in standard time. This is easily
1551arranged, as in the example, by expressing DST switch times in the time zone's
1552standard local time.
1553
1554Applications that can't bear such ambiguities should avoid using hybrid
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001555:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`,
1556or any other fixed-offset :class:`tzinfo` subclass (such as a class representing
1557only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
1558
1559
1560.. _datetime-timezone:
1561
1562:class:`timezone` Objects
1563--------------------------
1564
1565A :class:`timezone` object represents a timezone that is defined by a
1566fixed offset from UTC. Note that objects of this class cannot be used
1567to represent timezone information in the locations where different
1568offsets are used in different days of the year or where historical
1569changes have been made to civil time.
1570
1571
1572.. class:: timezone(offset[, name])
1573
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001574 The *offset* argument must be specified as a :class:`timedelta`
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001575 object representing the difference between the local time and UTC. It must
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001576 be strictly between ``-timedelta(hours=24)`` and
1577 ``timedelta(hours=24)`` and represent a whole number of minutes,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001578 otherwise :exc:`ValueError` is raised.
1579
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001580 The *name* argument is optional. If specified it must be a string that
1581 is used as the value returned by the ``tzname(dt)`` method. Otherwise,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001582 ``tzname(dt)`` returns a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001583 *offset*, HH and MM are two digits of ``offset.hours`` and
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001584 ``offset.minutes`` respectively.
1585
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001586.. method:: timezone.utcoffset(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001587
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001588 Return the fixed value specified when the :class:`timezone` instance is
1589 constructed. The *dt* argument is ignored. The return value is a
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001590 :class:`timedelta` instance equal to the difference between the
1591 local time and UTC.
1592
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001593.. method:: timezone.tzname(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001594
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001595 Return the fixed value specified when the :class:`timezone` instance is
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001596 constructed or a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001597 *offset*, HH and MM are two digits of ``offset.hours`` and
1598 ``offset.minutes`` respectively.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001599
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001600.. method:: timezone.dst(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001601
1602 Always returns ``None``.
1603
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001604.. method:: timezone.fromutc(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001605
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001606 Return ``dt + offset``. The *dt* argument must be an aware
1607 :class:`datetime` instance, with ``tzinfo`` set to ``self``.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001608
1609Class attributes:
1610
1611.. attribute:: timezone.utc
1612
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001613 The UTC timezone, ``timezone(timedelta(0))``.
Georg Brandl48310cd2009-01-03 21:18:54 +00001614
Georg Brandl116aa622007-08-15 14:28:22 +00001615
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001616.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00001617
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001618:meth:`strftime` and :meth:`strptime` Behavior
1619----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001620
1621:class:`date`, :class:`datetime`, and :class:`time` objects all support a
1622``strftime(format)`` method, to create a string representing the time under the
1623control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1624acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1625although not all objects support a :meth:`timetuple` method.
1626
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001627Conversely, the :meth:`datetime.strptime` class method creates a
1628:class:`datetime` object from a string representing a date and time and a
1629corresponding format string. ``datetime.strptime(date_string, format)`` is
1630equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1631
Georg Brandl116aa622007-08-15 14:28:22 +00001632For :class:`time` objects, the format codes for year, month, and day should not
1633be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001634is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00001635
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001636For :class:`date` objects, the format codes for hours, minutes, seconds, and
1637microseconds should not be used, as :class:`date` objects have no such
1638values. If they're used anyway, ``0`` is substituted for them.
1639
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001640For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1641strings.
1642
1643For an aware object:
1644
1645``%z``
1646 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1647 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1648 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1649 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1650 replaced with the string ``'-0330'``.
1651
1652``%Z``
1653 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1654 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl116aa622007-08-15 14:28:22 +00001655
Georg Brandl116aa622007-08-15 14:28:22 +00001656The full set of format codes supported varies across platforms, because Python
1657calls the platform C library's :func:`strftime` function, and platform
Georg Brandl48310cd2009-01-03 21:18:54 +00001658variations are common.
Christian Heimes895627f2007-12-08 17:28:33 +00001659
1660The following is a list of all the format codes that the C standard (1989
1661version) requires, and these work on all platforms with a standard C
1662implementation. Note that the 1999 version of the C standard added additional
1663format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001664
1665The exact range of years for which :meth:`strftime` works also varies across
1666platforms. Regardless of platform, years before 1900 cannot be used.
1667
Christian Heimes895627f2007-12-08 17:28:33 +00001668+-----------+--------------------------------+-------+
1669| Directive | Meaning | Notes |
1670+===========+================================+=======+
1671| ``%a`` | Locale's abbreviated weekday | |
1672| | name. | |
1673+-----------+--------------------------------+-------+
1674| ``%A`` | Locale's full weekday name. | |
1675+-----------+--------------------------------+-------+
1676| ``%b`` | Locale's abbreviated month | |
1677| | name. | |
1678+-----------+--------------------------------+-------+
1679| ``%B`` | Locale's full month name. | |
1680+-----------+--------------------------------+-------+
1681| ``%c`` | Locale's appropriate date and | |
1682| | time representation. | |
1683+-----------+--------------------------------+-------+
1684| ``%d`` | Day of the month as a decimal | |
1685| | number [01,31]. | |
1686+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001687| ``%f`` | Microsecond as a decimal | \(1) |
1688| | number [0,999999], zero-padded | |
1689| | on the left | |
1690+-----------+--------------------------------+-------+
Christian Heimes895627f2007-12-08 17:28:33 +00001691| ``%H`` | Hour (24-hour clock) as a | |
1692| | decimal number [00,23]. | |
1693+-----------+--------------------------------+-------+
1694| ``%I`` | Hour (12-hour clock) as a | |
1695| | decimal number [01,12]. | |
1696+-----------+--------------------------------+-------+
1697| ``%j`` | Day of the year as a decimal | |
1698| | number [001,366]. | |
1699+-----------+--------------------------------+-------+
1700| ``%m`` | Month as a decimal number | |
1701| | [01,12]. | |
1702+-----------+--------------------------------+-------+
1703| ``%M`` | Minute as a decimal number | |
1704| | [00,59]. | |
1705+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001706| ``%p`` | Locale's equivalent of either | \(2) |
Christian Heimes895627f2007-12-08 17:28:33 +00001707| | AM or PM. | |
1708+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001709| ``%S`` | Second as a decimal number | \(3) |
Christian Heimes895627f2007-12-08 17:28:33 +00001710| | [00,61]. | |
1711+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001712| ``%U`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001713| | (Sunday as the first day of | |
1714| | the week) as a decimal number | |
1715| | [00,53]. All days in a new | |
1716| | year preceding the first | |
1717| | Sunday are considered to be in | |
1718| | week 0. | |
1719+-----------+--------------------------------+-------+
1720| ``%w`` | Weekday as a decimal number | |
1721| | [0(Sunday),6]. | |
1722+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001723| ``%W`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001724| | (Monday as the first day of | |
1725| | the week) as a decimal number | |
1726| | [00,53]. All days in a new | |
1727| | year preceding the first | |
1728| | Monday are considered to be in | |
1729| | week 0. | |
1730+-----------+--------------------------------+-------+
1731| ``%x`` | Locale's appropriate date | |
1732| | representation. | |
1733+-----------+--------------------------------+-------+
1734| ``%X`` | Locale's appropriate time | |
1735| | representation. | |
1736+-----------+--------------------------------+-------+
1737| ``%y`` | Year without century as a | |
1738| | decimal number [00,99]. | |
1739+-----------+--------------------------------+-------+
1740| ``%Y`` | Year with century as a decimal | |
1741| | number. | |
1742+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001743| ``%z`` | UTC offset in the form +HHMM | \(5) |
Christian Heimes895627f2007-12-08 17:28:33 +00001744| | or -HHMM (empty string if the | |
1745| | the object is naive). | |
1746+-----------+--------------------------------+-------+
1747| ``%Z`` | Time zone name (empty string | |
1748| | if the object is naive). | |
1749+-----------+--------------------------------+-------+
1750| ``%%`` | A literal ``'%'`` character. | |
1751+-----------+--------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001752
Christian Heimes895627f2007-12-08 17:28:33 +00001753Notes:
1754
1755(1)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001756 When used with the :meth:`strptime` method, the ``%f`` directive
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001757 accepts from one to six digits and zero pads on the right. ``%f`` is
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001758 an extension to the set of format characters in the C standard (but
1759 implemented separately in datetime objects, and therefore always
1760 available).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001761
1762(2)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001763 When used with the :meth:`strptime` method, the ``%p`` directive only affects
Christian Heimes895627f2007-12-08 17:28:33 +00001764 the output hour field if the ``%I`` directive is used to parse the hour.
1765
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001766(3)
R. David Murraybd25d332009-04-02 04:50:03 +00001767 The range really is ``0`` to ``61``; according to the Posix standard this
1768 accounts for leap seconds and the (very rare) double leap seconds.
1769 The :mod:`time` module may produce and does accept leap seconds since
1770 it is based on the Posix standard, but the :mod:`datetime` module
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001771 does not accept leap seconds in :meth:`strptime` input nor will it
R. David Murraybd25d332009-04-02 04:50:03 +00001772 produce them in :func:`strftime` output.
Christian Heimes895627f2007-12-08 17:28:33 +00001773
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001774(4)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001775 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in
Christian Heimes895627f2007-12-08 17:28:33 +00001776 calculations when the day of the week and the year are specified.
1777
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001778(5)
Christian Heimes895627f2007-12-08 17:28:33 +00001779 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1780 ``%z`` is replaced with the string ``'-0330'``.
Alexander Belopolskyca94f552010-06-17 18:30:34 +00001781
1782.. versionadded:: 3.2
1783
1784 When the ``%z`` directive is provided to the :meth:`strptime`
1785 method, an aware :class:`datetime` object will be produced. The
1786 ``tzinfo`` of the result will be set to a :class:`timezone`
Alexander Belopolsky49d7a572010-06-18 16:57:49 +00001787 instance.