blob: 4fc7e9eef1ea4f032545da54645c0150c8e4d7ab [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Georg Brandlb19be572007-12-29 10:57:00 +000010.. XXX what order should the types be discussed in?
Georg Brandl8ec7f652007-08-15 14:28:01 +000011
12.. versionadded:: 2.3
13
14The :mod:`datetime` module supplies classes for manipulating dates and times in
15both simple and complex ways. While date and time arithmetic is supported, the
Senthil Kumaran6f18b982011-07-04 12:50:02 -070016focus of the implementation is on efficient attribute extraction for output
R David Murray8349bc22012-05-14 22:33:36 -040017formatting and manipulation. For related functionality, see also the
18:mod:`time` and :mod:`calendar` modules.
Georg Brandl8ec7f652007-08-15 14:28:01 +000019
R David Murray089d4d42012-05-14 22:32:44 -040020There are two kinds of date and time objects: "naive" and "aware".
21
22An aware object has sufficient knowledge of applicable algorithmic and
23political time adjustments, such as time zone and daylight saving time
24information, to locate itself relative to other aware objects. An aware object
25is used to represent a specific moment in time that is not open to
26interpretation [#]_.
27
28+A naive object does not contain enough information to unambiguously locate
R David Murray8349bc22012-05-14 22:33:36 -040029+itself relative to other date/time objects. Whether a naive object represents
30Coordinated Universal Time (UTC), local time, or time in some other timezone is
31purely up to the program, just like it's up to the program whether a particular
32number represents metres, miles, or mass. Naive objects are easy to understand
33and to work with, at the cost of ignoring some aspects of reality.
Georg Brandl8ec7f652007-08-15 14:28:01 +000034
R David Murray8349bc22012-05-14 22:33:36 -040035For applications requiring aware objects, :class:`.datetime` and :class:`.time`
36objects have an optional time zone information attribute, :attr:`tzinfo`, that
37can be set to an instance of a subclass of the abstract :class:`tzinfo` class.
38These :class:`tzinfo` objects capture information about the offset from UTC
39time, the time zone name, and whether Daylight Saving Time is in effect. Note
40that no concrete :class:`tzinfo` classes are supplied by the :mod:`datetime`
41module. Supporting timezones at whatever level of detail is required is up to
42the application. The rules for time adjustment across the world are more
43political than rational, and there is no standard suitable for every
44application.
Georg Brandl8ec7f652007-08-15 14:28:01 +000045
46The :mod:`datetime` module exports the following constants:
47
Georg Brandl8ec7f652007-08-15 14:28:01 +000048.. data:: MINYEAR
49
Sandro Tosi8d38fcf2012-02-18 20:28:35 +010050 The smallest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl8ec7f652007-08-15 14:28:01 +000051 :const:`MINYEAR` is ``1``.
52
53
54.. data:: MAXYEAR
55
Sandro Tosi8d38fcf2012-02-18 20:28:35 +010056 The largest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl8ec7f652007-08-15 14:28:01 +000057 :const:`MAXYEAR` is ``9999``.
58
59
60.. seealso::
61
62 Module :mod:`calendar`
63 General calendar related functions.
64
65 Module :mod:`time`
66 Time access and conversions.
67
68
69Available Types
70---------------
71
Georg Brandl8ec7f652007-08-15 14:28:01 +000072.. class:: date
Georg Brandl592c58d2009-09-19 10:42:34 +000073 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +000074
75 An idealized naive date, assuming the current Gregorian calendar always was, and
76 always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and
77 :attr:`day`.
78
79
80.. class:: time
Georg Brandl592c58d2009-09-19 10:42:34 +000081 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +000082
83 An idealized time, independent of any particular day, assuming that every day
84 has exactly 24\*60\*60 seconds (there is no notion of "leap seconds" here).
85 Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
86 and :attr:`tzinfo`.
87
88
89.. class:: datetime
Georg Brandl592c58d2009-09-19 10:42:34 +000090 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +000091
92 A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`,
93 :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
94 and :attr:`tzinfo`.
95
96
97.. class:: timedelta
Georg Brandl592c58d2009-09-19 10:42:34 +000098 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +000099
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100100 A duration expressing the difference between two :class:`date`, :class:`.time`,
101 or :class:`.datetime` instances to microsecond resolution.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000102
103
104.. class:: tzinfo
105
106 An abstract base class for time zone information objects. These are used by the
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100107 :class:`.datetime` and :class:`.time` classes to provide a customizable notion of
Georg Brandl8ec7f652007-08-15 14:28:01 +0000108 time adjustment (for example, to account for time zone and/or daylight saving
109 time).
110
111Objects of these types are immutable.
112
113Objects of the :class:`date` type are always naive.
114
R David Murray089d4d42012-05-14 22:32:44 -0400115An object of type :class:`.time` or :class:`.datetime` may be naive or aware.
116A :class:`.datetime` object *d* is aware if ``d.tzinfo`` is not ``None`` and
117``d.tzinfo.utcoffset(d)`` does not return ``None``. If ``d.tzinfo`` is
118``None``, or if ``d.tzinfo`` is not ``None`` but ``d.tzinfo.utcoffset(d)``
119returns ``None``, *d* is naive. A :class:`.time` object *t* is aware
120if ``t.tzinfo`` is not ``None`` and ``t.tzinfo.utcoffset(None)`` does not return
121``None``. Otherwise, *t* is naive.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000122
123The distinction between naive and aware doesn't apply to :class:`timedelta`
124objects.
125
126Subclass relationships::
127
128 object
129 timedelta
130 tzinfo
131 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 Brandl8ec7f652007-08-15 14:28:01 +0000144.. class:: timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
145
146 All arguments are optional and default to ``0``. Arguments may be ints, longs,
147 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
Georg Brandl3f043032008-03-22 21:21:57 +0000173 example,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000174
Georg Brandle40a6a82007-12-08 11:23:13 +0000175 >>> from datetime import timedelta
Georg Brandl8ec7f652007-08-15 14:28:01 +0000176 >>> d = timedelta(microseconds=-1)
177 >>> (d.days, d.seconds, d.microseconds)
178 (-1, 86399, 999999)
179
Georg Brandl8ec7f652007-08-15 14:28:01 +0000180
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000181Class attributes are:
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Georg Brandlb19be572007-12-29 10:57:00 +0000216.. XXX this table is too wide!
Georg Brandl8ec7f652007-08-15 14:28:01 +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+--------------------------------+-----------------------------------------------+
228| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer or long. |
229| | 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+--------------------------------+-----------------------------------------------+
235| ``t1 = t2 // i`` | The floor is computed and the remainder (if |
236| | any) is thrown away. (3) |
237+--------------------------------+-----------------------------------------------+
238| ``+t1`` | Returns a :class:`timedelta` object with the |
239| | same value. (2) |
240+--------------------------------+-----------------------------------------------+
241| ``-t1`` | equivalent to :class:`timedelta`\ |
242| | (-*t1.days*, -*t1.seconds*, |
243| | -*t1.microseconds*), and to *t1*\* -1. (1)(4) |
244+--------------------------------+-----------------------------------------------+
Georg Brandl5ffa1462009-10-13 18:10:59 +0000245| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, and|
Georg Brandl8ec7f652007-08-15 14:28:01 +0000246| | to -*t* when ``t.days < 0``. (2) |
247+--------------------------------+-----------------------------------------------+
Georg Brandlad8ac862010-08-01 19:21:26 +0000248| ``str(t)`` | Returns a string in the form |
249| | ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D |
250| | is negative for negative ``t``. (5) |
251+--------------------------------+-----------------------------------------------+
252| ``repr(t)`` | Returns a string in the form |
253| | ``datetime.timedelta(D[, S[, U]])``, where D |
254| | is negative for negative ``t``. (5) |
255+--------------------------------+-----------------------------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000256
257Notes:
258
259(1)
260 This is exact, but may overflow.
261
262(2)
263 This is exact, and cannot overflow.
264
265(3)
266 Division by 0 raises :exc:`ZeroDivisionError`.
267
268(4)
269 -*timedelta.max* is not representable as a :class:`timedelta` object.
270
Georg Brandlad8ac862010-08-01 19:21:26 +0000271(5)
272 String representations of :class:`timedelta` objects are normalized
273 similarly to their internal representation. This leads to somewhat
274 unusual results for negative timedeltas. For example:
275
276 >>> timedelta(hours=-5)
277 datetime.timedelta(-1, 68400)
278 >>> print(_)
279 -1 day, 19:00:00
280
Georg Brandl8ec7f652007-08-15 14:28:01 +0000281In addition to the operations listed above :class:`timedelta` objects support
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100282certain additions and subtractions with :class:`date` and :class:`.datetime`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000283objects (see below).
284
285Comparisons of :class:`timedelta` objects are supported with the
286:class:`timedelta` object representing the smaller duration considered to be the
287smaller timedelta. In order to stop mixed-type comparisons from falling back to
288the default comparison by object address, when a :class:`timedelta` object is
289compared to an object of a different type, :exc:`TypeError` is raised unless the
290comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
291:const:`True`, respectively.
292
Georg Brandl7c3e79f2007-11-02 20:06:17 +0000293:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl8ec7f652007-08-15 14:28:01 +0000294efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
295considered to be true if and only if it isn't equal to ``timedelta(0)``.
296
Antoine Pitroubcfaf802009-11-25 22:59:36 +0000297Instance methods:
298
299.. method:: timedelta.total_seconds()
300
Mark Dickinson7000e9e2010-05-09 09:30:06 +0000301 Return the total number of seconds contained in the duration.
302 Equivalent to ``(td.microseconds + (td.seconds + td.days * 24 *
303 3600) * 10**6) / 10**6`` computed with true division enabled.
304
305 Note that for very large time intervals (greater than 270 years on
306 most platforms) this method will lose microsecond accuracy.
Antoine Pitroubcfaf802009-11-25 22:59:36 +0000307
Antoine Pitroue236c3c2009-11-25 23:03:22 +0000308 .. versionadded:: 2.7
309
Antoine Pitroubcfaf802009-11-25 22:59:36 +0000310
Georg Brandl3f043032008-03-22 21:21:57 +0000311Example usage:
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000312
Georg Brandle40a6a82007-12-08 11:23:13 +0000313 >>> from datetime import timedelta
314 >>> year = timedelta(days=365)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000315 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Georg Brandle40a6a82007-12-08 11:23:13 +0000316 ... minutes=50, seconds=600) # adds up to 365 days
Antoine Pitroubcfaf802009-11-25 22:59:36 +0000317 >>> year.total_seconds()
318 31536000.0
Georg Brandle40a6a82007-12-08 11:23:13 +0000319 >>> year == another_year
320 True
321 >>> ten_years = 10 * year
322 >>> ten_years, ten_years.days // 365
323 (datetime.timedelta(3650), 10)
324 >>> nine_years = ten_years - year
325 >>> nine_years, nine_years.days // 365
326 (datetime.timedelta(3285), 9)
327 >>> three_years = nine_years // 3;
328 >>> three_years, three_years.days // 365
329 (datetime.timedelta(1095), 3)
330 >>> abs(three_years - ten_years) == 2 * three_years + year
331 True
332
Georg Brandl8ec7f652007-08-15 14:28:01 +0000333
334.. _datetime-date:
335
336:class:`date` Objects
337---------------------
338
339A :class:`date` object represents a date (year, month and day) in an idealized
340calendar, the current Gregorian calendar indefinitely extended in both
341directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
342called day number 2, and so on. This matches the definition of the "proleptic
343Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
344where it's the base calendar for all computations. See the book for algorithms
345for converting between proleptic Gregorian ordinals and many other calendar
346systems.
347
348
349.. class:: date(year, month, day)
350
351 All arguments are required. Arguments may be ints or longs, in the following
352 ranges:
353
354 * ``MINYEAR <= year <= MAXYEAR``
355 * ``1 <= month <= 12``
356 * ``1 <= day <= number of days in the given month and year``
357
358 If an argument outside those ranges is given, :exc:`ValueError` is raised.
359
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000360
Georg Brandl8ec7f652007-08-15 14:28:01 +0000361Other constructors, all class methods:
362
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000363.. classmethod:: date.today()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000364
365 Return the current local date. This is equivalent to
366 ``date.fromtimestamp(time.time())``.
367
368
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000369.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000370
371 Return the local date corresponding to the POSIX timestamp, such as is returned
372 by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100373 of the range of values supported by the platform C :c:func:`localtime` function.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000374 It's common for this to be restricted to years from 1970 through 2038. Note
375 that on non-POSIX systems that include leap seconds in their notion of a
376 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
377
378
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000379.. classmethod:: date.fromordinal(ordinal)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000380
381 Return the date corresponding to the proleptic Gregorian ordinal, where January
382 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
383 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
384 d``.
385
Georg Brandl8ec7f652007-08-15 14:28:01 +0000386
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000387Class attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000388
389.. attribute:: date.min
390
391 The earliest representable date, ``date(MINYEAR, 1, 1)``.
392
393
394.. attribute:: date.max
395
396 The latest representable date, ``date(MAXYEAR, 12, 31)``.
397
398
399.. attribute:: date.resolution
400
401 The smallest possible difference between non-equal date objects,
402 ``timedelta(days=1)``.
403
Georg Brandl8ec7f652007-08-15 14:28:01 +0000404
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000405Instance attributes (read-only):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000406
407.. attribute:: date.year
408
409 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
410
411
412.. attribute:: date.month
413
414 Between 1 and 12 inclusive.
415
416
417.. attribute:: date.day
418
419 Between 1 and the number of days in the given month of the given year.
420
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000421
Georg Brandl8ec7f652007-08-15 14:28:01 +0000422Supported operations:
423
424+-------------------------------+----------------------------------------------+
425| Operation | Result |
426+===============================+==============================================+
427| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
428| | from *date1*. (1) |
429+-------------------------------+----------------------------------------------+
430| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
431| | timedelta == date1``. (2) |
432+-------------------------------+----------------------------------------------+
433| ``timedelta = date1 - date2`` | \(3) |
434+-------------------------------+----------------------------------------------+
435| ``date1 < date2`` | *date1* is considered less than *date2* when |
436| | *date1* precedes *date2* in time. (4) |
437+-------------------------------+----------------------------------------------+
438
439Notes:
440
441(1)
442 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
443 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
444 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
445 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
446 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
447
448(2)
449 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
450 isolation can overflow in cases where date1 - timedelta does not.
451 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
452
453(3)
454 This is exact, and cannot overflow. timedelta.seconds and
455 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
456
457(4)
458 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
459 date2.toordinal()``. In order to stop comparison from falling back to the
460 default scheme of comparing object addresses, date comparison normally raises
461 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
462 However, ``NotImplemented`` is returned instead if the other comparand has a
463 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
464 chance at implementing mixed-type comparison. If not, when a :class:`date`
465 object is compared to an object of a different type, :exc:`TypeError` is raised
466 unless the comparison is ``==`` or ``!=``. The latter cases return
467 :const:`False` or :const:`True`, respectively.
468
469Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
470objects are considered to be true.
471
472Instance methods:
473
Georg Brandl8ec7f652007-08-15 14:28:01 +0000474.. method:: date.replace(year, month, day)
475
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700476 Return a date with the same value, except for those parameters given new
477 values by whichever keyword arguments are specified. For example, if ``d ==
478 date(2002, 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000479
480
481.. method:: date.timetuple()
482
483 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
484 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
485 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
Georg Brandl151973e2010-05-23 21:29:29 +0000486 d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1,
487 1).toordinal() + 1`` is the day number within the current year starting with
488 ``1`` for January 1st.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000489
490
491.. method:: date.toordinal()
492
493 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
494 has ordinal 1. For any :class:`date` object *d*,
495 ``date.fromordinal(d.toordinal()) == d``.
496
497
498.. method:: date.weekday()
499
500 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
501 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
502 :meth:`isoweekday`.
503
504
505.. method:: date.isoweekday()
506
507 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
508 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
509 :meth:`weekday`, :meth:`isocalendar`.
510
511
512.. method:: date.isocalendar()
513
514 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
515
516 The ISO calendar is a widely used variant of the Gregorian calendar. See
Mark Dickinson5b544322009-11-03 16:26:14 +0000517 http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
518 explanation.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000519
520 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
521 Monday and ends on a Sunday. The first week of an ISO year is the first
522 (Gregorian) calendar week of a year containing a Thursday. This is called week
523 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
524
525 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
526 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
527 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
528 4).isocalendar() == (2004, 1, 7)``.
529
530
531.. method:: date.isoformat()
532
533 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
534 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
535
536
537.. method:: date.__str__()
538
539 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
540
541
542.. method:: date.ctime()
543
544 Return a string representing the date, for example ``date(2002, 12,
545 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
546 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100547 :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl8ec7f652007-08-15 14:28:01 +0000548 :meth:`date.ctime` does not invoke) conforms to the C standard.
549
550
551.. method:: date.strftime(format)
552
553 Return a string representing the date, controlled by an explicit format string.
554 Format codes referring to hours, minutes or seconds will see 0 values. See
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000555 section :ref:`strftime-strptime-behavior`.
556
Georg Brandl8ec7f652007-08-15 14:28:01 +0000557
Georg Brandle40a6a82007-12-08 11:23:13 +0000558Example of counting days to an event::
559
560 >>> import time
561 >>> from datetime import date
562 >>> today = date.today()
563 >>> today
564 datetime.date(2007, 12, 5)
565 >>> today == date.fromtimestamp(time.time())
566 True
567 >>> my_birthday = date(today.year, 6, 24)
568 >>> if my_birthday < today:
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000569 ... my_birthday = my_birthday.replace(year=today.year + 1)
Georg Brandle40a6a82007-12-08 11:23:13 +0000570 >>> my_birthday
571 datetime.date(2008, 6, 24)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000572 >>> time_to_birthday = abs(my_birthday - today)
Georg Brandle40a6a82007-12-08 11:23:13 +0000573 >>> time_to_birthday.days
574 202
575
Georg Brandl3f043032008-03-22 21:21:57 +0000576Example of working with :class:`date`:
577
578.. doctest::
Georg Brandle40a6a82007-12-08 11:23:13 +0000579
580 >>> from datetime import date
581 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
582 >>> d
583 datetime.date(2002, 3, 11)
584 >>> t = d.timetuple()
Georg Brandl3f043032008-03-22 21:21:57 +0000585 >>> for i in t: # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +0000586 ... print i
587 2002 # year
588 3 # month
589 11 # day
590 0
591 0
592 0
593 0 # weekday (0 = Monday)
594 70 # 70th day in the year
595 -1
596 >>> ic = d.isocalendar()
Georg Brandl3f043032008-03-22 21:21:57 +0000597 >>> for i in ic: # doctest: +SKIP
598 ... print i
Georg Brandle40a6a82007-12-08 11:23:13 +0000599 2002 # ISO year
600 11 # ISO week number
601 1 # ISO day number ( 1 = Monday )
602 >>> d.isoformat()
603 '2002-03-11'
604 >>> d.strftime("%d/%m/%y")
605 '11/03/02'
606 >>> d.strftime("%A %d. %B %Y")
607 'Monday 11. March 2002'
608
Georg Brandl8ec7f652007-08-15 14:28:01 +0000609
610.. _datetime-datetime:
611
612:class:`datetime` Objects
613-------------------------
614
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100615A :class:`.datetime` object is a single object containing all the information
616from a :class:`date` object and a :class:`.time` object. Like a :class:`date`
617object, :class:`.datetime` assumes the current Gregorian calendar extended in
618both directions; like a time object, :class:`.datetime` assumes there are exactly
Georg Brandl8ec7f652007-08-15 14:28:01 +00006193600\*24 seconds in every day.
620
621Constructor:
622
Georg Brandl8ec7f652007-08-15 14:28:01 +0000623.. class:: datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])
624
625 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
626 instance of a :class:`tzinfo` subclass. The remaining arguments may be ints or
627 longs, in the following ranges:
628
629 * ``MINYEAR <= year <= MAXYEAR``
630 * ``1 <= month <= 12``
631 * ``1 <= day <= number of days in the given month and year``
632 * ``0 <= hour < 24``
633 * ``0 <= minute < 60``
634 * ``0 <= second < 60``
635 * ``0 <= microsecond < 1000000``
636
637 If an argument outside those ranges is given, :exc:`ValueError` is raised.
638
639Other constructors, all class methods:
640
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000641.. classmethod:: datetime.today()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000642
643 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
644 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
645 :meth:`fromtimestamp`.
646
647
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000648.. classmethod:: datetime.now([tz])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000649
650 Return the current local date and time. If optional argument *tz* is ``None``
651 or not specified, this is like :meth:`today`, but, if possible, supplies more
652 precision than can be gotten from going through a :func:`time.time` timestamp
653 (for example, this may be possible on platforms supplying the C
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100654 :c:func:`gettimeofday` function).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000655
656 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
657 current date and time are converted to *tz*'s time zone. In this case the
658 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
659 See also :meth:`today`, :meth:`utcnow`.
660
661
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000662.. classmethod:: datetime.utcnow()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000663
664 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
665 :meth:`now`, but returns the current UTC date and time, as a naive
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100666 :class:`.datetime` object. See also :meth:`now`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000667
668
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000669.. classmethod:: datetime.fromtimestamp(timestamp[, tz])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000670
671 Return the local date and time corresponding to the POSIX timestamp, such as is
672 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
673 specified, the timestamp is converted to the platform's local date and time, and
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100674 the returned :class:`.datetime` object is naive.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000675
676 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
677 timestamp is converted to *tz*'s time zone. In this case the result is
678 equivalent to
679 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
680
681 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100682 the range of values supported by the platform C :c:func:`localtime` or
683 :c:func:`gmtime` functions. It's common for this to be restricted to years in
Georg Brandl8ec7f652007-08-15 14:28:01 +0000684 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
685 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
686 and then it's possible to have two timestamps differing by a second that yield
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100687 identical :class:`.datetime` objects. See also :meth:`utcfromtimestamp`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000688
689
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000690.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000691
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100692 Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with
Georg Brandl8ec7f652007-08-15 14:28:01 +0000693 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100694 out of the range of values supported by the platform C :c:func:`gmtime` function.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000695 It's common for this to be restricted to years in 1970 through 2038. See also
696 :meth:`fromtimestamp`.
697
698
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000699.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000700
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100701 Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000702 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
703 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
704 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
705
706
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000707.. classmethod:: datetime.combine(date, time)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000708
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100709 Return a new :class:`.datetime` object whose date components are equal to the
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800710 given :class:`date` object's, and whose time components and :attr:`tzinfo`
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100711 attributes are equal to the given :class:`.time` object's. For any
712 :class:`.datetime` object *d*,
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800713 ``d == datetime.combine(d.date(), d.timetz())``. If date is a
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100714 :class:`.datetime` object, its time components and :attr:`tzinfo` attributes
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800715 are ignored.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000716
717
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000718.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000719
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100720 Return a :class:`.datetime` corresponding to *date_string*, parsed according to
Georg Brandl8ec7f652007-08-15 14:28:01 +0000721 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
722 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
723 can't be parsed by :func:`time.strptime` or if it returns a value which isn't a
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000724 time tuple. See section :ref:`strftime-strptime-behavior`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000725
726 .. versionadded:: 2.5
727
Georg Brandl8ec7f652007-08-15 14:28:01 +0000728
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000729Class attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000730
731.. attribute:: datetime.min
732
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100733 The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000734 tzinfo=None)``.
735
736
737.. attribute:: datetime.max
738
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100739 The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000740 59, 999999, tzinfo=None)``.
741
742
743.. attribute:: datetime.resolution
744
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100745 The smallest possible difference between non-equal :class:`.datetime` objects,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000746 ``timedelta(microseconds=1)``.
747
Georg Brandl8ec7f652007-08-15 14:28:01 +0000748
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000749Instance attributes (read-only):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000750
751.. attribute:: datetime.year
752
753 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
754
755
756.. attribute:: datetime.month
757
758 Between 1 and 12 inclusive.
759
760
761.. attribute:: datetime.day
762
763 Between 1 and the number of days in the given month of the given year.
764
765
766.. attribute:: datetime.hour
767
768 In ``range(24)``.
769
770
771.. attribute:: datetime.minute
772
773 In ``range(60)``.
774
775
776.. attribute:: datetime.second
777
778 In ``range(60)``.
779
780
781.. attribute:: datetime.microsecond
782
783 In ``range(1000000)``.
784
785
786.. attribute:: datetime.tzinfo
787
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100788 The object passed as the *tzinfo* argument to the :class:`.datetime` constructor,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000789 or ``None`` if none was passed.
790
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000791
Georg Brandl8ec7f652007-08-15 14:28:01 +0000792Supported operations:
793
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100794+---------------------------------------+--------------------------------+
795| Operation | Result |
796+=======================================+================================+
797| ``datetime2 = datetime1 + timedelta`` | \(1) |
798+---------------------------------------+--------------------------------+
799| ``datetime2 = datetime1 - timedelta`` | \(2) |
800+---------------------------------------+--------------------------------+
801| ``timedelta = datetime1 - datetime2`` | \(3) |
802+---------------------------------------+--------------------------------+
803| ``datetime1 < datetime2`` | Compares :class:`.datetime` to |
804| | :class:`.datetime`. (4) |
805+---------------------------------------+--------------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000806
807(1)
808 datetime2 is a duration of timedelta removed from datetime1, moving forward in
809 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700810 result has the same :attr:`tzinfo` attribute as the input datetime, and
811 datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
812 datetime2.year would be smaller than :const:`MINYEAR` or larger than
813 :const:`MAXYEAR`. Note that no time zone adjustments are done even if the
814 input is an aware object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000815
816(2)
817 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700818 addition, the result has the same :attr:`tzinfo` attribute as the input
819 datetime, and no time zone adjustments are done even if the input is aware.
820 This isn't quite equivalent to datetime1 + (-timedelta), because -timedelta
821 in isolation can overflow in cases where datetime1 - timedelta does not.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000822
823(3)
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100824 Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if
Georg Brandl8ec7f652007-08-15 14:28:01 +0000825 both operands are naive, or if both are aware. If one is aware and the other is
826 naive, :exc:`TypeError` is raised.
827
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700828 If both are naive, or both are aware and have the same :attr:`tzinfo` attribute,
829 the :attr:`tzinfo` attributes are ignored, and the result is a :class:`timedelta`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000830 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
831 are done in this case.
832
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700833 If both are aware and have different :attr:`tzinfo` attributes, ``a-b`` acts
834 as if *a* and *b* were first converted to naive UTC datetimes first. The
835 result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
836 - b.utcoffset())`` except that the implementation never overflows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000837
838(4)
839 *datetime1* is considered less than *datetime2* when *datetime1* precedes
840 *datetime2* in time.
841
842 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700843 If both comparands are aware, and have the same :attr:`tzinfo` attribute, the
844 common :attr:`tzinfo` attribute is ignored and the base datetimes are
845 compared. If both comparands are aware and have different :attr:`tzinfo`
846 attributes, the comparands are first adjusted by subtracting their UTC
847 offsets (obtained from ``self.utcoffset()``).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000848
849 .. note::
850
851 In order to stop comparison from falling back to the default scheme of comparing
852 object addresses, datetime comparison normally raises :exc:`TypeError` if the
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100853 other comparand isn't also a :class:`.datetime` object. However,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000854 ``NotImplemented`` is returned instead if the other comparand has a
855 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100856 chance at implementing mixed-type comparison. If not, when a :class:`.datetime`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000857 object is compared to an object of a different type, :exc:`TypeError` is raised
858 unless the comparison is ``==`` or ``!=``. The latter cases return
859 :const:`False` or :const:`True`, respectively.
860
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100861:class:`.datetime` objects can be used as dictionary keys. In Boolean contexts,
862all :class:`.datetime` objects are considered to be true.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000863
864Instance methods:
865
Georg Brandl8ec7f652007-08-15 14:28:01 +0000866.. method:: datetime.date()
867
868 Return :class:`date` object with same year, month and day.
869
870
871.. method:: datetime.time()
872
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100873 Return :class:`.time` object with same hour, minute, second and microsecond.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000874 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
875
876
877.. method:: datetime.timetz()
878
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100879 Return :class:`.time` object with same hour, minute, second, microsecond, and
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700880 tzinfo attributes. See also method :meth:`time`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000881
882
883.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
884
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700885 Return a datetime with the same attributes, except for those attributes given
886 new values by whichever keyword arguments are specified. Note that
887 ``tzinfo=None`` can be specified to create a naive datetime from an aware
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800888 datetime with no conversion of date and time data.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000889
890
891.. method:: datetime.astimezone(tz)
892
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100893 Return a :class:`.datetime` object with new :attr:`tzinfo` attribute *tz*,
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800894 adjusting the date and time data so the result is the same UTC time as
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700895 *self*, but in *tz*'s local time.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000896
897 *tz* must be an instance of a :class:`tzinfo` subclass, and its
898 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
899 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
900 not return ``None``).
901
902 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800903 adjustment of date or time data is performed. Else the result is local
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700904 time in time zone *tz*, representing the same UTC time as *self*: after
905 ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800906 the same date and time data as ``dt - dt.utcoffset()``. The discussion
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700907 of class :class:`tzinfo` explains the cases at Daylight Saving Time transition
908 boundaries where this cannot be achieved (an issue only if *tz* models both
909 standard and daylight time).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000910
911 If you merely want to attach a time zone object *tz* to a datetime *dt* without
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800912 adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you
Georg Brandl8ec7f652007-08-15 14:28:01 +0000913 merely want to remove the time zone object from an aware datetime *dt* without
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800914 conversion of date and time data, use ``dt.replace(tzinfo=None)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000915
916 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
917 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
918 Ignoring error cases, :meth:`astimezone` acts like::
919
920 def astimezone(self, tz):
921 if self.tzinfo is tz:
922 return self
923 # Convert self to UTC, and attach the new time zone object.
924 utc = (self - self.utcoffset()).replace(tzinfo=tz)
925 # Convert from UTC to tz's local time.
926 return tz.fromutc(utc)
927
928
929.. method:: datetime.utcoffset()
930
931 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
932 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
933 return ``None``, or a :class:`timedelta` object representing a whole number of
934 minutes with magnitude less than one day.
935
936
937.. method:: datetime.dst()
938
939 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
940 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
941 ``None``, or a :class:`timedelta` object representing a whole number of minutes
942 with magnitude less than one day.
943
944
945.. method:: datetime.tzname()
946
947 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
948 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
949 ``None`` or a string object,
950
951
952.. method:: datetime.timetuple()
953
954 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
955 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
Georg Brandl151973e2010-05-23 21:29:29 +0000956 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
957 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
958 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
959 of the result is set according to the :meth:`dst` method: :attr:`tzinfo` is
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000960 ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
Georg Brandl151973e2010-05-23 21:29:29 +0000961 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
Alexander Belopolsky094c53c2010-06-09 17:08:11 +0000962 else :attr:`tm_isdst` is set to ``0``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000963
964
965.. method:: datetime.utctimetuple()
966
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100967 If :class:`.datetime` instance *d* is naive, this is the same as
Georg Brandl8ec7f652007-08-15 14:28:01 +0000968 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
969 ``d.dst()`` returns. DST is never in effect for a UTC time.
970
971 If *d* is aware, *d* is normalized to UTC time, by subtracting
972 ``d.utcoffset()``, and a :class:`time.struct_time` for the normalized time is
973 returned. :attr:`tm_isdst` is forced to 0. Note that the result's
974 :attr:`tm_year` member may be :const:`MINYEAR`\ -1 or :const:`MAXYEAR`\ +1, if
975 *d*.year was ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
976 boundary.
977
978
979.. method:: datetime.toordinal()
980
981 Return the proleptic Gregorian ordinal of the date. The same as
982 ``self.date().toordinal()``.
983
984
985.. method:: datetime.weekday()
986
987 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
988 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
989
990
991.. method:: datetime.isoweekday()
992
993 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
994 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
995 :meth:`isocalendar`.
996
997
998.. method:: datetime.isocalendar()
999
1000 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
1001 ``self.date().isocalendar()``.
1002
1003
1004.. method:: datetime.isoformat([sep])
1005
1006 Return a string representing the date and time in ISO 8601 format,
1007 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
1008 YYYY-MM-DDTHH:MM:SS
1009
1010 If :meth:`utcoffset` does not return ``None``, a 6-character string is
1011 appended, giving the UTC offset in (signed) hours and minutes:
1012 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
1013 YYYY-MM-DDTHH:MM:SS+HH:MM
1014
1015 The optional argument *sep* (default ``'T'``) is a one-character separator,
Georg Brandl3f043032008-03-22 21:21:57 +00001016 placed between the date and time portions of the result. For example,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001017
1018 >>> from datetime import tzinfo, timedelta, datetime
1019 >>> class TZ(tzinfo):
1020 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1021 ...
1022 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1023 '2002-12-25 00:00:00-06:39'
1024
1025
1026.. method:: datetime.__str__()
1027
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001028 For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to
Georg Brandl8ec7f652007-08-15 14:28:01 +00001029 ``d.isoformat(' ')``.
1030
1031
1032.. method:: datetime.ctime()
1033
1034 Return a string representing the date and time, for example ``datetime(2002, 12,
1035 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1036 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
Sandro Tosi98ed08f2012-01-14 16:42:02 +01001037 native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl8ec7f652007-08-15 14:28:01 +00001038 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1039
1040
1041.. method:: datetime.strftime(format)
1042
1043 Return a string representing the date and time, controlled by an explicit format
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001044 string. See section :ref:`strftime-strptime-behavior`.
1045
Georg Brandl8ec7f652007-08-15 14:28:01 +00001046
Georg Brandl3f043032008-03-22 21:21:57 +00001047Examples of working with datetime objects:
1048
1049.. doctest::
1050
Georg Brandle40a6a82007-12-08 11:23:13 +00001051 >>> from datetime import datetime, date, time
1052 >>> # Using datetime.combine()
1053 >>> d = date(2005, 7, 14)
1054 >>> t = time(12, 30)
1055 >>> datetime.combine(d, t)
1056 datetime.datetime(2005, 7, 14, 12, 30)
1057 >>> # Using datetime.now() or datetime.utcnow()
Georg Brandl3f043032008-03-22 21:21:57 +00001058 >>> datetime.now() # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +00001059 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Georg Brandl3f043032008-03-22 21:21:57 +00001060 >>> datetime.utcnow() # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +00001061 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1062 >>> # Using datetime.strptime()
1063 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1064 >>> dt
1065 datetime.datetime(2006, 11, 21, 16, 30)
1066 >>> # Using datetime.timetuple() to get tuple of all attributes
1067 >>> tt = dt.timetuple()
Georg Brandl3f043032008-03-22 21:21:57 +00001068 >>> for it in tt: # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +00001069 ... print it
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001070 ...
Georg Brandle40a6a82007-12-08 11:23:13 +00001071 2006 # year
1072 11 # month
1073 21 # day
1074 16 # hour
1075 30 # minute
1076 0 # second
1077 1 # weekday (0 = Monday)
1078 325 # number of days since 1st January
1079 -1 # dst - method tzinfo.dst() returned None
1080 >>> # Date in ISO format
1081 >>> ic = dt.isocalendar()
Georg Brandl3f043032008-03-22 21:21:57 +00001082 >>> for it in ic: # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +00001083 ... print it
1084 ...
1085 2006 # ISO year
1086 47 # ISO week
1087 2 # ISO weekday
1088 >>> # Formatting datetime
1089 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1090 'Tuesday, 21. November 2006 04:30PM'
1091
Georg Brandl3f043032008-03-22 21:21:57 +00001092Using datetime with tzinfo:
Georg Brandle40a6a82007-12-08 11:23:13 +00001093
1094 >>> from datetime import timedelta, datetime, tzinfo
1095 >>> class GMT1(tzinfo):
1096 ... def __init__(self): # DST starts last Sunday in March
1097 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1098 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001099 ... d = datetime(dt.year, 11, 1)
Georg Brandle40a6a82007-12-08 11:23:13 +00001100 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1101 ... def utcoffset(self, dt):
1102 ... return timedelta(hours=1) + self.dst(dt)
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001103 ... def dst(self, dt):
Georg Brandle40a6a82007-12-08 11:23:13 +00001104 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1105 ... return timedelta(hours=1)
1106 ... else:
1107 ... return timedelta(0)
1108 ... def tzname(self,dt):
1109 ... return "GMT +1"
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001110 ...
Georg Brandle40a6a82007-12-08 11:23:13 +00001111 >>> class GMT2(tzinfo):
1112 ... def __init__(self):
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001113 ... d = datetime(dt.year, 4, 1)
Georg Brandle40a6a82007-12-08 11:23:13 +00001114 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001115 ... d = datetime(dt.year, 11, 1)
Georg Brandle40a6a82007-12-08 11:23:13 +00001116 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1117 ... def utcoffset(self, dt):
1118 ... return timedelta(hours=1) + self.dst(dt)
1119 ... def dst(self, dt):
1120 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1121 ... return timedelta(hours=2)
1122 ... else:
1123 ... return timedelta(0)
1124 ... def tzname(self,dt):
1125 ... return "GMT +2"
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001126 ...
Georg Brandle40a6a82007-12-08 11:23:13 +00001127 >>> gmt1 = GMT1()
1128 >>> # Daylight Saving Time
1129 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1130 >>> dt1.dst()
1131 datetime.timedelta(0)
1132 >>> dt1.utcoffset()
1133 datetime.timedelta(0, 3600)
1134 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1135 >>> dt2.dst()
1136 datetime.timedelta(0, 3600)
1137 >>> dt2.utcoffset()
1138 datetime.timedelta(0, 7200)
1139 >>> # Convert datetime to another time zone
1140 >>> dt3 = dt2.astimezone(GMT2())
1141 >>> dt3 # doctest: +ELLIPSIS
1142 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1143 >>> dt2 # doctest: +ELLIPSIS
1144 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1145 >>> dt2.utctimetuple() == dt3.utctimetuple()
1146 True
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001147
Georg Brandle40a6a82007-12-08 11:23:13 +00001148
Georg Brandl8ec7f652007-08-15 14:28:01 +00001149
1150.. _datetime-time:
1151
1152:class:`time` Objects
1153---------------------
1154
1155A time object represents a (local) time of day, independent of any particular
1156day, and subject to adjustment via a :class:`tzinfo` object.
1157
Georg Brandl8ec7f652007-08-15 14:28:01 +00001158.. class:: time(hour[, minute[, second[, microsecond[, tzinfo]]]])
1159
1160 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
1161 :class:`tzinfo` subclass. The remaining arguments may be ints or longs, in the
1162 following ranges:
1163
1164 * ``0 <= hour < 24``
1165 * ``0 <= minute < 60``
1166 * ``0 <= second < 60``
1167 * ``0 <= microsecond < 1000000``.
1168
1169 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1170 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1171
1172Class attributes:
1173
1174
1175.. attribute:: time.min
1176
Ezio Melottif17e4052011-10-02 12:22:13 +03001177 The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001178
1179
1180.. attribute:: time.max
1181
Ezio Melottif17e4052011-10-02 12:22:13 +03001182 The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001183
1184
1185.. attribute:: time.resolution
1186
Ezio Melottif17e4052011-10-02 12:22:13 +03001187 The smallest possible difference between non-equal :class:`.time` objects,
1188 ``timedelta(microseconds=1)``, although note that arithmetic on
1189 :class:`.time` objects is not supported.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001190
Georg Brandl8ec7f652007-08-15 14:28:01 +00001191
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001192Instance attributes (read-only):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001193
1194.. attribute:: time.hour
1195
1196 In ``range(24)``.
1197
1198
1199.. attribute:: time.minute
1200
1201 In ``range(60)``.
1202
1203
1204.. attribute:: time.second
1205
1206 In ``range(60)``.
1207
1208
1209.. attribute:: time.microsecond
1210
1211 In ``range(1000000)``.
1212
1213
1214.. attribute:: time.tzinfo
1215
Ezio Melottif17e4052011-10-02 12:22:13 +03001216 The object passed as the tzinfo argument to the :class:`.time` constructor, or
Georg Brandl8ec7f652007-08-15 14:28:01 +00001217 ``None`` if none was passed.
1218
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001219
Georg Brandl8ec7f652007-08-15 14:28:01 +00001220Supported operations:
1221
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001222* comparison of :class:`.time` to :class:`.time`, where *a* is considered less
Georg Brandl8ec7f652007-08-15 14:28:01 +00001223 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1224 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
Senthil Kumaran6f18b982011-07-04 12:50:02 -07001225 the same :attr:`tzinfo` attribute, the common :attr:`tzinfo` attribute is
1226 ignored and the base times are compared. If both comparands are aware and
1227 have different :attr:`tzinfo` attributes, the comparands are first adjusted by
1228 subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
1229 to stop mixed-type comparisons from falling back to the default comparison by
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001230 object address, when a :class:`.time` object is compared to an object of a
Senthil Kumaran6f18b982011-07-04 12:50:02 -07001231 different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
1232 ``!=``. The latter cases return :const:`False` or :const:`True`, respectively.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001233
1234* hash, use as dict key
1235
1236* efficient pickling
1237
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001238* in Boolean contexts, a :class:`.time` object is considered to be true if and
Georg Brandl8ec7f652007-08-15 14:28:01 +00001239 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1240 ``0`` if that's ``None``), the result is non-zero.
1241
Georg Brandl8ec7f652007-08-15 14:28:01 +00001242
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001243Instance methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001244
1245.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1246
Ezio Melottif17e4052011-10-02 12:22:13 +03001247 Return a :class:`.time` with the same value, except for those attributes given
Senthil Kumaran6f18b982011-07-04 12:50:02 -07001248 new values by whichever keyword arguments are specified. Note that
Ezio Melottif17e4052011-10-02 12:22:13 +03001249 ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
1250 aware :class:`.time`, without conversion of the time data.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001251
1252
1253.. method:: time.isoformat()
1254
1255 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1256 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1257 6-character string is appended, giving the UTC offset in (signed) hours and
1258 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1259
1260
1261.. method:: time.__str__()
1262
1263 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1264
1265
1266.. method:: time.strftime(format)
1267
1268 Return a string representing the time, controlled by an explicit format string.
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001269 See section :ref:`strftime-strptime-behavior`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001270
1271
1272.. method:: time.utcoffset()
1273
1274 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1275 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1276 return ``None`` or a :class:`timedelta` object representing a whole number of
1277 minutes with magnitude less than one day.
1278
1279
1280.. method:: time.dst()
1281
1282 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1283 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1284 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1285 with magnitude less than one day.
1286
1287
1288.. method:: time.tzname()
1289
1290 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1291 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1292 return ``None`` or a string object.
1293
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001294
Georg Brandl3f043032008-03-22 21:21:57 +00001295Example:
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001296
Georg Brandle40a6a82007-12-08 11:23:13 +00001297 >>> from datetime import time, tzinfo
1298 >>> class GMT1(tzinfo):
1299 ... def utcoffset(self, dt):
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001300 ... return timedelta(hours=1)
1301 ... def dst(self, dt):
Georg Brandle40a6a82007-12-08 11:23:13 +00001302 ... return timedelta(0)
1303 ... def tzname(self,dt):
1304 ... return "Europe/Prague"
1305 ...
1306 >>> t = time(12, 10, 30, tzinfo=GMT1())
1307 >>> t # doctest: +ELLIPSIS
1308 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1309 >>> gmt = GMT1()
1310 >>> t.isoformat()
1311 '12:10:30+01:00'
1312 >>> t.dst()
1313 datetime.timedelta(0)
1314 >>> t.tzname()
1315 'Europe/Prague'
1316 >>> t.strftime("%H:%M:%S %Z")
1317 '12:10:30 Europe/Prague'
1318
Georg Brandl8ec7f652007-08-15 14:28:01 +00001319
1320.. _datetime-tzinfo:
1321
1322:class:`tzinfo` Objects
1323-----------------------
1324
Brett Cannon8aa2c6c2009-01-29 00:54:32 +00001325:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl8ec7f652007-08-15 14:28:01 +00001326instantiated directly. You need to derive a concrete subclass, and (at least)
1327supply implementations of the standard :class:`tzinfo` methods needed by the
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001328:class:`.datetime` methods you use. The :mod:`datetime` module does not supply
Georg Brandl8ec7f652007-08-15 14:28:01 +00001329any concrete subclasses of :class:`tzinfo`.
1330
1331An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001332constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
Senthil Kumaran6f18b982011-07-04 12:50:02 -07001333view their attributes as being in local time, and the :class:`tzinfo` object
Georg Brandl8ec7f652007-08-15 14:28:01 +00001334supports methods revealing offset of local time from UTC, the name of the time
1335zone, and DST offset, all relative to a date or time object passed to them.
1336
1337Special requirement for pickling: A :class:`tzinfo` subclass must have an
1338:meth:`__init__` method that can be called with no arguments, else it can be
1339pickled but possibly not unpickled again. This is a technical requirement that
1340may be relaxed in the future.
1341
1342A concrete subclass of :class:`tzinfo` may need to implement the following
1343methods. Exactly which methods are needed depends on the uses made of aware
1344:mod:`datetime` objects. If in doubt, simply implement all of them.
1345
1346
1347.. method:: tzinfo.utcoffset(self, dt)
1348
1349 Return offset of local time from UTC, in minutes east of UTC. If local time is
1350 west of UTC, this should be negative. Note that this is intended to be the
1351 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1352 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1353 the UTC offset isn't known, return ``None``. Else the value returned must be a
1354 :class:`timedelta` object specifying a whole number of minutes in the range
1355 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1356 than one day). Most implementations of :meth:`utcoffset` will probably look
1357 like one of these two::
1358
1359 return CONSTANT # fixed-offset class
1360 return CONSTANT + self.dst(dt) # daylight-aware class
1361
1362 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1363 ``None`` either.
1364
1365 The default implementation of :meth:`utcoffset` raises
1366 :exc:`NotImplementedError`.
1367
1368
1369.. method:: tzinfo.dst(self, dt)
1370
1371 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1372 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1373 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1374 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1375 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1376 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1377 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
Senthil Kumaran6f18b982011-07-04 12:50:02 -07001378 attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
1379 should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
1380 DST changes when crossing time zones.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001381
1382 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1383 daylight times must be consistent in this sense:
1384
1385 ``tz.utcoffset(dt) - tz.dst(dt)``
1386
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001387 must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo ==
Georg Brandl8ec7f652007-08-15 14:28:01 +00001388 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1389 zone's "standard offset", which should not depend on the date or the time, but
1390 only on geographic location. The implementation of :meth:`datetime.astimezone`
1391 relies on this, but cannot detect violations; it's the programmer's
1392 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1393 this, it may be able to override the default implementation of
1394 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1395
1396 Most implementations of :meth:`dst` will probably look like one of these two::
1397
Sandro Tosi1f3b84f2011-11-01 10:31:26 +01001398 def dst(self, dt):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001399 # a fixed-offset class: doesn't account for DST
1400 return timedelta(0)
1401
1402 or ::
1403
Sandro Tosi1f3b84f2011-11-01 10:31:26 +01001404 def dst(self, dt):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001405 # Code to set dston and dstoff to the time zone's DST
1406 # transition times based on the input dt.year, and expressed
1407 # in standard local time. Then
1408
1409 if dston <= dt.replace(tzinfo=None) < dstoff:
1410 return timedelta(hours=1)
1411 else:
1412 return timedelta(0)
1413
1414 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1415
1416
1417.. method:: tzinfo.tzname(self, dt)
1418
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001419 Return the time zone name corresponding to the :class:`.datetime` object *dt*, as
Georg Brandl8ec7f652007-08-15 14:28:01 +00001420 a string. Nothing about string names is defined by the :mod:`datetime` module,
1421 and there's no requirement that it mean anything in particular. For example,
1422 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1423 valid replies. Return ``None`` if a string name isn't known. Note that this is
1424 a method rather than a fixed string primarily because some :class:`tzinfo`
1425 subclasses will wish to return different names depending on the specific value
1426 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1427 daylight time.
1428
1429 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1430
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001431
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001432These methods are called by a :class:`.datetime` or :class:`.time` object, in
1433response to their methods of the same names. A :class:`.datetime` object passes
1434itself as the argument, and a :class:`.time` object passes ``None`` as the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001435argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001436accept a *dt* argument of ``None``, or of class :class:`.datetime`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001437
1438When ``None`` is passed, it's up to the class designer to decide the best
1439response. For example, returning ``None`` is appropriate if the class wishes to
1440say that time objects don't participate in the :class:`tzinfo` protocols. It
1441may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1442there is no other convention for discovering the standard offset.
1443
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001444When a :class:`.datetime` object is passed in response to a :class:`.datetime`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001445method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1446rely on this, unless user code calls :class:`tzinfo` methods directly. The
1447intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1448time, and not need worry about objects in other timezones.
1449
1450There is one more :class:`tzinfo` method that a subclass may wish to override:
1451
1452
1453.. method:: tzinfo.fromutc(self, dt)
1454
Senthil Kumaran4c9721a2011-07-17 19:10:10 +08001455 This is called from the default :class:`datetime.astimezone()`
1456 implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s
1457 date and time data are to be viewed as expressing a UTC time. The purpose
1458 of :meth:`fromutc` is to adjust the date and time data, returning an
Senthil Kumaran6f18b982011-07-04 12:50:02 -07001459 equivalent datetime in *self*'s local time.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001460
1461 Most :class:`tzinfo` subclasses should be able to inherit the default
1462 :meth:`fromutc` implementation without problems. It's strong enough to handle
1463 fixed-offset time zones, and time zones accounting for both standard and
1464 daylight time, and the latter even if the DST transition times differ in
1465 different years. An example of a time zone the default :meth:`fromutc`
1466 implementation may not handle correctly in all cases is one where the standard
1467 offset (from UTC) depends on the specific date and time passed, which can happen
1468 for political reasons. The default implementations of :meth:`astimezone` and
1469 :meth:`fromutc` may not produce the result you want if the result is one of the
1470 hours straddling the moment the standard offset changes.
1471
1472 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1473 like::
1474
1475 def fromutc(self, dt):
1476 # raise ValueError error if dt.tzinfo is not self
1477 dtoff = dt.utcoffset()
1478 dtdst = dt.dst()
1479 # raise ValueError if dtoff is None or dtdst is None
1480 delta = dtoff - dtdst # this is self's standard offset
1481 if delta:
1482 dt += delta # convert to standard local time
1483 dtdst = dt.dst()
1484 # raise ValueError if dtdst is None
1485 if dtdst:
1486 return dt + dtdst
1487 else:
1488 return dt
1489
1490Example :class:`tzinfo` classes:
1491
1492.. literalinclude:: ../includes/tzinfo-examples.py
1493
1494
1495Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1496subclass accounting for both standard and daylight time, at the DST transition
1497points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandlce00cf22010-03-21 09:58:36 +00001498minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
14991:59 (EDT) on the first Sunday in November::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001500
1501 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1502 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1503 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1504
1505 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1506
1507 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1508
1509When DST starts (the "start" line), the local wall clock leaps from 1:59 to
15103:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1511``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1512begins. In order for :meth:`astimezone` to make this guarantee, the
1513:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1514Eastern) to be in daylight time.
1515
1516When DST ends (the "end" line), there's a potentially worse problem: there's an
1517hour that can't be spelled unambiguously in local wall time: the last hour of
1518daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1519daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1520to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1521:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1522hours into the same local hour then. In the Eastern example, UTC times of the
1523form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1524:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1525consider times in the "repeated hour" to be in standard time. This is easily
1526arranged, as in the example, by expressing DST switch times in the time zone's
1527standard local time.
1528
1529Applications that can't bear such ambiguities should avoid using hybrid
1530:class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any
1531other fixed-offset :class:`tzinfo` subclass (such as a class representing only
1532EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001533
Sandro Tosi13c598b2012-04-24 19:43:33 +02001534.. seealso::
1535
1536 `pytz <http://pypi.python.org/pypi/pytz/>`_
Sandro Tosiaa31d522012-04-28 11:19:11 +02001537 The standard library has no :class:`tzinfo` instances except for UTC, but
1538 there exists a third-party library which brings the *IANA timezone
1539 database* (also known as the Olson database) to Python: *pytz*.
Sandro Tosi13c598b2012-04-24 19:43:33 +02001540
Sandro Tosiaa31d522012-04-28 11:19:11 +02001541 *pytz* contains up-to-date information and its usage is recommended.
1542
1543 `IANA timezone database <http://www.iana.org/time-zones>`_
1544 The Time Zone Database (often called tz or zoneinfo) contains code and
1545 data that represent the history of local time for many representative
1546 locations around the globe. It is updated periodically to reflect changes
1547 made by political bodies to time zone boundaries, UTC offsets, and
1548 daylight-saving rules.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001549
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001550.. _strftime-strptime-behavior:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001551
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001552:meth:`strftime` and :meth:`strptime` Behavior
1553----------------------------------------------
Georg Brandl8ec7f652007-08-15 14:28:01 +00001554
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001555:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
Georg Brandl8ec7f652007-08-15 14:28:01 +00001556``strftime(format)`` method, to create a string representing the time under the
1557control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1558acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1559although not all objects support a :meth:`timetuple` method.
1560
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001561Conversely, the :meth:`datetime.strptime` class method creates a
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001562:class:`.datetime` object from a string representing a date and time and a
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001563corresponding format string. ``datetime.strptime(date_string, format)`` is
1564equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1565
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001566For :class:`.time` objects, the format codes for year, month, and day should not
Georg Brandl8ec7f652007-08-15 14:28:01 +00001567be used, as time objects have no such values. If they're used anyway, ``1900``
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001568is substituted for the year, and ``1`` for the month and day.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001569
Skip Montanarofc070d22008-03-15 16:04:45 +00001570For :class:`date` objects, the format codes for hours, minutes, seconds, and
1571microseconds should not be used, as :class:`date` objects have no such
1572values. If they're used anyway, ``0`` is substituted for them.
1573
Skip Montanarofc070d22008-03-15 16:04:45 +00001574.. versionadded:: 2.6
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001575 :class:`.time` and :class:`.datetime` objects support a ``%f`` format code
Georg Brandlaf9a97b2009-01-18 14:41:52 +00001576 which expands to the number of microseconds in the object, zero-padded on
1577 the left to six places.
Skip Montanarofc070d22008-03-15 16:04:45 +00001578
1579For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1580strings.
1581
1582For an aware object:
1583
1584``%z``
1585 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1586 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1587 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1588 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1589 replaced with the string ``'-0330'``.
1590
1591``%Z``
1592 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1593 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001594
Georg Brandl8ec7f652007-08-15 14:28:01 +00001595The full set of format codes supported varies across platforms, because Python
1596calls the platform C library's :func:`strftime` function, and platform
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001597variations are common.
Georg Brandle40a6a82007-12-08 11:23:13 +00001598
1599The following is a list of all the format codes that the C standard (1989
1600version) requires, and these work on all platforms with a standard C
1601implementation. Note that the 1999 version of the C standard added additional
1602format codes.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001603
1604The exact range of years for which :meth:`strftime` works also varies across
1605platforms. Regardless of platform, years before 1900 cannot be used.
1606
Georg Brandle40a6a82007-12-08 11:23:13 +00001607+-----------+--------------------------------+-------+
1608| Directive | Meaning | Notes |
1609+===========+================================+=======+
1610| ``%a`` | Locale's abbreviated weekday | |
1611| | name. | |
1612+-----------+--------------------------------+-------+
1613| ``%A`` | Locale's full weekday name. | |
1614+-----------+--------------------------------+-------+
1615| ``%b`` | Locale's abbreviated month | |
1616| | name. | |
1617+-----------+--------------------------------+-------+
1618| ``%B`` | Locale's full month name. | |
1619+-----------+--------------------------------+-------+
1620| ``%c`` | Locale's appropriate date and | |
1621| | time representation. | |
1622+-----------+--------------------------------+-------+
1623| ``%d`` | Day of the month as a decimal | |
1624| | number [01,31]. | |
1625+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001626| ``%f`` | Microsecond as a decimal | \(1) |
1627| | number [0,999999], zero-padded | |
1628| | on the left | |
1629+-----------+--------------------------------+-------+
Georg Brandle40a6a82007-12-08 11:23:13 +00001630| ``%H`` | Hour (24-hour clock) as a | |
1631| | decimal number [00,23]. | |
1632+-----------+--------------------------------+-------+
1633| ``%I`` | Hour (12-hour clock) as a | |
1634| | decimal number [01,12]. | |
1635+-----------+--------------------------------+-------+
1636| ``%j`` | Day of the year as a decimal | |
1637| | number [001,366]. | |
1638+-----------+--------------------------------+-------+
1639| ``%m`` | Month as a decimal number | |
1640| | [01,12]. | |
1641+-----------+--------------------------------+-------+
1642| ``%M`` | Minute as a decimal number | |
1643| | [00,59]. | |
1644+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001645| ``%p`` | Locale's equivalent of either | \(2) |
Georg Brandle40a6a82007-12-08 11:23:13 +00001646| | AM or PM. | |
1647+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001648| ``%S`` | Second as a decimal number | \(3) |
Georg Brandle40a6a82007-12-08 11:23:13 +00001649| | [00,61]. | |
1650+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001651| ``%U`` | Week number of the year | \(4) |
Georg Brandle40a6a82007-12-08 11:23:13 +00001652| | (Sunday as the first day of | |
1653| | the week) as a decimal number | |
1654| | [00,53]. All days in a new | |
1655| | year preceding the first | |
1656| | Sunday are considered to be in | |
1657| | week 0. | |
1658+-----------+--------------------------------+-------+
1659| ``%w`` | Weekday as a decimal number | |
1660| | [0(Sunday),6]. | |
1661+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001662| ``%W`` | Week number of the year | \(4) |
Georg Brandle40a6a82007-12-08 11:23:13 +00001663| | (Monday as the first day of | |
1664| | the week) as a decimal number | |
1665| | [00,53]. All days in a new | |
1666| | year preceding the first | |
1667| | Monday are considered to be in | |
1668| | week 0. | |
1669+-----------+--------------------------------+-------+
1670| ``%x`` | Locale's appropriate date | |
1671| | representation. | |
1672+-----------+--------------------------------+-------+
1673| ``%X`` | Locale's appropriate time | |
1674| | representation. | |
1675+-----------+--------------------------------+-------+
1676| ``%y`` | Year without century as a | |
1677| | decimal number [00,99]. | |
1678+-----------+--------------------------------+-------+
1679| ``%Y`` | Year with century as a decimal | |
1680| | number. | |
1681+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001682| ``%z`` | UTC offset in the form +HHMM | \(5) |
Georg Brandle40a6a82007-12-08 11:23:13 +00001683| | or -HHMM (empty string if the | |
1684| | the object is naive). | |
1685+-----------+--------------------------------+-------+
1686| ``%Z`` | Time zone name (empty string | |
1687| | if the object is naive). | |
1688+-----------+--------------------------------+-------+
1689| ``%%`` | A literal ``'%'`` character. | |
1690+-----------+--------------------------------+-------+
Georg Brandl8ec7f652007-08-15 14:28:01 +00001691
Georg Brandle40a6a82007-12-08 11:23:13 +00001692Notes:
1693
1694(1)
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001695 When used with the :meth:`strptime` method, the ``%f`` directive
Skip Montanarofc070d22008-03-15 16:04:45 +00001696 accepts from one to six digits and zero pads on the right. ``%f`` is
Georg Brandlaf9a97b2009-01-18 14:41:52 +00001697 an extension to the set of format characters in the C standard (but
1698 implemented separately in datetime objects, and therefore always
1699 available).
Skip Montanarofc070d22008-03-15 16:04:45 +00001700
1701(2)
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001702 When used with the :meth:`strptime` method, the ``%p`` directive only affects
Georg Brandle40a6a82007-12-08 11:23:13 +00001703 the output hour field if the ``%I`` directive is used to parse the hour.
1704
Skip Montanarofc070d22008-03-15 16:04:45 +00001705(3)
R. David Murrayd56bab42009-04-02 04:34:04 +00001706 The range really is ``0`` to ``61``; according to the Posix standard this
1707 accounts for leap seconds and the (very rare) double leap seconds.
1708 The :mod:`time` module may produce and does accept leap seconds since
1709 it is based on the Posix standard, but the :mod:`datetime` module
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001710 does not accept leap seconds in :meth:`strptime` input nor will it
R. David Murrayd56bab42009-04-02 04:34:04 +00001711 produce them in :func:`strftime` output.
Georg Brandle40a6a82007-12-08 11:23:13 +00001712
Skip Montanarofc070d22008-03-15 16:04:45 +00001713(4)
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001714 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in
Georg Brandle40a6a82007-12-08 11:23:13 +00001715 calculations when the day of the week and the year are specified.
1716
Skip Montanarofc070d22008-03-15 16:04:45 +00001717(5)
Georg Brandle40a6a82007-12-08 11:23:13 +00001718 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1719 ``%z`` is replaced with the string ``'-0330'``.
R David Murray089d4d42012-05-14 22:32:44 -04001720
1721
1722.. rubric:: Footnotes
1723
1724.. [#] If, that is, we ignore the effects of Relativity