blob: ae73e162ec2f0c05b659484a9df829628c6df78d [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+--------------------------------+-----------------------------------------------+
268
269Notes:
270
271(1)
272 This is exact, but may overflow.
273
274(2)
275 This is exact, and cannot overflow.
276
277(3)
278 Division by 0 raises :exc:`ZeroDivisionError`.
279
280(4)
281 -*timedelta.max* is not representable as a :class:`timedelta` object.
282
283In addition to the operations listed above :class:`timedelta` objects support
284certain additions and subtractions with :class:`date` and :class:`datetime`
285objects (see below).
286
Mark Dickinson7c186e22010-04-20 22:32:49 +0000287.. versionadded:: 3.2
288 Floor division and true division of a :class:`timedelta` object by
289 another :class:`timedelta` object are now supported, as are
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000290 remainder operations and the :func:`divmod` function. True
291 division and multiplication of a :class:`timedelta` object by
292 a :class:`float` object are now supported.
Mark Dickinson7c186e22010-04-20 22:32:49 +0000293
294
Georg Brandl116aa622007-08-15 14:28:22 +0000295Comparisons of :class:`timedelta` objects are supported with the
296:class:`timedelta` object representing the smaller duration considered to be the
297smaller timedelta. In order to stop mixed-type comparisons from falling back to
298the default comparison by object address, when a :class:`timedelta` object is
299compared to an object of a different type, :exc:`TypeError` is raised unless the
300comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
301:const:`True`, respectively.
302
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000303:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl116aa622007-08-15 14:28:22 +0000304efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
305considered to be true if and only if it isn't equal to ``timedelta(0)``.
306
Antoine Pitroube6859d2009-11-25 23:02:32 +0000307Instance methods:
308
309.. method:: timedelta.total_seconds()
310
311 Return the total number of seconds contained in the duration. Equivalent to
Mark Dickinson0381e3f2010-05-08 14:35:02 +0000312 ``td / timedelta(seconds=1)``.
313
314 Note that for very large time intervals (greater than 270 years on
315 most platforms) this method will lose microsecond accuracy.
Antoine Pitroube6859d2009-11-25 23:02:32 +0000316
317 .. versionadded:: 3.2
318
319
Christian Heimesfe337bf2008-03-23 21:54:12 +0000320Example usage:
Georg Brandl48310cd2009-01-03 21:18:54 +0000321
Christian Heimes895627f2007-12-08 17:28:33 +0000322 >>> from datetime import timedelta
323 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000324 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Christian Heimes895627f2007-12-08 17:28:33 +0000325 ... minutes=50, seconds=600) # adds up to 365 days
Antoine Pitroube6859d2009-11-25 23:02:32 +0000326 >>> year.total_seconds()
327 31536000.0
Christian Heimes895627f2007-12-08 17:28:33 +0000328 >>> year == another_year
329 True
330 >>> ten_years = 10 * year
331 >>> ten_years, ten_years.days // 365
332 (datetime.timedelta(3650), 10)
333 >>> nine_years = ten_years - year
334 >>> nine_years, nine_years.days // 365
335 (datetime.timedelta(3285), 9)
336 >>> three_years = nine_years // 3;
337 >>> three_years, three_years.days // 365
338 (datetime.timedelta(1095), 3)
339 >>> abs(three_years - ten_years) == 2 * three_years + year
340 True
341
Georg Brandl116aa622007-08-15 14:28:22 +0000342
343.. _datetime-date:
344
345:class:`date` Objects
346---------------------
347
348A :class:`date` object represents a date (year, month and day) in an idealized
349calendar, the current Gregorian calendar indefinitely extended in both
350directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
351called day number 2, and so on. This matches the definition of the "proleptic
352Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
353where it's the base calendar for all computations. See the book for algorithms
354for converting between proleptic Gregorian ordinals and many other calendar
355systems.
356
357
358.. class:: date(year, month, day)
359
Georg Brandl5c106642007-11-29 17:41:05 +0000360 All arguments are required. Arguments may be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000361 ranges:
362
363 * ``MINYEAR <= year <= MAXYEAR``
364 * ``1 <= month <= 12``
365 * ``1 <= day <= number of days in the given month and year``
366
367 If an argument outside those ranges is given, :exc:`ValueError` is raised.
368
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000369
Georg Brandl116aa622007-08-15 14:28:22 +0000370Other constructors, all class methods:
371
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000372.. classmethod:: date.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000373
374 Return the current local date. This is equivalent to
375 ``date.fromtimestamp(time.time())``.
376
377
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000378.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000379
380 Return the local date corresponding to the POSIX timestamp, such as is returned
381 by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out
382 of the range of values supported by the platform C :cfunc:`localtime` function.
383 It's common for this to be restricted to years from 1970 through 2038. Note
384 that on non-POSIX systems that include leap seconds in their notion of a
385 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
386
387
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000388.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000389
390 Return the date corresponding to the proleptic Gregorian ordinal, where January
391 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
392 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
393 d``.
394
Georg Brandl116aa622007-08-15 14:28:22 +0000395
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000396Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000397
398.. attribute:: date.min
399
400 The earliest representable date, ``date(MINYEAR, 1, 1)``.
401
402
403.. attribute:: date.max
404
405 The latest representable date, ``date(MAXYEAR, 12, 31)``.
406
407
408.. attribute:: date.resolution
409
410 The smallest possible difference between non-equal date objects,
411 ``timedelta(days=1)``.
412
Georg Brandl116aa622007-08-15 14:28:22 +0000413
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000414Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000415
416.. attribute:: date.year
417
418 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
419
420
421.. attribute:: date.month
422
423 Between 1 and 12 inclusive.
424
425
426.. attribute:: date.day
427
428 Between 1 and the number of days in the given month of the given year.
429
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000430
Georg Brandl116aa622007-08-15 14:28:22 +0000431Supported operations:
432
433+-------------------------------+----------------------------------------------+
434| Operation | Result |
435+===============================+==============================================+
436| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
437| | from *date1*. (1) |
438+-------------------------------+----------------------------------------------+
439| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
440| | timedelta == date1``. (2) |
441+-------------------------------+----------------------------------------------+
442| ``timedelta = date1 - date2`` | \(3) |
443+-------------------------------+----------------------------------------------+
444| ``date1 < date2`` | *date1* is considered less than *date2* when |
445| | *date1* precedes *date2* in time. (4) |
446+-------------------------------+----------------------------------------------+
447
448Notes:
449
450(1)
451 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
452 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
453 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
454 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
455 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
456
457(2)
458 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
459 isolation can overflow in cases where date1 - timedelta does not.
460 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
461
462(3)
463 This is exact, and cannot overflow. timedelta.seconds and
464 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
465
466(4)
467 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
468 date2.toordinal()``. In order to stop comparison from falling back to the
469 default scheme of comparing object addresses, date comparison normally raises
470 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
471 However, ``NotImplemented`` is returned instead if the other comparand has a
472 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
473 chance at implementing mixed-type comparison. If not, when a :class:`date`
474 object is compared to an object of a different type, :exc:`TypeError` is raised
475 unless the comparison is ``==`` or ``!=``. The latter cases return
476 :const:`False` or :const:`True`, respectively.
477
478Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
479objects are considered to be true.
480
481Instance methods:
482
Georg Brandl116aa622007-08-15 14:28:22 +0000483.. method:: date.replace(year, month, day)
484
485 Return a date with the same value, except for those members given new values by
486 whichever keyword arguments are specified. For example, if ``d == date(2002,
487 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
488
489
490.. method:: date.timetuple()
491
492 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
493 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
494 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000495 d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1,
496 1).toordinal() + 1`` is the day number within the current year starting with
497 ``1`` for January 1st.
Georg Brandl116aa622007-08-15 14:28:22 +0000498
499
500.. method:: date.toordinal()
501
502 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
503 has ordinal 1. For any :class:`date` object *d*,
504 ``date.fromordinal(d.toordinal()) == d``.
505
506
507.. method:: date.weekday()
508
509 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
510 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
511 :meth:`isoweekday`.
512
513
514.. method:: date.isoweekday()
515
516 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
517 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
518 :meth:`weekday`, :meth:`isocalendar`.
519
520
521.. method:: date.isocalendar()
522
523 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
524
525 The ISO calendar is a widely used variant of the Gregorian calendar. See
Mark Dickinsonf964ac22009-11-03 16:29:10 +0000526 http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
527 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000528
529 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
530 Monday and ends on a Sunday. The first week of an ISO year is the first
531 (Gregorian) calendar week of a year containing a Thursday. This is called week
532 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
533
534 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
535 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
536 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
537 4).isocalendar() == (2004, 1, 7)``.
538
539
540.. method:: date.isoformat()
541
542 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
543 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
544
545
546.. method:: date.__str__()
547
548 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
549
550
551.. method:: date.ctime()
552
553 Return a string representing the date, for example ``date(2002, 12,
554 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
555 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
556 :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
557 :meth:`date.ctime` does not invoke) conforms to the C standard.
558
559
560.. method:: date.strftime(format)
561
562 Return a string representing the date, controlled by an explicit format string.
563 Format codes referring to hours, minutes or seconds will see 0 values. See
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000564 section :ref:`strftime-strptime-behavior`.
565
Georg Brandl116aa622007-08-15 14:28:22 +0000566
Christian Heimes895627f2007-12-08 17:28:33 +0000567Example of counting days to an event::
568
569 >>> import time
570 >>> from datetime import date
571 >>> today = date.today()
572 >>> today
573 datetime.date(2007, 12, 5)
574 >>> today == date.fromtimestamp(time.time())
575 True
576 >>> my_birthday = date(today.year, 6, 24)
577 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000578 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000579 >>> my_birthday
580 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000581 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000582 >>> time_to_birthday.days
583 202
584
Christian Heimesfe337bf2008-03-23 21:54:12 +0000585Example of working with :class:`date`:
586
587.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000588
589 >>> from datetime import date
590 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
591 >>> d
592 datetime.date(2002, 3, 11)
593 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000594 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000595 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000596 2002 # year
597 3 # month
598 11 # day
599 0
600 0
601 0
602 0 # weekday (0 = Monday)
603 70 # 70th day in the year
604 -1
605 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000606 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000607 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000608 2002 # ISO year
609 11 # ISO week number
610 1 # ISO day number ( 1 = Monday )
611 >>> d.isoformat()
612 '2002-03-11'
613 >>> d.strftime("%d/%m/%y")
614 '11/03/02'
615 >>> d.strftime("%A %d. %B %Y")
616 'Monday 11. March 2002'
617
Georg Brandl116aa622007-08-15 14:28:22 +0000618
619.. _datetime-datetime:
620
621:class:`datetime` Objects
622-------------------------
623
624A :class:`datetime` object is a single object containing all the information
625from a :class:`date` object and a :class:`time` object. Like a :class:`date`
626object, :class:`datetime` assumes the current Gregorian calendar extended in
627both directions; like a time object, :class:`datetime` assumes there are exactly
6283600\*24 seconds in every day.
629
630Constructor:
631
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000632.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000633
634 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000635 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
636 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000637
638 * ``MINYEAR <= year <= MAXYEAR``
639 * ``1 <= month <= 12``
640 * ``1 <= day <= number of days in the given month and year``
641 * ``0 <= hour < 24``
642 * ``0 <= minute < 60``
643 * ``0 <= second < 60``
644 * ``0 <= microsecond < 1000000``
645
646 If an argument outside those ranges is given, :exc:`ValueError` is raised.
647
648Other constructors, all class methods:
649
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000650.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000651
652 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
653 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
654 :meth:`fromtimestamp`.
655
656
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000657.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000658
659 Return the current local date and time. If optional argument *tz* is ``None``
660 or not specified, this is like :meth:`today`, but, if possible, supplies more
661 precision than can be gotten from going through a :func:`time.time` timestamp
662 (for example, this may be possible on platforms supplying the C
663 :cfunc:`gettimeofday` function).
664
665 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
666 current date and time are converted to *tz*'s time zone. In this case the
667 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
668 See also :meth:`today`, :meth:`utcnow`.
669
670
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000671.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000672
673 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
674 :meth:`now`, but returns the current UTC date and time, as a naive
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000675 :class:`datetime` object. An aware current UTC datetime can be obtained by
676 calling ``datetime.now(timezone.utc)``. See also :meth:`now`.
Georg Brandl116aa622007-08-15 14:28:22 +0000677
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000678.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000679
680 Return the local date and time corresponding to the POSIX timestamp, such as is
681 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
682 specified, the timestamp is converted to the platform's local date and time, and
683 the returned :class:`datetime` object is naive.
684
685 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
686 timestamp is converted to *tz*'s time zone. In this case the result is
687 equivalent to
688 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
689
690 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
691 the range of values supported by the platform C :cfunc:`localtime` or
692 :cfunc:`gmtime` functions. It's common for this to be restricted to years in
693 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
694 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
695 and then it's possible to have two timestamps differing by a second that yield
696 identical :class:`datetime` objects. See also :meth:`utcfromtimestamp`.
697
698
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000699.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000700
701 Return the UTC :class:`datetime` corresponding to the POSIX timestamp, with
702 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
703 out of the range of values supported by the platform C :cfunc:`gmtime` function.
704 It's common for this to be restricted to years in 1970 through 2038. See also
705 :meth:`fromtimestamp`.
706
707
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000708.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000709
710 Return the :class:`datetime` corresponding to the proleptic Gregorian ordinal,
711 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
712 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
713 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
714
715
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000716.. classmethod:: datetime.combine(date, time)
Georg Brandl116aa622007-08-15 14:28:22 +0000717
718 Return a new :class:`datetime` object whose date members are equal to the given
719 :class:`date` object's, and whose time and :attr:`tzinfo` members are equal to
720 the given :class:`time` object's. For any :class:`datetime` object *d*, ``d ==
721 datetime.combine(d.date(), d.timetz())``. If date is a :class:`datetime`
722 object, its time and :attr:`tzinfo` members are ignored.
723
724
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000725.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000726
727 Return a :class:`datetime` corresponding to *date_string*, parsed according to
728 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
729 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
730 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 +0000731 time tuple. See section :ref:`strftime-strptime-behavior`.
732
Georg Brandl116aa622007-08-15 14:28:22 +0000733
Georg Brandl116aa622007-08-15 14:28:22 +0000734
735Class attributes:
736
Georg Brandl116aa622007-08-15 14:28:22 +0000737.. attribute:: datetime.min
738
739 The earliest representable :class:`datetime`, ``datetime(MINYEAR, 1, 1,
740 tzinfo=None)``.
741
742
743.. attribute:: datetime.max
744
745 The latest representable :class:`datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
746 59, 999999, tzinfo=None)``.
747
748
749.. attribute:: datetime.resolution
750
751 The smallest possible difference between non-equal :class:`datetime` objects,
752 ``timedelta(microseconds=1)``.
753
Georg Brandl116aa622007-08-15 14:28:22 +0000754
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000755Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000756
757.. attribute:: datetime.year
758
759 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
760
761
762.. attribute:: datetime.month
763
764 Between 1 and 12 inclusive.
765
766
767.. attribute:: datetime.day
768
769 Between 1 and the number of days in the given month of the given year.
770
771
772.. attribute:: datetime.hour
773
774 In ``range(24)``.
775
776
777.. attribute:: datetime.minute
778
779 In ``range(60)``.
780
781
782.. attribute:: datetime.second
783
784 In ``range(60)``.
785
786
787.. attribute:: datetime.microsecond
788
789 In ``range(1000000)``.
790
791
792.. attribute:: datetime.tzinfo
793
794 The object passed as the *tzinfo* argument to the :class:`datetime` constructor,
795 or ``None`` if none was passed.
796
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000797
Georg Brandl116aa622007-08-15 14:28:22 +0000798Supported operations:
799
800+---------------------------------------+-------------------------------+
801| Operation | Result |
802+=======================================+===============================+
803| ``datetime2 = datetime1 + timedelta`` | \(1) |
804+---------------------------------------+-------------------------------+
805| ``datetime2 = datetime1 - timedelta`` | \(2) |
806+---------------------------------------+-------------------------------+
807| ``timedelta = datetime1 - datetime2`` | \(3) |
808+---------------------------------------+-------------------------------+
809| ``datetime1 < datetime2`` | Compares :class:`datetime` to |
810| | :class:`datetime`. (4) |
811+---------------------------------------+-------------------------------+
812
813(1)
814 datetime2 is a duration of timedelta removed from datetime1, moving forward in
815 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
816 result has the same :attr:`tzinfo` member as the input datetime, and datetime2 -
817 datetime1 == timedelta after. :exc:`OverflowError` is raised if datetime2.year
818 would be smaller than :const:`MINYEAR` or larger than :const:`MAXYEAR`. Note
819 that no time zone adjustments are done even if the input is an aware object.
820
821(2)
822 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
823 addition, the result has the same :attr:`tzinfo` member as the input datetime,
824 and no time zone adjustments are done even if the input is aware. This isn't
825 quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation
826 can overflow in cases where datetime1 - timedelta does not.
827
828(3)
829 Subtraction of a :class:`datetime` from a :class:`datetime` is defined only if
830 both operands are naive, or if both are aware. If one is aware and the other is
831 naive, :exc:`TypeError` is raised.
832
833 If both are naive, or both are aware and have the same :attr:`tzinfo` member,
834 the :attr:`tzinfo` members are ignored, and the result is a :class:`timedelta`
835 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
836 are done in this case.
837
838 If both are aware and have different :attr:`tzinfo` members, ``a-b`` acts as if
839 *a* and *b* were first converted to naive UTC datetimes first. The result is
840 ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) -
841 b.utcoffset())`` except that the implementation never overflows.
842
843(4)
844 *datetime1* is considered less than *datetime2* when *datetime1* precedes
845 *datetime2* in time.
846
847 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
848 If both comparands are aware, and have the same :attr:`tzinfo` member, the
849 common :attr:`tzinfo` member is ignored and the base datetimes are compared. If
850 both comparands are aware and have different :attr:`tzinfo` members, the
851 comparands are first adjusted by subtracting their UTC offsets (obtained from
852 ``self.utcoffset()``).
853
854 .. note::
855
856 In order to stop comparison from falling back to the default scheme of comparing
857 object addresses, datetime comparison normally raises :exc:`TypeError` if the
858 other comparand isn't also a :class:`datetime` object. However,
859 ``NotImplemented`` is returned instead if the other comparand has a
860 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
861 chance at implementing mixed-type comparison. If not, when a :class:`datetime`
862 object is compared to an object of a different type, :exc:`TypeError` is raised
863 unless the comparison is ``==`` or ``!=``. The latter cases return
864 :const:`False` or :const:`True`, respectively.
865
866:class:`datetime` objects can be used as dictionary keys. In Boolean contexts,
867all :class:`datetime` objects are considered to be true.
868
869Instance methods:
870
Georg Brandl116aa622007-08-15 14:28:22 +0000871.. method:: datetime.date()
872
873 Return :class:`date` object with same year, month and day.
874
875
876.. method:: datetime.time()
877
878 Return :class:`time` object with same hour, minute, second and microsecond.
879 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
880
881
882.. method:: datetime.timetz()
883
884 Return :class:`time` object with same hour, minute, second, microsecond, and
885 tzinfo members. See also method :meth:`time`.
886
887
888.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
889
890 Return a datetime with the same members, except for those members given new
891 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
892 can be specified to create a naive datetime from an aware datetime with no
893 conversion of date and time members.
894
895
896.. method:: datetime.astimezone(tz)
897
898 Return a :class:`datetime` object with new :attr:`tzinfo` member *tz*, adjusting
899 the date and time members so the result is the same UTC time as *self*, but in
900 *tz*'s local time.
901
902 *tz* must be an instance of a :class:`tzinfo` subclass, and its
903 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
904 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
905 not return ``None``).
906
907 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
908 adjustment of date or time members is performed. Else the result is local time
909 in time zone *tz*, representing the same UTC time as *self*: after ``astz =
910 dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have the same date
911 and time members as ``dt - dt.utcoffset()``. The discussion of class
912 :class:`tzinfo` explains the cases at Daylight Saving Time transition boundaries
913 where this cannot be achieved (an issue only if *tz* models both standard and
914 daylight time).
915
916 If you merely want to attach a time zone object *tz* to a datetime *dt* without
917 adjustment of date and time members, use ``dt.replace(tzinfo=tz)``. If you
918 merely want to remove the time zone object from an aware datetime *dt* without
919 conversion of date and time members, use ``dt.replace(tzinfo=None)``.
920
921 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
922 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
923 Ignoring error cases, :meth:`astimezone` acts like::
924
925 def astimezone(self, tz):
926 if self.tzinfo is tz:
927 return self
928 # Convert self to UTC, and attach the new time zone object.
929 utc = (self - self.utcoffset()).replace(tzinfo=tz)
930 # Convert from UTC to tz's local time.
931 return tz.fromutc(utc)
932
933
934.. method:: datetime.utcoffset()
935
936 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
937 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
938 return ``None``, or a :class:`timedelta` object representing a whole number of
939 minutes with magnitude less than one day.
940
941
942.. method:: datetime.dst()
943
944 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
945 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
946 ``None``, or a :class:`timedelta` object representing a whole number of minutes
947 with magnitude less than one day.
948
949
950.. method:: datetime.tzname()
951
952 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
953 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
954 ``None`` or a string object,
955
956
957.. method:: datetime.timetuple()
958
959 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
960 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
Alexander Belopolsky64912482010-06-08 18:59:20 +0000961 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
962 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
963 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
964 of the result is set according to the :meth:`dst` method: :attr:`tzinfo` is
965 ``None`` or :meth:`dst`` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
966 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
Alexander Belopolskyda62f2f2010-06-09 17:11:01 +0000967 else :attr:`tm_isdst` is set to ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +0000968
969
970.. method:: datetime.utctimetuple()
971
972 If :class:`datetime` instance *d* is naive, this is the same as
973 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
974 ``d.dst()`` returns. DST is never in effect for a UTC time.
975
976 If *d* is aware, *d* is normalized to UTC time, by subtracting
977 ``d.utcoffset()``, and a :class:`time.struct_time` for the normalized time is
978 returned. :attr:`tm_isdst` is forced to 0. Note that the result's
979 :attr:`tm_year` member may be :const:`MINYEAR`\ -1 or :const:`MAXYEAR`\ +1, if
980 *d*.year was ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
981 boundary.
982
983
984.. method:: datetime.toordinal()
985
986 Return the proleptic Gregorian ordinal of the date. The same as
987 ``self.date().toordinal()``.
988
989
990.. method:: datetime.weekday()
991
992 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
993 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
994
995
996.. method:: datetime.isoweekday()
997
998 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
999 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
1000 :meth:`isocalendar`.
1001
1002
1003.. method:: datetime.isocalendar()
1004
1005 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
1006 ``self.date().isocalendar()``.
1007
1008
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001009.. method:: datetime.isoformat(sep='T')
Georg Brandl116aa622007-08-15 14:28:22 +00001010
1011 Return a string representing the date and time in ISO 8601 format,
1012 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
1013 YYYY-MM-DDTHH:MM:SS
1014
1015 If :meth:`utcoffset` does not return ``None``, a 6-character string is
1016 appended, giving the UTC offset in (signed) hours and minutes:
1017 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
1018 YYYY-MM-DDTHH:MM:SS+HH:MM
1019
1020 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +00001021 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +00001022
1023 >>> from datetime import tzinfo, timedelta, datetime
1024 >>> class TZ(tzinfo):
1025 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1026 ...
1027 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1028 '2002-12-25 00:00:00-06:39'
1029
1030
1031.. method:: datetime.__str__()
1032
1033 For a :class:`datetime` instance *d*, ``str(d)`` is equivalent to
1034 ``d.isoformat(' ')``.
1035
1036
1037.. method:: datetime.ctime()
1038
1039 Return a string representing the date and time, for example ``datetime(2002, 12,
1040 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1041 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
1042 native C :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
1043 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1044
1045
1046.. method:: datetime.strftime(format)
1047
1048 Return a string representing the date and time, controlled by an explicit format
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001049 string. See section :ref:`strftime-strptime-behavior`.
1050
Georg Brandl116aa622007-08-15 14:28:22 +00001051
Christian Heimesfe337bf2008-03-23 21:54:12 +00001052Examples of working with datetime objects:
1053
1054.. doctest::
1055
Christian Heimes895627f2007-12-08 17:28:33 +00001056 >>> from datetime import datetime, date, time
1057 >>> # Using datetime.combine()
1058 >>> d = date(2005, 7, 14)
1059 >>> t = time(12, 30)
1060 >>> datetime.combine(d, t)
1061 datetime.datetime(2005, 7, 14, 12, 30)
1062 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001063 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001064 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001065 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001066 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1067 >>> # Using datetime.strptime()
1068 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1069 >>> dt
1070 datetime.datetime(2006, 11, 21, 16, 30)
1071 >>> # Using datetime.timetuple() to get tuple of all attributes
1072 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001073 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001074 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001075 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001076 2006 # year
1077 11 # month
1078 21 # day
1079 16 # hour
1080 30 # minute
1081 0 # second
1082 1 # weekday (0 = Monday)
1083 325 # number of days since 1st January
1084 -1 # dst - method tzinfo.dst() returned None
1085 >>> # Date in ISO format
1086 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001087 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001088 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001089 ...
1090 2006 # ISO year
1091 47 # ISO week
1092 2 # ISO weekday
1093 >>> # Formatting datetime
1094 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1095 'Tuesday, 21. November 2006 04:30PM'
1096
Christian Heimesfe337bf2008-03-23 21:54:12 +00001097Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001098
1099 >>> from datetime import timedelta, datetime, tzinfo
1100 >>> class GMT1(tzinfo):
1101 ... def __init__(self): # DST starts last Sunday in March
1102 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1103 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001104 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001105 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1106 ... def utcoffset(self, dt):
1107 ... return timedelta(hours=1) + self.dst(dt)
Georg Brandl48310cd2009-01-03 21:18:54 +00001108 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001109 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1110 ... return timedelta(hours=1)
1111 ... else:
1112 ... return timedelta(0)
1113 ... def tzname(self,dt):
1114 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001115 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001116 >>> class GMT2(tzinfo):
1117 ... def __init__(self):
Georg Brandl48310cd2009-01-03 21:18:54 +00001118 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001119 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001120 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001121 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1122 ... def utcoffset(self, dt):
1123 ... return timedelta(hours=1) + self.dst(dt)
1124 ... def dst(self, dt):
1125 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1126 ... return timedelta(hours=2)
1127 ... else:
1128 ... return timedelta(0)
1129 ... def tzname(self,dt):
1130 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001131 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001132 >>> gmt1 = GMT1()
1133 >>> # Daylight Saving Time
1134 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1135 >>> dt1.dst()
1136 datetime.timedelta(0)
1137 >>> dt1.utcoffset()
1138 datetime.timedelta(0, 3600)
1139 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1140 >>> dt2.dst()
1141 datetime.timedelta(0, 3600)
1142 >>> dt2.utcoffset()
1143 datetime.timedelta(0, 7200)
1144 >>> # Convert datetime to another time zone
1145 >>> dt3 = dt2.astimezone(GMT2())
1146 >>> dt3 # doctest: +ELLIPSIS
1147 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1148 >>> dt2 # doctest: +ELLIPSIS
1149 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1150 >>> dt2.utctimetuple() == dt3.utctimetuple()
1151 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001152
Christian Heimes895627f2007-12-08 17:28:33 +00001153
Georg Brandl116aa622007-08-15 14:28:22 +00001154
1155.. _datetime-time:
1156
1157:class:`time` Objects
1158---------------------
1159
1160A time object represents a (local) time of day, independent of any particular
1161day, and subject to adjustment via a :class:`tzinfo` object.
1162
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001163.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001164
1165 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001166 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001167 following ranges:
1168
1169 * ``0 <= hour < 24``
1170 * ``0 <= minute < 60``
1171 * ``0 <= second < 60``
1172 * ``0 <= microsecond < 1000000``.
1173
1174 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1175 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1176
1177Class attributes:
1178
1179
1180.. attribute:: time.min
1181
1182 The earliest representable :class:`time`, ``time(0, 0, 0, 0)``.
1183
1184
1185.. attribute:: time.max
1186
1187 The latest representable :class:`time`, ``time(23, 59, 59, 999999)``.
1188
1189
1190.. attribute:: time.resolution
1191
1192 The smallest possible difference between non-equal :class:`time` objects,
1193 ``timedelta(microseconds=1)``, although note that arithmetic on :class:`time`
1194 objects is not supported.
1195
Georg Brandl116aa622007-08-15 14:28:22 +00001196
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001197Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001198
1199.. attribute:: time.hour
1200
1201 In ``range(24)``.
1202
1203
1204.. attribute:: time.minute
1205
1206 In ``range(60)``.
1207
1208
1209.. attribute:: time.second
1210
1211 In ``range(60)``.
1212
1213
1214.. attribute:: time.microsecond
1215
1216 In ``range(1000000)``.
1217
1218
1219.. attribute:: time.tzinfo
1220
1221 The object passed as the tzinfo argument to the :class:`time` constructor, or
1222 ``None`` if none was passed.
1223
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001224
Georg Brandl116aa622007-08-15 14:28:22 +00001225Supported operations:
1226
1227* comparison of :class:`time` to :class:`time`, where *a* is considered less
1228 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1229 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
1230 the same :attr:`tzinfo` member, the common :attr:`tzinfo` member is ignored and
1231 the base times are compared. If both comparands are aware and have different
1232 :attr:`tzinfo` members, the comparands are first adjusted by subtracting their
1233 UTC offsets (obtained from ``self.utcoffset()``). In order to stop mixed-type
1234 comparisons from falling back to the default comparison by object address, when
1235 a :class:`time` object is compared to an object of a different type,
1236 :exc:`TypeError` is raised unless the comparison is ``==`` or ``!=``. The
1237 latter cases return :const:`False` or :const:`True`, respectively.
1238
1239* hash, use as dict key
1240
1241* efficient pickling
1242
1243* in Boolean contexts, a :class:`time` object is considered to be true if and
1244 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1245 ``0`` if that's ``None``), the result is non-zero.
1246
Georg Brandl116aa622007-08-15 14:28:22 +00001247
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001248Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001249
1250.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1251
1252 Return a :class:`time` with the same value, except for those members given new
1253 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
1254 can be specified to create a naive :class:`time` from an aware :class:`time`,
1255 without conversion of the time members.
1256
1257
1258.. method:: time.isoformat()
1259
1260 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1261 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1262 6-character string is appended, giving the UTC offset in (signed) hours and
1263 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1264
1265
1266.. method:: time.__str__()
1267
1268 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1269
1270
1271.. method:: time.strftime(format)
1272
1273 Return a string representing the time, controlled by an explicit format string.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001274 See section :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001275
1276
1277.. method:: time.utcoffset()
1278
1279 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1280 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1281 return ``None`` or a :class:`timedelta` object representing a whole number of
1282 minutes with magnitude less than one day.
1283
1284
1285.. method:: time.dst()
1286
1287 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1288 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1289 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1290 with magnitude less than one day.
1291
1292
1293.. method:: time.tzname()
1294
1295 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1296 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1297 return ``None`` or a string object.
1298
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001299
Christian Heimesfe337bf2008-03-23 21:54:12 +00001300Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001301
Christian Heimes895627f2007-12-08 17:28:33 +00001302 >>> from datetime import time, tzinfo
1303 >>> class GMT1(tzinfo):
1304 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001305 ... return timedelta(hours=1)
1306 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001307 ... return timedelta(0)
1308 ... def tzname(self,dt):
1309 ... return "Europe/Prague"
1310 ...
1311 >>> t = time(12, 10, 30, tzinfo=GMT1())
1312 >>> t # doctest: +ELLIPSIS
1313 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1314 >>> gmt = GMT1()
1315 >>> t.isoformat()
1316 '12:10:30+01:00'
1317 >>> t.dst()
1318 datetime.timedelta(0)
1319 >>> t.tzname()
1320 'Europe/Prague'
1321 >>> t.strftime("%H:%M:%S %Z")
1322 '12:10:30 Europe/Prague'
1323
Georg Brandl116aa622007-08-15 14:28:22 +00001324
1325.. _datetime-tzinfo:
1326
1327:class:`tzinfo` Objects
1328-----------------------
1329
Brett Cannone1327f72009-01-29 04:10:21 +00001330:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001331instantiated directly. You need to derive a concrete subclass, and (at least)
1332supply implementations of the standard :class:`tzinfo` methods needed by the
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001333:class:`datetime` methods you use. The :mod:`datetime` module supplies
1334a simple concrete subclass of :class:`tzinfo` :class:`timezone` which can reprsent
1335timezones with fixed offset from UTC such as UTC itself or North American EST and
1336EDT.
Georg Brandl116aa622007-08-15 14:28:22 +00001337
1338An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1339constructors for :class:`datetime` and :class:`time` objects. The latter objects
1340view their members as being in local time, and the :class:`tzinfo` object
1341supports methods revealing offset of local time from UTC, the name of the time
1342zone, and DST offset, all relative to a date or time object passed to them.
1343
1344Special requirement for pickling: A :class:`tzinfo` subclass must have an
1345:meth:`__init__` method that can be called with no arguments, else it can be
1346pickled but possibly not unpickled again. This is a technical requirement that
1347may be relaxed in the future.
1348
1349A concrete subclass of :class:`tzinfo` may need to implement the following
1350methods. Exactly which methods are needed depends on the uses made of aware
1351:mod:`datetime` objects. If in doubt, simply implement all of them.
1352
1353
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001354.. method:: tzinfo.utcoffset(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001355
1356 Return offset of local time from UTC, in minutes east of UTC. If local time is
1357 west of UTC, this should be negative. Note that this is intended to be the
1358 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1359 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1360 the UTC offset isn't known, return ``None``. Else the value returned must be a
1361 :class:`timedelta` object specifying a whole number of minutes in the range
1362 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1363 than one day). Most implementations of :meth:`utcoffset` will probably look
1364 like one of these two::
1365
1366 return CONSTANT # fixed-offset class
1367 return CONSTANT + self.dst(dt) # daylight-aware class
1368
1369 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1370 ``None`` either.
1371
1372 The default implementation of :meth:`utcoffset` raises
1373 :exc:`NotImplementedError`.
1374
1375
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001376.. method:: tzinfo.dst(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001377
1378 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1379 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1380 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1381 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1382 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1383 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1384 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
1385 member's :meth:`dst` method to determine how the :attr:`tm_isdst` flag should be
1386 set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for DST changes
1387 when crossing time zones.
1388
1389 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1390 daylight times must be consistent in this sense:
1391
1392 ``tz.utcoffset(dt) - tz.dst(dt)``
1393
1394 must return the same result for every :class:`datetime` *dt* with ``dt.tzinfo ==
1395 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1396 zone's "standard offset", which should not depend on the date or the time, but
1397 only on geographic location. The implementation of :meth:`datetime.astimezone`
1398 relies on this, but cannot detect violations; it's the programmer's
1399 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1400 this, it may be able to override the default implementation of
1401 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1402
1403 Most implementations of :meth:`dst` will probably look like one of these two::
1404
1405 def dst(self):
1406 # a fixed-offset class: doesn't account for DST
1407 return timedelta(0)
1408
1409 or ::
1410
1411 def dst(self):
1412 # Code to set dston and dstoff to the time zone's DST
1413 # transition times based on the input dt.year, and expressed
1414 # in standard local time. Then
1415
1416 if dston <= dt.replace(tzinfo=None) < dstoff:
1417 return timedelta(hours=1)
1418 else:
1419 return timedelta(0)
1420
1421 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1422
1423
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001424.. method:: tzinfo.tzname(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001425
1426 Return the time zone name corresponding to the :class:`datetime` object *dt*, as
1427 a string. Nothing about string names is defined by the :mod:`datetime` module,
1428 and there's no requirement that it mean anything in particular. For example,
1429 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1430 valid replies. Return ``None`` if a string name isn't known. Note that this is
1431 a method rather than a fixed string primarily because some :class:`tzinfo`
1432 subclasses will wish to return different names depending on the specific value
1433 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1434 daylight time.
1435
1436 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1437
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001438
Georg Brandl116aa622007-08-15 14:28:22 +00001439These methods are called by a :class:`datetime` or :class:`time` object, in
1440response to their methods of the same names. A :class:`datetime` object passes
1441itself as the argument, and a :class:`time` object passes ``None`` as the
1442argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
1443accept a *dt* argument of ``None``, or of class :class:`datetime`.
1444
1445When ``None`` is passed, it's up to the class designer to decide the best
1446response. For example, returning ``None`` is appropriate if the class wishes to
1447say that time objects don't participate in the :class:`tzinfo` protocols. It
1448may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1449there is no other convention for discovering the standard offset.
1450
1451When a :class:`datetime` object is passed in response to a :class:`datetime`
1452method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1453rely on this, unless user code calls :class:`tzinfo` methods directly. The
1454intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1455time, and not need worry about objects in other timezones.
1456
1457There is one more :class:`tzinfo` method that a subclass may wish to override:
1458
1459
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001460.. method:: tzinfo.fromutc(dt)
Georg Brandl116aa622007-08-15 14:28:22 +00001461
1462 This is called from the default :class:`datetime.astimezone()` implementation.
1463 When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members
1464 are to be viewed as expressing a UTC time. The purpose of :meth:`fromutc` is to
1465 adjust the date and time members, returning an equivalent datetime in *self*'s
1466 local time.
1467
1468 Most :class:`tzinfo` subclasses should be able to inherit the default
1469 :meth:`fromutc` implementation without problems. It's strong enough to handle
1470 fixed-offset time zones, and time zones accounting for both standard and
1471 daylight time, and the latter even if the DST transition times differ in
1472 different years. An example of a time zone the default :meth:`fromutc`
1473 implementation may not handle correctly in all cases is one where the standard
1474 offset (from UTC) depends on the specific date and time passed, which can happen
1475 for political reasons. The default implementations of :meth:`astimezone` and
1476 :meth:`fromutc` may not produce the result you want if the result is one of the
1477 hours straddling the moment the standard offset changes.
1478
1479 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1480 like::
1481
1482 def fromutc(self, dt):
1483 # raise ValueError error if dt.tzinfo is not self
1484 dtoff = dt.utcoffset()
1485 dtdst = dt.dst()
1486 # raise ValueError if dtoff is None or dtdst is None
1487 delta = dtoff - dtdst # this is self's standard offset
1488 if delta:
1489 dt += delta # convert to standard local time
1490 dtdst = dt.dst()
1491 # raise ValueError if dtdst is None
1492 if dtdst:
1493 return dt + dtdst
1494 else:
1495 return dt
1496
1497Example :class:`tzinfo` classes:
1498
1499.. literalinclude:: ../includes/tzinfo-examples.py
1500
1501
1502Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1503subclass accounting for both standard and daylight time, at the DST transition
1504points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl7bc6e4f2010-03-21 10:03:36 +00001505minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
15061:59 (EDT) on the first Sunday in November::
Georg Brandl116aa622007-08-15 14:28:22 +00001507
1508 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1509 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1510 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1511
1512 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1513
1514 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1515
1516When DST starts (the "start" line), the local wall clock leaps from 1:59 to
15173:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1518``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1519begins. In order for :meth:`astimezone` to make this guarantee, the
1520:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1521Eastern) to be in daylight time.
1522
1523When DST ends (the "end" line), there's a potentially worse problem: there's an
1524hour that can't be spelled unambiguously in local wall time: the last hour of
1525daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1526daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1527to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1528:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1529hours into the same local hour then. In the Eastern example, UTC times of the
1530form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1531:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1532consider times in the "repeated hour" to be in standard time. This is easily
1533arranged, as in the example, by expressing DST switch times in the time zone's
1534standard local time.
1535
1536Applications that can't bear such ambiguities should avoid using hybrid
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001537:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`,
1538or any other fixed-offset :class:`tzinfo` subclass (such as a class representing
1539only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
1540
1541
1542.. _datetime-timezone:
1543
1544:class:`timezone` Objects
1545--------------------------
1546
1547A :class:`timezone` object represents a timezone that is defined by a
1548fixed offset from UTC. Note that objects of this class cannot be used
1549to represent timezone information in the locations where different
1550offsets are used in different days of the year or where historical
1551changes have been made to civil time.
1552
1553
1554.. class:: timezone(offset[, name])
1555
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001556 The *offset* argument must be specified as a :class:`timedelta`
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001557 object representing the difference between the local time and UTC. It must
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001558 be strictly between ``-timedelta(hours=24)`` and
1559 ``timedelta(hours=24)`` and represent a whole number of minutes,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001560 otherwise :exc:`ValueError` is raised.
1561
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001562 The *name* argument is optional. If specified it must be a string that
1563 is used as the value returned by the ``tzname(dt)`` method. Otherwise,
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001564 ``tzname(dt)`` returns a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001565 *offset*, HH and MM are two digits of ``offset.hours`` and
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001566 ``offset.minutes`` respectively.
1567
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001568.. method:: timezone.utcoffset(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001569
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001570 Return the fixed value specified when the :class:`timezone` instance is
1571 constructed. The *dt* argument is ignored. The return value is a
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001572 :class:`timedelta` instance equal to the difference between the
1573 local time and UTC.
1574
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001575.. method:: timezone.tzname(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001576
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001577 Return the fixed value specified when the :class:`timezone` instance is
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001578 constructed or a string 'UTCsHH:MM', where s is the sign of
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001579 *offset*, HH and MM are two digits of ``offset.hours`` and
1580 ``offset.minutes`` respectively.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001581
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001582.. method:: timezone.dst(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001583
1584 Always returns ``None``.
1585
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001586.. method:: timezone.fromutc(dt)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001587
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001588 Return ``dt + offset``. The *dt* argument must be an aware
1589 :class:`datetime` instance, with ``tzinfo`` set to ``self``.
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001590
1591Class attributes:
1592
1593.. attribute:: timezone.utc
1594
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00001595 The UTC timezone, ``timezone(timedelta(0))``.
Georg Brandl48310cd2009-01-03 21:18:54 +00001596
Georg Brandl116aa622007-08-15 14:28:22 +00001597
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001598.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00001599
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001600:meth:`strftime` and :meth:`strptime` Behavior
1601----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001602
1603:class:`date`, :class:`datetime`, and :class:`time` objects all support a
1604``strftime(format)`` method, to create a string representing the time under the
1605control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1606acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1607although not all objects support a :meth:`timetuple` method.
1608
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001609Conversely, the :meth:`datetime.strptime` class method creates a
1610:class:`datetime` object from a string representing a date and time and a
1611corresponding format string. ``datetime.strptime(date_string, format)`` is
1612equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1613
Georg Brandl116aa622007-08-15 14:28:22 +00001614For :class:`time` objects, the format codes for year, month, and day should not
1615be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001616is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00001617
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001618For :class:`date` objects, the format codes for hours, minutes, seconds, and
1619microseconds should not be used, as :class:`date` objects have no such
1620values. If they're used anyway, ``0`` is substituted for them.
1621
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001622For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1623strings.
1624
1625For an aware object:
1626
1627``%z``
1628 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1629 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1630 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1631 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1632 replaced with the string ``'-0330'``.
1633
1634``%Z``
1635 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1636 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl116aa622007-08-15 14:28:22 +00001637
Georg Brandl116aa622007-08-15 14:28:22 +00001638The full set of format codes supported varies across platforms, because Python
1639calls the platform C library's :func:`strftime` function, and platform
Georg Brandl48310cd2009-01-03 21:18:54 +00001640variations are common.
Christian Heimes895627f2007-12-08 17:28:33 +00001641
1642The following is a list of all the format codes that the C standard (1989
1643version) requires, and these work on all platforms with a standard C
1644implementation. Note that the 1999 version of the C standard added additional
1645format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001646
1647The exact range of years for which :meth:`strftime` works also varies across
1648platforms. Regardless of platform, years before 1900 cannot be used.
1649
Christian Heimes895627f2007-12-08 17:28:33 +00001650+-----------+--------------------------------+-------+
1651| Directive | Meaning | Notes |
1652+===========+================================+=======+
1653| ``%a`` | Locale's abbreviated weekday | |
1654| | name. | |
1655+-----------+--------------------------------+-------+
1656| ``%A`` | Locale's full weekday name. | |
1657+-----------+--------------------------------+-------+
1658| ``%b`` | Locale's abbreviated month | |
1659| | name. | |
1660+-----------+--------------------------------+-------+
1661| ``%B`` | Locale's full month name. | |
1662+-----------+--------------------------------+-------+
1663| ``%c`` | Locale's appropriate date and | |
1664| | time representation. | |
1665+-----------+--------------------------------+-------+
1666| ``%d`` | Day of the month as a decimal | |
1667| | number [01,31]. | |
1668+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001669| ``%f`` | Microsecond as a decimal | \(1) |
1670| | number [0,999999], zero-padded | |
1671| | on the left | |
1672+-----------+--------------------------------+-------+
Christian Heimes895627f2007-12-08 17:28:33 +00001673| ``%H`` | Hour (24-hour clock) as a | |
1674| | decimal number [00,23]. | |
1675+-----------+--------------------------------+-------+
1676| ``%I`` | Hour (12-hour clock) as a | |
1677| | decimal number [01,12]. | |
1678+-----------+--------------------------------+-------+
1679| ``%j`` | Day of the year as a decimal | |
1680| | number [001,366]. | |
1681+-----------+--------------------------------+-------+
1682| ``%m`` | Month as a decimal number | |
1683| | [01,12]. | |
1684+-----------+--------------------------------+-------+
1685| ``%M`` | Minute as a decimal number | |
1686| | [00,59]. | |
1687+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001688| ``%p`` | Locale's equivalent of either | \(2) |
Christian Heimes895627f2007-12-08 17:28:33 +00001689| | AM or PM. | |
1690+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001691| ``%S`` | Second as a decimal number | \(3) |
Christian Heimes895627f2007-12-08 17:28:33 +00001692| | [00,61]. | |
1693+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001694| ``%U`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001695| | (Sunday as the first day of | |
1696| | the week) as a decimal number | |
1697| | [00,53]. All days in a new | |
1698| | year preceding the first | |
1699| | Sunday are considered to be in | |
1700| | week 0. | |
1701+-----------+--------------------------------+-------+
1702| ``%w`` | Weekday as a decimal number | |
1703| | [0(Sunday),6]. | |
1704+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001705| ``%W`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001706| | (Monday as the first day of | |
1707| | the week) as a decimal number | |
1708| | [00,53]. All days in a new | |
1709| | year preceding the first | |
1710| | Monday are considered to be in | |
1711| | week 0. | |
1712+-----------+--------------------------------+-------+
1713| ``%x`` | Locale's appropriate date | |
1714| | representation. | |
1715+-----------+--------------------------------+-------+
1716| ``%X`` | Locale's appropriate time | |
1717| | representation. | |
1718+-----------+--------------------------------+-------+
1719| ``%y`` | Year without century as a | |
1720| | decimal number [00,99]. | |
1721+-----------+--------------------------------+-------+
1722| ``%Y`` | Year with century as a decimal | |
1723| | number. | |
1724+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001725| ``%z`` | UTC offset in the form +HHMM | \(5) |
Christian Heimes895627f2007-12-08 17:28:33 +00001726| | or -HHMM (empty string if the | |
1727| | the object is naive). | |
1728+-----------+--------------------------------+-------+
1729| ``%Z`` | Time zone name (empty string | |
1730| | if the object is naive). | |
1731+-----------+--------------------------------+-------+
1732| ``%%`` | A literal ``'%'`` character. | |
1733+-----------+--------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001734
Christian Heimes895627f2007-12-08 17:28:33 +00001735Notes:
1736
1737(1)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001738 When used with the :meth:`strptime` method, the ``%f`` directive
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001739 accepts from one to six digits and zero pads on the right. ``%f`` is
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001740 an extension to the set of format characters in the C standard (but
1741 implemented separately in datetime objects, and therefore always
1742 available).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001743
1744(2)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001745 When used with the :meth:`strptime` method, the ``%p`` directive only affects
Christian Heimes895627f2007-12-08 17:28:33 +00001746 the output hour field if the ``%I`` directive is used to parse the hour.
1747
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001748(3)
R. David Murraybd25d332009-04-02 04:50:03 +00001749 The range really is ``0`` to ``61``; according to the Posix standard this
1750 accounts for leap seconds and the (very rare) double leap seconds.
1751 The :mod:`time` module may produce and does accept leap seconds since
1752 it is based on the Posix standard, but the :mod:`datetime` module
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001753 does not accept leap seconds in :meth:`strptime` input nor will it
R. David Murraybd25d332009-04-02 04:50:03 +00001754 produce them in :func:`strftime` output.
Christian Heimes895627f2007-12-08 17:28:33 +00001755
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001756(4)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001757 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in
Christian Heimes895627f2007-12-08 17:28:33 +00001758 calculations when the day of the week and the year are specified.
1759
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001760(5)
Christian Heimes895627f2007-12-08 17:28:33 +00001761 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1762 ``%z`` is replaced with the string ``'-0330'``.
Alexander Belopolskyca94f552010-06-17 18:30:34 +00001763
1764.. versionadded:: 3.2
1765
1766 When the ``%z`` directive is provided to the :meth:`strptime`
1767 method, an aware :class:`datetime` object will be produced. The
1768 ``tzinfo`` of the result will be set to a :class:`timezone`
1769 instance.