blob: 7219cea64574ad57db67d7329b483dc051550e49 [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
Georg Brandle565cf82012-08-21 19:44:00 +020028A naive object does not contain enough information to unambiguously locate
29itself relative to other date/time objects. Whether a naive object represents
R David Murray8349bc22012-05-14 22:33:36 -040030Coordinated 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
Ezio Melotticfb63cd2013-04-04 09:16:15 +0300558.. method:: date.__format__(format)
559
560 Same as :meth:`.date.strftime`. This makes it possible to specify format
561 string for a :class:`.date` object when using :meth:`str.format`.
562 See section :ref:`strftime-strptime-behavior`.
563
564
Georg Brandle40a6a82007-12-08 11:23:13 +0000565Example of counting days to an event::
566
567 >>> import time
568 >>> from datetime import date
569 >>> today = date.today()
570 >>> today
571 datetime.date(2007, 12, 5)
572 >>> today == date.fromtimestamp(time.time())
573 True
574 >>> my_birthday = date(today.year, 6, 24)
575 >>> if my_birthday < today:
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000576 ... my_birthday = my_birthday.replace(year=today.year + 1)
Georg Brandle40a6a82007-12-08 11:23:13 +0000577 >>> my_birthday
578 datetime.date(2008, 6, 24)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000579 >>> time_to_birthday = abs(my_birthday - today)
Georg Brandle40a6a82007-12-08 11:23:13 +0000580 >>> time_to_birthday.days
581 202
582
Georg Brandl3f043032008-03-22 21:21:57 +0000583Example of working with :class:`date`:
584
585.. doctest::
Georg Brandle40a6a82007-12-08 11:23:13 +0000586
587 >>> from datetime import date
588 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
589 >>> d
590 datetime.date(2002, 3, 11)
591 >>> t = d.timetuple()
Georg Brandl3f043032008-03-22 21:21:57 +0000592 >>> for i in t: # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +0000593 ... print i
594 2002 # year
595 3 # month
596 11 # day
597 0
598 0
599 0
600 0 # weekday (0 = Monday)
601 70 # 70th day in the year
602 -1
603 >>> ic = d.isocalendar()
Georg Brandl3f043032008-03-22 21:21:57 +0000604 >>> for i in ic: # doctest: +SKIP
605 ... print i
Georg Brandle40a6a82007-12-08 11:23:13 +0000606 2002 # ISO year
607 11 # ISO week number
608 1 # ISO day number ( 1 = Monday )
609 >>> d.isoformat()
610 '2002-03-11'
611 >>> d.strftime("%d/%m/%y")
612 '11/03/02'
613 >>> d.strftime("%A %d. %B %Y")
614 'Monday 11. March 2002'
Ezio Melotticfb63cd2013-04-04 09:16:15 +0300615 >>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")
616 'The day is 11, the month is March.'
Georg Brandle40a6a82007-12-08 11:23:13 +0000617
Georg Brandl8ec7f652007-08-15 14:28:01 +0000618
619.. _datetime-datetime:
620
621:class:`datetime` Objects
622-------------------------
623
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100624A :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
Georg Brandl8ec7f652007-08-15 14:28:01 +00006283600\*24 seconds in every day.
629
630Constructor:
631
Georg Brandl8ec7f652007-08-15 14:28:01 +0000632.. class:: datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])
633
634 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
635 instance of a :class:`tzinfo` subclass. The remaining arguments may be ints or
636 longs, in the following ranges:
637
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
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000650.. classmethod:: datetime.today()
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000657.. classmethod:: datetime.now([tz])
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100663 :c:func:`gettimeofday` function).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000664
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
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000671.. classmethod:: datetime.utcnow()
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100675 :class:`.datetime` object. See also :meth:`now`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000676
677
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000678.. classmethod:: datetime.fromtimestamp(timestamp[, tz])
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100683 the returned :class:`.datetime` object is naive.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000684
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
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100691 the range of values supported by the platform C :c:func:`localtime` or
692 :c:func:`gmtime` functions. It's common for this to be restricted to years in
Georg Brandl8ec7f652007-08-15 14:28:01 +0000693 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
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100696 identical :class:`.datetime` objects. See also :meth:`utcfromtimestamp`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000697
698
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000699.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000700
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100701 Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with
Georg Brandl8ec7f652007-08-15 14:28:01 +0000702 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100703 out of the range of values supported by the platform C :c:func:`gmtime` function.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000704 It's common for this to be restricted to years in 1970 through 2038. See also
705 :meth:`fromtimestamp`.
706
707
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000708.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000709
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100710 Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000711 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
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000716.. classmethod:: datetime.combine(date, time)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000717
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100718 Return a new :class:`.datetime` object whose date components are equal to the
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800719 given :class:`date` object's, and whose time components and :attr:`tzinfo`
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100720 attributes are equal to the given :class:`.time` object's. For any
721 :class:`.datetime` object *d*,
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800722 ``d == datetime.combine(d.date(), d.timetz())``. If date is a
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100723 :class:`.datetime` object, its time components and :attr:`tzinfo` attributes
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800724 are ignored.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000725
726
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000727.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000728
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100729 Return a :class:`.datetime` corresponding to *date_string*, parsed according to
Georg Brandl8ec7f652007-08-15 14:28:01 +0000730 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
731 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
732 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 +0000733 time tuple. See section :ref:`strftime-strptime-behavior`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000734
735 .. versionadded:: 2.5
736
Georg Brandl8ec7f652007-08-15 14:28:01 +0000737
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000738Class attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000739
740.. attribute:: datetime.min
741
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100742 The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000743 tzinfo=None)``.
744
745
746.. attribute:: datetime.max
747
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100748 The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000749 59, 999999, tzinfo=None)``.
750
751
752.. attribute:: datetime.resolution
753
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100754 The smallest possible difference between non-equal :class:`.datetime` objects,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000755 ``timedelta(microseconds=1)``.
756
Georg Brandl8ec7f652007-08-15 14:28:01 +0000757
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000758Instance attributes (read-only):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000759
760.. attribute:: datetime.year
761
762 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
763
764
765.. attribute:: datetime.month
766
767 Between 1 and 12 inclusive.
768
769
770.. attribute:: datetime.day
771
772 Between 1 and the number of days in the given month of the given year.
773
774
775.. attribute:: datetime.hour
776
777 In ``range(24)``.
778
779
780.. attribute:: datetime.minute
781
782 In ``range(60)``.
783
784
785.. attribute:: datetime.second
786
787 In ``range(60)``.
788
789
790.. attribute:: datetime.microsecond
791
792 In ``range(1000000)``.
793
794
795.. attribute:: datetime.tzinfo
796
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100797 The object passed as the *tzinfo* argument to the :class:`.datetime` constructor,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000798 or ``None`` if none was passed.
799
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000800
Georg Brandl8ec7f652007-08-15 14:28:01 +0000801Supported operations:
802
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100803+---------------------------------------+--------------------------------+
804| Operation | Result |
805+=======================================+================================+
806| ``datetime2 = datetime1 + timedelta`` | \(1) |
807+---------------------------------------+--------------------------------+
808| ``datetime2 = datetime1 - timedelta`` | \(2) |
809+---------------------------------------+--------------------------------+
810| ``timedelta = datetime1 - datetime2`` | \(3) |
811+---------------------------------------+--------------------------------+
812| ``datetime1 < datetime2`` | Compares :class:`.datetime` to |
813| | :class:`.datetime`. (4) |
814+---------------------------------------+--------------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000815
816(1)
817 datetime2 is a duration of timedelta removed from datetime1, moving forward in
818 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700819 result has the same :attr:`tzinfo` attribute as the input datetime, and
820 datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
821 datetime2.year would be smaller than :const:`MINYEAR` or larger than
822 :const:`MAXYEAR`. Note that no time zone adjustments are done even if the
823 input is an aware object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000824
825(2)
826 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700827 addition, the result has the same :attr:`tzinfo` attribute as the input
828 datetime, and no time zone adjustments are done even if the input is aware.
829 This isn't quite equivalent to datetime1 + (-timedelta), because -timedelta
830 in isolation can overflow in cases where datetime1 - timedelta does not.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000831
832(3)
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100833 Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if
Georg Brandl8ec7f652007-08-15 14:28:01 +0000834 both operands are naive, or if both are aware. If one is aware and the other is
835 naive, :exc:`TypeError` is raised.
836
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700837 If both are naive, or both are aware and have the same :attr:`tzinfo` attribute,
838 the :attr:`tzinfo` attributes are ignored, and the result is a :class:`timedelta`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000839 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
840 are done in this case.
841
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700842 If both are aware and have different :attr:`tzinfo` attributes, ``a-b`` acts
843 as if *a* and *b* were first converted to naive UTC datetimes first. The
844 result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
845 - b.utcoffset())`` except that the implementation never overflows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000846
847(4)
848 *datetime1* is considered less than *datetime2* when *datetime1* precedes
849 *datetime2* in time.
850
851 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700852 If both comparands are aware, and have the same :attr:`tzinfo` attribute, the
853 common :attr:`tzinfo` attribute is ignored and the base datetimes are
854 compared. If both comparands are aware and have different :attr:`tzinfo`
855 attributes, the comparands are first adjusted by subtracting their UTC
856 offsets (obtained from ``self.utcoffset()``).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000857
858 .. note::
859
860 In order to stop comparison from falling back to the default scheme of comparing
861 object addresses, datetime comparison normally raises :exc:`TypeError` if the
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100862 other comparand isn't also a :class:`.datetime` object. However,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000863 ``NotImplemented`` is returned instead if the other comparand has a
864 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100865 chance at implementing mixed-type comparison. If not, when a :class:`.datetime`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000866 object is compared to an object of a different type, :exc:`TypeError` is raised
867 unless the comparison is ``==`` or ``!=``. The latter cases return
868 :const:`False` or :const:`True`, respectively.
869
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100870:class:`.datetime` objects can be used as dictionary keys. In Boolean contexts,
871all :class:`.datetime` objects are considered to be true.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000872
873Instance methods:
874
Georg Brandl8ec7f652007-08-15 14:28:01 +0000875.. method:: datetime.date()
876
877 Return :class:`date` object with same year, month and day.
878
879
880.. method:: datetime.time()
881
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100882 Return :class:`.time` object with same hour, minute, second and microsecond.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000883 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
884
885
886.. method:: datetime.timetz()
887
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100888 Return :class:`.time` object with same hour, minute, second, microsecond, and
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700889 tzinfo attributes. See also method :meth:`time`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000890
891
892.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
893
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700894 Return a datetime with the same attributes, except for those attributes given
895 new values by whichever keyword arguments are specified. Note that
896 ``tzinfo=None`` can be specified to create a naive datetime from an aware
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800897 datetime with no conversion of date and time data.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000898
899
900.. method:: datetime.astimezone(tz)
901
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100902 Return a :class:`.datetime` object with new :attr:`tzinfo` attribute *tz*,
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800903 adjusting the date and time data so the result is the same UTC time as
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700904 *self*, but in *tz*'s local time.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000905
906 *tz* must be an instance of a :class:`tzinfo` subclass, and its
907 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
908 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
909 not return ``None``).
910
911 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800912 adjustment of date or time data is performed. Else the result is local
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700913 time in time zone *tz*, representing the same UTC time as *self*: after
914 ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800915 the same date and time data as ``dt - dt.utcoffset()``. The discussion
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700916 of class :class:`tzinfo` explains the cases at Daylight Saving Time transition
917 boundaries where this cannot be achieved (an issue only if *tz* models both
918 standard and daylight time).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000919
920 If you merely want to attach a time zone object *tz* to a datetime *dt* without
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800921 adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you
Georg Brandl8ec7f652007-08-15 14:28:01 +0000922 merely want to remove the time zone object from an aware datetime *dt* without
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800923 conversion of date and time data, use ``dt.replace(tzinfo=None)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000924
925 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
926 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
927 Ignoring error cases, :meth:`astimezone` acts like::
928
929 def astimezone(self, tz):
930 if self.tzinfo is tz:
931 return self
932 # Convert self to UTC, and attach the new time zone object.
933 utc = (self - self.utcoffset()).replace(tzinfo=tz)
934 # Convert from UTC to tz's local time.
935 return tz.fromutc(utc)
936
937
938.. method:: datetime.utcoffset()
939
940 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
941 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
942 return ``None``, or a :class:`timedelta` object representing a whole number of
943 minutes with magnitude less than one day.
944
945
946.. method:: datetime.dst()
947
948 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
949 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
950 ``None``, or a :class:`timedelta` object representing a whole number of minutes
951 with magnitude less than one day.
952
953
954.. method:: datetime.tzname()
955
956 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
957 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
958 ``None`` or a string object,
959
960
961.. method:: datetime.timetuple()
962
963 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
964 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
Georg Brandl151973e2010-05-23 21:29:29 +0000965 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
966 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
967 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
968 of the result is set according to the :meth:`dst` method: :attr:`tzinfo` is
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000969 ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
Georg Brandl151973e2010-05-23 21:29:29 +0000970 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
Alexander Belopolsky094c53c2010-06-09 17:08:11 +0000971 else :attr:`tm_isdst` is set to ``0``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000972
973
974.. method:: datetime.utctimetuple()
975
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100976 If :class:`.datetime` instance *d* is naive, this is the same as
Georg Brandl8ec7f652007-08-15 14:28:01 +0000977 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
978 ``d.dst()`` returns. DST is never in effect for a UTC time.
979
980 If *d* is aware, *d* is normalized to UTC time, by subtracting
981 ``d.utcoffset()``, and a :class:`time.struct_time` for the normalized time is
982 returned. :attr:`tm_isdst` is forced to 0. Note that the result's
983 :attr:`tm_year` member may be :const:`MINYEAR`\ -1 or :const:`MAXYEAR`\ +1, if
984 *d*.year was ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
985 boundary.
986
987
988.. method:: datetime.toordinal()
989
990 Return the proleptic Gregorian ordinal of the date. The same as
991 ``self.date().toordinal()``.
992
993
994.. method:: datetime.weekday()
995
996 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
997 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
998
999
1000.. method:: datetime.isoweekday()
1001
1002 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
1003 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
1004 :meth:`isocalendar`.
1005
1006
1007.. method:: datetime.isocalendar()
1008
1009 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
1010 ``self.date().isocalendar()``.
1011
1012
1013.. method:: datetime.isoformat([sep])
1014
1015 Return a string representing the date and time in ISO 8601 format,
1016 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
1017 YYYY-MM-DDTHH:MM:SS
1018
1019 If :meth:`utcoffset` does not return ``None``, a 6-character string is
1020 appended, giving the UTC offset in (signed) hours and minutes:
1021 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
1022 YYYY-MM-DDTHH:MM:SS+HH:MM
1023
1024 The optional argument *sep* (default ``'T'``) is a one-character separator,
Georg Brandl3f043032008-03-22 21:21:57 +00001025 placed between the date and time portions of the result. For example,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001026
1027 >>> from datetime import tzinfo, timedelta, datetime
1028 >>> class TZ(tzinfo):
1029 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1030 ...
1031 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1032 '2002-12-25 00:00:00-06:39'
1033
1034
1035.. method:: datetime.__str__()
1036
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001037 For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to
Georg Brandl8ec7f652007-08-15 14:28:01 +00001038 ``d.isoformat(' ')``.
1039
1040
1041.. method:: datetime.ctime()
1042
1043 Return a string representing the date and time, for example ``datetime(2002, 12,
1044 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1045 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
Sandro Tosi98ed08f2012-01-14 16:42:02 +01001046 native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl8ec7f652007-08-15 14:28:01 +00001047 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1048
1049
1050.. method:: datetime.strftime(format)
1051
1052 Return a string representing the date and time, controlled by an explicit format
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001053 string. See section :ref:`strftime-strptime-behavior`.
1054
Georg Brandl8ec7f652007-08-15 14:28:01 +00001055
Ezio Melotticfb63cd2013-04-04 09:16:15 +03001056.. method:: datetime.__format__(format)
1057
1058 Same as :meth:`.datetime.strftime`. This makes it possible to specify format
1059 string for a :class:`.datetime` object when using :meth:`str.format`.
1060 See section :ref:`strftime-strptime-behavior`.
1061
1062
Georg Brandl3f043032008-03-22 21:21:57 +00001063Examples of working with datetime objects:
1064
1065.. doctest::
1066
Georg Brandle40a6a82007-12-08 11:23:13 +00001067 >>> from datetime import datetime, date, time
1068 >>> # Using datetime.combine()
1069 >>> d = date(2005, 7, 14)
1070 >>> t = time(12, 30)
1071 >>> datetime.combine(d, t)
1072 datetime.datetime(2005, 7, 14, 12, 30)
1073 >>> # Using datetime.now() or datetime.utcnow()
Georg Brandl3f043032008-03-22 21:21:57 +00001074 >>> datetime.now() # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +00001075 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Georg Brandl3f043032008-03-22 21:21:57 +00001076 >>> datetime.utcnow() # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +00001077 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1078 >>> # Using datetime.strptime()
1079 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1080 >>> dt
1081 datetime.datetime(2006, 11, 21, 16, 30)
1082 >>> # Using datetime.timetuple() to get tuple of all attributes
1083 >>> tt = dt.timetuple()
Georg Brandl3f043032008-03-22 21:21:57 +00001084 >>> for it in tt: # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +00001085 ... print it
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001086 ...
Georg Brandle40a6a82007-12-08 11:23:13 +00001087 2006 # year
1088 11 # month
1089 21 # day
1090 16 # hour
1091 30 # minute
1092 0 # second
1093 1 # weekday (0 = Monday)
1094 325 # number of days since 1st January
1095 -1 # dst - method tzinfo.dst() returned None
1096 >>> # Date in ISO format
1097 >>> ic = dt.isocalendar()
Georg Brandl3f043032008-03-22 21:21:57 +00001098 >>> for it in ic: # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +00001099 ... print it
1100 ...
1101 2006 # ISO year
1102 47 # ISO week
1103 2 # ISO weekday
1104 >>> # Formatting datetime
1105 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1106 'Tuesday, 21. November 2006 04:30PM'
Ezio Melotticfb63cd2013-04-04 09:16:15 +03001107 >>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
1108 'The day is 21, the month is November, the time is 04:30PM.'
Georg Brandle40a6a82007-12-08 11:23:13 +00001109
Georg Brandl3f043032008-03-22 21:21:57 +00001110Using datetime with tzinfo:
Georg Brandle40a6a82007-12-08 11:23:13 +00001111
1112 >>> from datetime import timedelta, datetime, tzinfo
1113 >>> class GMT1(tzinfo):
Senthil Kumaran189bd912012-06-26 20:05:12 +08001114 ... def utcoffset(self, dt):
1115 ... return timedelta(hours=1) + self.dst(dt)
1116 ... def dst(self, dt):
1117 ... # DST starts last Sunday in March
Georg Brandle40a6a82007-12-08 11:23:13 +00001118 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1119 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001120 ... d = datetime(dt.year, 11, 1)
Georg Brandle40a6a82007-12-08 11:23:13 +00001121 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
Georg Brandle40a6a82007-12-08 11:23:13 +00001122 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1123 ... return timedelta(hours=1)
1124 ... else:
1125 ... return timedelta(0)
1126 ... def tzname(self,dt):
1127 ... return "GMT +1"
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001128 ...
Georg Brandle40a6a82007-12-08 11:23:13 +00001129 >>> class GMT2(tzinfo):
Senthil Kumaran189bd912012-06-26 20:05:12 +08001130 ... def utcoffset(self, dt):
1131 ... return timedelta(hours=2) + self.dst(dt)
1132 ... def dst(self, dt):
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001133 ... d = datetime(dt.year, 4, 1)
Georg Brandle40a6a82007-12-08 11:23:13 +00001134 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001135 ... d = datetime(dt.year, 11, 1)
Georg Brandle40a6a82007-12-08 11:23:13 +00001136 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
Georg Brandle40a6a82007-12-08 11:23:13 +00001137 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
Senthil Kumaran189bd912012-06-26 20:05:12 +08001138 ... return timedelta(hours=1)
Georg Brandle40a6a82007-12-08 11:23:13 +00001139 ... else:
1140 ... return timedelta(0)
1141 ... def tzname(self,dt):
1142 ... return "GMT +2"
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001143 ...
Georg Brandle40a6a82007-12-08 11:23:13 +00001144 >>> gmt1 = GMT1()
1145 >>> # Daylight Saving Time
1146 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1147 >>> dt1.dst()
1148 datetime.timedelta(0)
1149 >>> dt1.utcoffset()
1150 datetime.timedelta(0, 3600)
1151 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1152 >>> dt2.dst()
1153 datetime.timedelta(0, 3600)
1154 >>> dt2.utcoffset()
1155 datetime.timedelta(0, 7200)
1156 >>> # Convert datetime to another time zone
1157 >>> dt3 = dt2.astimezone(GMT2())
1158 >>> dt3 # doctest: +ELLIPSIS
1159 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1160 >>> dt2 # doctest: +ELLIPSIS
1161 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1162 >>> dt2.utctimetuple() == dt3.utctimetuple()
1163 True
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001164
Georg Brandle40a6a82007-12-08 11:23:13 +00001165
Georg Brandl8ec7f652007-08-15 14:28:01 +00001166
1167.. _datetime-time:
1168
1169:class:`time` Objects
1170---------------------
1171
1172A time object represents a (local) time of day, independent of any particular
1173day, and subject to adjustment via a :class:`tzinfo` object.
1174
Andrew Svetlov766849b2012-12-06 16:32:37 +02001175.. class:: time([hour[, minute[, second[, microsecond[, tzinfo]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001176
1177 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
1178 :class:`tzinfo` subclass. The remaining arguments may be ints or longs, in the
1179 following ranges:
1180
1181 * ``0 <= hour < 24``
1182 * ``0 <= minute < 60``
1183 * ``0 <= second < 60``
1184 * ``0 <= microsecond < 1000000``.
1185
1186 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1187 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1188
1189Class attributes:
1190
1191
1192.. attribute:: time.min
1193
Ezio Melottif17e4052011-10-02 12:22:13 +03001194 The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001195
1196
1197.. attribute:: time.max
1198
Ezio Melottif17e4052011-10-02 12:22:13 +03001199 The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001200
1201
1202.. attribute:: time.resolution
1203
Ezio Melottif17e4052011-10-02 12:22:13 +03001204 The smallest possible difference between non-equal :class:`.time` objects,
1205 ``timedelta(microseconds=1)``, although note that arithmetic on
1206 :class:`.time` objects is not supported.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001207
Georg Brandl8ec7f652007-08-15 14:28:01 +00001208
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001209Instance attributes (read-only):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001210
1211.. attribute:: time.hour
1212
1213 In ``range(24)``.
1214
1215
1216.. attribute:: time.minute
1217
1218 In ``range(60)``.
1219
1220
1221.. attribute:: time.second
1222
1223 In ``range(60)``.
1224
1225
1226.. attribute:: time.microsecond
1227
1228 In ``range(1000000)``.
1229
1230
1231.. attribute:: time.tzinfo
1232
Ezio Melottif17e4052011-10-02 12:22:13 +03001233 The object passed as the tzinfo argument to the :class:`.time` constructor, or
Georg Brandl8ec7f652007-08-15 14:28:01 +00001234 ``None`` if none was passed.
1235
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001236
Georg Brandl8ec7f652007-08-15 14:28:01 +00001237Supported operations:
1238
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001239* comparison of :class:`.time` to :class:`.time`, where *a* is considered less
Georg Brandl8ec7f652007-08-15 14:28:01 +00001240 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1241 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
Senthil Kumaran6f18b982011-07-04 12:50:02 -07001242 the same :attr:`tzinfo` attribute, the common :attr:`tzinfo` attribute is
1243 ignored and the base times are compared. If both comparands are aware and
1244 have different :attr:`tzinfo` attributes, the comparands are first adjusted by
1245 subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
1246 to stop mixed-type comparisons from falling back to the default comparison by
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001247 object address, when a :class:`.time` object is compared to an object of a
Senthil Kumaran6f18b982011-07-04 12:50:02 -07001248 different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
1249 ``!=``. The latter cases return :const:`False` or :const:`True`, respectively.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001250
1251* hash, use as dict key
1252
1253* efficient pickling
1254
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001255* in Boolean contexts, a :class:`.time` object is considered to be true if and
Georg Brandl8ec7f652007-08-15 14:28:01 +00001256 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1257 ``0`` if that's ``None``), the result is non-zero.
1258
Georg Brandl8ec7f652007-08-15 14:28:01 +00001259
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001260Instance methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001261
1262.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1263
Ezio Melottif17e4052011-10-02 12:22:13 +03001264 Return a :class:`.time` with the same value, except for those attributes given
Senthil Kumaran6f18b982011-07-04 12:50:02 -07001265 new values by whichever keyword arguments are specified. Note that
Ezio Melottif17e4052011-10-02 12:22:13 +03001266 ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
1267 aware :class:`.time`, without conversion of the time data.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001268
1269
1270.. method:: time.isoformat()
1271
1272 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1273 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1274 6-character string is appended, giving the UTC offset in (signed) hours and
1275 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1276
1277
1278.. method:: time.__str__()
1279
1280 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1281
1282
1283.. method:: time.strftime(format)
1284
1285 Return a string representing the time, controlled by an explicit format string.
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001286 See section :ref:`strftime-strptime-behavior`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001287
1288
Ezio Melotticfb63cd2013-04-04 09:16:15 +03001289.. method:: time.__format__(format)
1290
1291 Same as :meth:`.time.strftime`. This makes it possible to specify format string
1292 for a :class:`.time` object when using :meth:`str.format`.
1293 See section :ref:`strftime-strptime-behavior`.
1294
1295
Georg Brandl8ec7f652007-08-15 14:28:01 +00001296.. method:: time.utcoffset()
1297
1298 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1299 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1300 return ``None`` or a :class:`timedelta` object representing a whole number of
1301 minutes with magnitude less than one day.
1302
1303
1304.. method:: time.dst()
1305
1306 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1307 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1308 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1309 with magnitude less than one day.
1310
1311
1312.. method:: time.tzname()
1313
1314 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1315 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1316 return ``None`` or a string object.
1317
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001318
Georg Brandl3f043032008-03-22 21:21:57 +00001319Example:
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001320
Georg Brandle40a6a82007-12-08 11:23:13 +00001321 >>> from datetime import time, tzinfo
1322 >>> class GMT1(tzinfo):
1323 ... def utcoffset(self, dt):
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001324 ... return timedelta(hours=1)
1325 ... def dst(self, dt):
Georg Brandle40a6a82007-12-08 11:23:13 +00001326 ... return timedelta(0)
1327 ... def tzname(self,dt):
1328 ... return "Europe/Prague"
1329 ...
1330 >>> t = time(12, 10, 30, tzinfo=GMT1())
1331 >>> t # doctest: +ELLIPSIS
1332 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1333 >>> gmt = GMT1()
1334 >>> t.isoformat()
1335 '12:10:30+01:00'
1336 >>> t.dst()
1337 datetime.timedelta(0)
1338 >>> t.tzname()
1339 'Europe/Prague'
1340 >>> t.strftime("%H:%M:%S %Z")
1341 '12:10:30 Europe/Prague'
Ezio Melotticfb63cd2013-04-04 09:16:15 +03001342 >>> 'The {} is {:%H:%M}.'.format("time", t)
1343 'The time is 12:10.'
Georg Brandle40a6a82007-12-08 11:23:13 +00001344
Georg Brandl8ec7f652007-08-15 14:28:01 +00001345
1346.. _datetime-tzinfo:
1347
1348:class:`tzinfo` Objects
1349-----------------------
1350
Brett Cannon8aa2c6c2009-01-29 00:54:32 +00001351:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl8ec7f652007-08-15 14:28:01 +00001352instantiated directly. You need to derive a concrete subclass, and (at least)
1353supply implementations of the standard :class:`tzinfo` methods needed by the
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001354:class:`.datetime` methods you use. The :mod:`datetime` module does not supply
Georg Brandl8ec7f652007-08-15 14:28:01 +00001355any concrete subclasses of :class:`tzinfo`.
1356
1357An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001358constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
Senthil Kumaran6f18b982011-07-04 12:50:02 -07001359view their attributes as being in local time, and the :class:`tzinfo` object
Georg Brandl8ec7f652007-08-15 14:28:01 +00001360supports methods revealing offset of local time from UTC, the name of the time
1361zone, and DST offset, all relative to a date or time object passed to them.
1362
1363Special requirement for pickling: A :class:`tzinfo` subclass must have an
1364:meth:`__init__` method that can be called with no arguments, else it can be
1365pickled but possibly not unpickled again. This is a technical requirement that
1366may be relaxed in the future.
1367
1368A concrete subclass of :class:`tzinfo` may need to implement the following
1369methods. Exactly which methods are needed depends on the uses made of aware
1370:mod:`datetime` objects. If in doubt, simply implement all of them.
1371
1372
1373.. method:: tzinfo.utcoffset(self, dt)
1374
1375 Return offset of local time from UTC, in minutes east of UTC. If local time is
1376 west of UTC, this should be negative. Note that this is intended to be the
1377 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1378 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1379 the UTC offset isn't known, return ``None``. Else the value returned must be a
1380 :class:`timedelta` object specifying a whole number of minutes in the range
1381 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1382 than one day). Most implementations of :meth:`utcoffset` will probably look
1383 like one of these two::
1384
1385 return CONSTANT # fixed-offset class
1386 return CONSTANT + self.dst(dt) # daylight-aware class
1387
1388 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1389 ``None`` either.
1390
1391 The default implementation of :meth:`utcoffset` raises
1392 :exc:`NotImplementedError`.
1393
1394
1395.. method:: tzinfo.dst(self, dt)
1396
1397 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1398 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1399 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1400 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1401 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1402 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1403 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
Senthil Kumaran6f18b982011-07-04 12:50:02 -07001404 attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
1405 should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
1406 DST changes when crossing time zones.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001407
1408 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1409 daylight times must be consistent in this sense:
1410
1411 ``tz.utcoffset(dt) - tz.dst(dt)``
1412
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001413 must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo ==
Georg Brandl8ec7f652007-08-15 14:28:01 +00001414 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1415 zone's "standard offset", which should not depend on the date or the time, but
1416 only on geographic location. The implementation of :meth:`datetime.astimezone`
1417 relies on this, but cannot detect violations; it's the programmer's
1418 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1419 this, it may be able to override the default implementation of
1420 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1421
1422 Most implementations of :meth:`dst` will probably look like one of these two::
1423
Sandro Tosi1f3b84f2011-11-01 10:31:26 +01001424 def dst(self, dt):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001425 # a fixed-offset class: doesn't account for DST
1426 return timedelta(0)
1427
1428 or ::
1429
Sandro Tosi1f3b84f2011-11-01 10:31:26 +01001430 def dst(self, dt):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001431 # Code to set dston and dstoff to the time zone's DST
1432 # transition times based on the input dt.year, and expressed
1433 # in standard local time. Then
1434
1435 if dston <= dt.replace(tzinfo=None) < dstoff:
1436 return timedelta(hours=1)
1437 else:
1438 return timedelta(0)
1439
1440 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1441
1442
1443.. method:: tzinfo.tzname(self, dt)
1444
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001445 Return the time zone name corresponding to the :class:`.datetime` object *dt*, as
Georg Brandl8ec7f652007-08-15 14:28:01 +00001446 a string. Nothing about string names is defined by the :mod:`datetime` module,
1447 and there's no requirement that it mean anything in particular. For example,
1448 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1449 valid replies. Return ``None`` if a string name isn't known. Note that this is
1450 a method rather than a fixed string primarily because some :class:`tzinfo`
1451 subclasses will wish to return different names depending on the specific value
1452 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1453 daylight time.
1454
1455 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1456
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001457
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001458These methods are called by a :class:`.datetime` or :class:`.time` object, in
1459response to their methods of the same names. A :class:`.datetime` object passes
1460itself as the argument, and a :class:`.time` object passes ``None`` as the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001461argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001462accept a *dt* argument of ``None``, or of class :class:`.datetime`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001463
1464When ``None`` is passed, it's up to the class designer to decide the best
1465response. For example, returning ``None`` is appropriate if the class wishes to
1466say that time objects don't participate in the :class:`tzinfo` protocols. It
1467may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1468there is no other convention for discovering the standard offset.
1469
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001470When a :class:`.datetime` object is passed in response to a :class:`.datetime`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001471method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1472rely on this, unless user code calls :class:`tzinfo` methods directly. The
1473intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1474time, and not need worry about objects in other timezones.
1475
1476There is one more :class:`tzinfo` method that a subclass may wish to override:
1477
1478
1479.. method:: tzinfo.fromutc(self, dt)
1480
Senthil Kumaran4c9721a2011-07-17 19:10:10 +08001481 This is called from the default :class:`datetime.astimezone()`
1482 implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s
1483 date and time data are to be viewed as expressing a UTC time. The purpose
1484 of :meth:`fromutc` is to adjust the date and time data, returning an
Senthil Kumaran6f18b982011-07-04 12:50:02 -07001485 equivalent datetime in *self*'s local time.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001486
1487 Most :class:`tzinfo` subclasses should be able to inherit the default
1488 :meth:`fromutc` implementation without problems. It's strong enough to handle
1489 fixed-offset time zones, and time zones accounting for both standard and
1490 daylight time, and the latter even if the DST transition times differ in
1491 different years. An example of a time zone the default :meth:`fromutc`
1492 implementation may not handle correctly in all cases is one where the standard
1493 offset (from UTC) depends on the specific date and time passed, which can happen
1494 for political reasons. The default implementations of :meth:`astimezone` and
1495 :meth:`fromutc` may not produce the result you want if the result is one of the
1496 hours straddling the moment the standard offset changes.
1497
1498 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1499 like::
1500
1501 def fromutc(self, dt):
1502 # raise ValueError error if dt.tzinfo is not self
1503 dtoff = dt.utcoffset()
1504 dtdst = dt.dst()
1505 # raise ValueError if dtoff is None or dtdst is None
1506 delta = dtoff - dtdst # this is self's standard offset
1507 if delta:
1508 dt += delta # convert to standard local time
1509 dtdst = dt.dst()
1510 # raise ValueError if dtdst is None
1511 if dtdst:
1512 return dt + dtdst
1513 else:
1514 return dt
1515
1516Example :class:`tzinfo` classes:
1517
1518.. literalinclude:: ../includes/tzinfo-examples.py
1519
1520
1521Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1522subclass accounting for both standard and daylight time, at the DST transition
1523points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandlce00cf22010-03-21 09:58:36 +00001524minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
15251:59 (EDT) on the first Sunday in November::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001526
1527 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1528 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1529 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1530
1531 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1532
1533 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1534
1535When DST starts (the "start" line), the local wall clock leaps from 1:59 to
15363:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1537``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1538begins. In order for :meth:`astimezone` to make this guarantee, the
1539:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1540Eastern) to be in daylight time.
1541
1542When DST ends (the "end" line), there's a potentially worse problem: there's an
1543hour that can't be spelled unambiguously in local wall time: the last hour of
1544daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1545daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1546to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1547:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1548hours into the same local hour then. In the Eastern example, UTC times of the
1549form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1550:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1551consider times in the "repeated hour" to be in standard time. This is easily
1552arranged, as in the example, by expressing DST switch times in the time zone's
1553standard local time.
1554
1555Applications that can't bear such ambiguities should avoid using hybrid
1556:class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any
1557other fixed-offset :class:`tzinfo` subclass (such as a class representing only
1558EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001559
Sandro Tosi13c598b2012-04-24 19:43:33 +02001560.. seealso::
1561
1562 `pytz <http://pypi.python.org/pypi/pytz/>`_
Jason R. Coombs86af5812013-01-18 15:33:39 -05001563 The standard library has no :class:`tzinfo` instances, but
Sandro Tosiaa31d522012-04-28 11:19:11 +02001564 there exists a third-party library which brings the *IANA timezone
1565 database* (also known as the Olson database) to Python: *pytz*.
Sandro Tosi13c598b2012-04-24 19:43:33 +02001566
Sandro Tosiaa31d522012-04-28 11:19:11 +02001567 *pytz* contains up-to-date information and its usage is recommended.
1568
1569 `IANA timezone database <http://www.iana.org/time-zones>`_
1570 The Time Zone Database (often called tz or zoneinfo) contains code and
1571 data that represent the history of local time for many representative
1572 locations around the globe. It is updated periodically to reflect changes
1573 made by political bodies to time zone boundaries, UTC offsets, and
1574 daylight-saving rules.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001575
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001576.. _strftime-strptime-behavior:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001577
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001578:meth:`strftime` and :meth:`strptime` Behavior
1579----------------------------------------------
Georg Brandl8ec7f652007-08-15 14:28:01 +00001580
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001581:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
Georg Brandl8ec7f652007-08-15 14:28:01 +00001582``strftime(format)`` method, to create a string representing the time under the
1583control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1584acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1585although not all objects support a :meth:`timetuple` method.
1586
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001587Conversely, the :meth:`datetime.strptime` class method creates a
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001588:class:`.datetime` object from a string representing a date and time and a
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001589corresponding format string. ``datetime.strptime(date_string, format)`` is
1590equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1591
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001592For :class:`.time` objects, the format codes for year, month, and day should not
Georg Brandl8ec7f652007-08-15 14:28:01 +00001593be used, as time objects have no such values. If they're used anyway, ``1900``
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001594is substituted for the year, and ``1`` for the month and day.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001595
Skip Montanarofc070d22008-03-15 16:04:45 +00001596For :class:`date` objects, the format codes for hours, minutes, seconds, and
1597microseconds should not be used, as :class:`date` objects have no such
1598values. If they're used anyway, ``0`` is substituted for them.
1599
Skip Montanarofc070d22008-03-15 16:04:45 +00001600.. versionadded:: 2.6
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001601 :class:`.time` and :class:`.datetime` objects support a ``%f`` format code
Georg Brandlaf9a97b2009-01-18 14:41:52 +00001602 which expands to the number of microseconds in the object, zero-padded on
1603 the left to six places.
Skip Montanarofc070d22008-03-15 16:04:45 +00001604
1605For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1606strings.
1607
1608For an aware object:
1609
1610``%z``
1611 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1612 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1613 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1614 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1615 replaced with the string ``'-0330'``.
1616
1617``%Z``
1618 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1619 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001620
Georg Brandl8ec7f652007-08-15 14:28:01 +00001621The full set of format codes supported varies across platforms, because Python
1622calls the platform C library's :func:`strftime` function, and platform
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001623variations are common.
Georg Brandle40a6a82007-12-08 11:23:13 +00001624
1625The following is a list of all the format codes that the C standard (1989
1626version) requires, and these work on all platforms with a standard C
1627implementation. Note that the 1999 version of the C standard added additional
1628format codes.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001629
1630The exact range of years for which :meth:`strftime` works also varies across
1631platforms. Regardless of platform, years before 1900 cannot be used.
1632
Georg Brandle40a6a82007-12-08 11:23:13 +00001633+-----------+--------------------------------+-------+
1634| Directive | Meaning | Notes |
1635+===========+================================+=======+
1636| ``%a`` | Locale's abbreviated weekday | |
1637| | name. | |
1638+-----------+--------------------------------+-------+
1639| ``%A`` | Locale's full weekday name. | |
1640+-----------+--------------------------------+-------+
1641| ``%b`` | Locale's abbreviated month | |
1642| | name. | |
1643+-----------+--------------------------------+-------+
1644| ``%B`` | Locale's full month name. | |
1645+-----------+--------------------------------+-------+
1646| ``%c`` | Locale's appropriate date and | |
1647| | time representation. | |
1648+-----------+--------------------------------+-------+
1649| ``%d`` | Day of the month as a decimal | |
1650| | number [01,31]. | |
1651+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001652| ``%f`` | Microsecond as a decimal | \(1) |
1653| | number [0,999999], zero-padded | |
1654| | on the left | |
1655+-----------+--------------------------------+-------+
Georg Brandle40a6a82007-12-08 11:23:13 +00001656| ``%H`` | Hour (24-hour clock) as a | |
1657| | decimal number [00,23]. | |
1658+-----------+--------------------------------+-------+
1659| ``%I`` | Hour (12-hour clock) as a | |
1660| | decimal number [01,12]. | |
1661+-----------+--------------------------------+-------+
1662| ``%j`` | Day of the year as a decimal | |
1663| | number [001,366]. | |
1664+-----------+--------------------------------+-------+
1665| ``%m`` | Month as a decimal number | |
1666| | [01,12]. | |
1667+-----------+--------------------------------+-------+
1668| ``%M`` | Minute as a decimal number | |
1669| | [00,59]. | |
1670+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001671| ``%p`` | Locale's equivalent of either | \(2) |
Georg Brandle40a6a82007-12-08 11:23:13 +00001672| | AM or PM. | |
1673+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001674| ``%S`` | Second as a decimal number | \(3) |
Georg Brandle40a6a82007-12-08 11:23:13 +00001675| | [00,61]. | |
1676+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001677| ``%U`` | Week number of the year | \(4) |
Georg Brandle40a6a82007-12-08 11:23:13 +00001678| | (Sunday as the first day of | |
1679| | the week) as a decimal number | |
1680| | [00,53]. All days in a new | |
1681| | year preceding the first | |
1682| | Sunday are considered to be in | |
1683| | week 0. | |
1684+-----------+--------------------------------+-------+
1685| ``%w`` | Weekday as a decimal number | |
1686| | [0(Sunday),6]. | |
1687+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001688| ``%W`` | Week number of the year | \(4) |
Georg Brandle40a6a82007-12-08 11:23:13 +00001689| | (Monday as the first day of | |
1690| | the week) as a decimal number | |
1691| | [00,53]. All days in a new | |
1692| | year preceding the first | |
1693| | Monday are considered to be in | |
1694| | week 0. | |
1695+-----------+--------------------------------+-------+
1696| ``%x`` | Locale's appropriate date | |
1697| | representation. | |
1698+-----------+--------------------------------+-------+
1699| ``%X`` | Locale's appropriate time | |
1700| | representation. | |
1701+-----------+--------------------------------+-------+
1702| ``%y`` | Year without century as a | |
1703| | decimal number [00,99]. | |
1704+-----------+--------------------------------+-------+
1705| ``%Y`` | Year with century as a decimal | |
1706| | number. | |
1707+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001708| ``%z`` | UTC offset in the form +HHMM | \(5) |
Georg Brandle40a6a82007-12-08 11:23:13 +00001709| | or -HHMM (empty string if the | |
1710| | the object is naive). | |
1711+-----------+--------------------------------+-------+
1712| ``%Z`` | Time zone name (empty string | |
1713| | if the object is naive). | |
1714+-----------+--------------------------------+-------+
1715| ``%%`` | A literal ``'%'`` character. | |
1716+-----------+--------------------------------+-------+
Georg Brandl8ec7f652007-08-15 14:28:01 +00001717
Georg Brandle40a6a82007-12-08 11:23:13 +00001718Notes:
1719
1720(1)
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001721 When used with the :meth:`strptime` method, the ``%f`` directive
Skip Montanarofc070d22008-03-15 16:04:45 +00001722 accepts from one to six digits and zero pads on the right. ``%f`` is
Georg Brandlaf9a97b2009-01-18 14:41:52 +00001723 an extension to the set of format characters in the C standard (but
1724 implemented separately in datetime objects, and therefore always
1725 available).
Skip Montanarofc070d22008-03-15 16:04:45 +00001726
1727(2)
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001728 When used with the :meth:`strptime` method, the ``%p`` directive only affects
Georg Brandle40a6a82007-12-08 11:23:13 +00001729 the output hour field if the ``%I`` directive is used to parse the hour.
1730
Skip Montanarofc070d22008-03-15 16:04:45 +00001731(3)
R. David Murrayd56bab42009-04-02 04:34:04 +00001732 The range really is ``0`` to ``61``; according to the Posix standard this
1733 accounts for leap seconds and the (very rare) double leap seconds.
1734 The :mod:`time` module may produce and does accept leap seconds since
1735 it is based on the Posix standard, but the :mod:`datetime` module
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001736 does not accept leap seconds in :meth:`strptime` input nor will it
R. David Murrayd56bab42009-04-02 04:34:04 +00001737 produce them in :func:`strftime` output.
Georg Brandle40a6a82007-12-08 11:23:13 +00001738
Skip Montanarofc070d22008-03-15 16:04:45 +00001739(4)
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001740 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in
Georg Brandle40a6a82007-12-08 11:23:13 +00001741 calculations when the day of the week and the year are specified.
1742
Skip Montanarofc070d22008-03-15 16:04:45 +00001743(5)
Georg Brandle40a6a82007-12-08 11:23:13 +00001744 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1745 ``%z`` is replaced with the string ``'-0330'``.
R David Murray089d4d42012-05-14 22:32:44 -04001746
1747
1748.. rubric:: Footnotes
1749
1750.. [#] If, that is, we ignore the effects of Relativity