blob: df04cf3a41ff76286866e05aafa02d8db8399ca1 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`datetime` --- Basic date and time types
2=============================================
3
4.. module:: datetime
5 :synopsis: Basic date and time types.
6.. moduleauthor:: Tim Peters <tim@zope.com>
7.. sectionauthor:: Tim Peters <tim@zope.com>
8.. sectionauthor:: A.M. Kuchling <amk@amk.ca>
9
Christian Heimes5b5e81c2007-12-31 16:14:33 +000010.. XXX what order should the types be discussed in?
Georg Brandl116aa622007-08-15 14:28:22 +000011
Georg Brandl116aa622007-08-15 14:28:22 +000012The :mod:`datetime` module supplies classes for manipulating dates and times in
13both simple and complex ways. While date and time arithmetic is supported, the
14focus of the implementation is on efficient member extraction for output
15formatting and manipulation. For related
16functionality, see also the :mod:`time` and :mod:`calendar` modules.
17
18There are two kinds of date and time objects: "naive" and "aware". This
19distinction refers to whether the object has any notion of time zone, daylight
20saving time, or other kind of algorithmic or political time adjustment. Whether
21a naive :class:`datetime` object represents Coordinated Universal Time (UTC),
22local time, or time in some other timezone is purely up to the program, just
23like it's up to the program whether a particular number represents metres,
24miles, or mass. Naive :class:`datetime` objects are easy to understand and to
25work with, at the cost of ignoring some aspects of reality.
26
27For applications requiring more, :class:`datetime` and :class:`time` objects
28have an optional time zone information member, :attr:`tzinfo`, that can contain
29an instance of a subclass of the abstract :class:`tzinfo` class. These
30:class:`tzinfo` objects capture information about the offset from UTC time, the
31time zone name, and whether Daylight Saving Time is in effect. Note that no
32concrete :class:`tzinfo` classes are supplied by the :mod:`datetime` module.
33Supporting timezones at whatever level of detail is required is up to the
34application. The rules for time adjustment across the world are more political
35than rational, and there is no standard suitable for every application.
36
37The :mod:`datetime` module exports the following constants:
38
39
40.. data:: MINYEAR
41
42 The smallest year number allowed in a :class:`date` or :class:`datetime` object.
43 :const:`MINYEAR` is ``1``.
44
45
46.. data:: MAXYEAR
47
48 The largest year number allowed in a :class:`date` or :class:`datetime` object.
49 :const:`MAXYEAR` is ``9999``.
50
51
52.. seealso::
53
54 Module :mod:`calendar`
55 General calendar related functions.
56
57 Module :mod:`time`
58 Time access and conversions.
59
60
61Available Types
62---------------
63
64
65.. class:: date
66
67 An idealized naive date, assuming the current Gregorian calendar always was, and
68 always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and
69 :attr:`day`.
70
71
72.. class:: time
73
74 An idealized time, independent of any particular day, assuming that every day
75 has exactly 24\*60\*60 seconds (there is no notion of "leap seconds" here).
76 Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
77 and :attr:`tzinfo`.
78
79
80.. class:: datetime
81
82 A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`,
83 :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
84 and :attr:`tzinfo`.
85
86
87.. class:: timedelta
88
89 A duration expressing the difference between two :class:`date`, :class:`time`,
90 or :class:`datetime` instances to microsecond resolution.
91
92
93.. class:: tzinfo
94
95 An abstract base class for time zone information objects. These are used by the
96 :class:`datetime` and :class:`time` classes to provide a customizable notion of
97 time adjustment (for example, to account for time zone and/or daylight saving
98 time).
99
100Objects of these types are immutable.
101
102Objects of the :class:`date` type are always naive.
103
104An object *d* of type :class:`time` or :class:`datetime` may be naive or aware.
105*d* is aware if ``d.tzinfo`` is not ``None`` and ``d.tzinfo.utcoffset(d)`` does
106not return ``None``. If ``d.tzinfo`` is ``None``, or if ``d.tzinfo`` is not
107``None`` but ``d.tzinfo.utcoffset(d)`` returns ``None``, *d* is naive.
108
109The distinction between naive and aware doesn't apply to :class:`timedelta`
110objects.
111
112Subclass relationships::
113
114 object
115 timedelta
116 tzinfo
117 time
118 date
119 datetime
120
121
122.. _datetime-timedelta:
123
124:class:`timedelta` Objects
125--------------------------
126
127A :class:`timedelta` object represents a duration, the difference between two
128dates or times.
129
130
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000131.. class:: timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000132
Georg Brandl5c106642007-11-29 17:41:05 +0000133 All arguments are optional and default to ``0``. Arguments may be integers
Georg Brandl116aa622007-08-15 14:28:22 +0000134 or floats, and may be positive or negative.
135
136 Only *days*, *seconds* and *microseconds* are stored internally. Arguments are
137 converted to those units:
138
139 * A millisecond is converted to 1000 microseconds.
140 * A minute is converted to 60 seconds.
141 * An hour is converted to 3600 seconds.
142 * A week is converted to 7 days.
143
144 and days, seconds and microseconds are then normalized so that the
145 representation is unique, with
146
147 * ``0 <= microseconds < 1000000``
148 * ``0 <= seconds < 3600*24`` (the number of seconds in one day)
149 * ``-999999999 <= days <= 999999999``
150
151 If any argument is a float and there are fractional microseconds, the fractional
152 microseconds left over from all arguments are combined and their sum is rounded
153 to the nearest microsecond. If no argument is a float, the conversion and
154 normalization processes are exact (no information is lost).
155
156 If the normalized value of days lies outside the indicated range,
157 :exc:`OverflowError` is raised.
158
159 Note that normalization of negative values may be surprising at first. For
Christian Heimesfe337bf2008-03-23 21:54:12 +0000160 example,
Georg Brandl116aa622007-08-15 14:28:22 +0000161
Christian Heimes895627f2007-12-08 17:28:33 +0000162 >>> from datetime import timedelta
Georg Brandl116aa622007-08-15 14:28:22 +0000163 >>> d = timedelta(microseconds=-1)
164 >>> (d.days, d.seconds, d.microseconds)
165 (-1, 86399, 999999)
166
167Class attributes are:
168
169
170.. attribute:: timedelta.min
171
172 The most negative :class:`timedelta` object, ``timedelta(-999999999)``.
173
174
175.. attribute:: timedelta.max
176
177 The most positive :class:`timedelta` object, ``timedelta(days=999999999,
178 hours=23, minutes=59, seconds=59, microseconds=999999)``.
179
180
181.. attribute:: timedelta.resolution
182
183 The smallest possible difference between non-equal :class:`timedelta` objects,
184 ``timedelta(microseconds=1)``.
185
186Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``.
187``-timedelta.max`` is not representable as a :class:`timedelta` object.
188
189Instance attributes (read-only):
190
191+------------------+--------------------------------------------+
192| Attribute | Value |
193+==================+============================================+
194| ``days`` | Between -999999999 and 999999999 inclusive |
195+------------------+--------------------------------------------+
196| ``seconds`` | Between 0 and 86399 inclusive |
197+------------------+--------------------------------------------+
198| ``microseconds`` | Between 0 and 999999 inclusive |
199+------------------+--------------------------------------------+
200
201Supported operations:
202
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000203.. XXX this table is too wide!
Georg Brandl116aa622007-08-15 14:28:22 +0000204
205+--------------------------------+-----------------------------------------------+
206| Operation | Result |
207+================================+===============================================+
208| ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == |
209| | *t3* and *t1*-*t3* == *t2* are true. (1) |
210+--------------------------------+-----------------------------------------------+
211| ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* |
212| | == *t2* - *t3* and *t2* == *t1* + *t3* are |
213| | true. (1) |
214+--------------------------------+-----------------------------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000215| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer. |
Georg Brandl116aa622007-08-15 14:28:22 +0000216| | Afterwards *t1* // i == *t2* is true, |
217| | provided ``i != 0``. |
218+--------------------------------+-----------------------------------------------+
219| | In general, *t1* \* i == *t1* \* (i-1) + *t1* |
220| | is true. (1) |
221+--------------------------------+-----------------------------------------------+
222| ``t1 = t2 // i`` | The floor is computed and the remainder (if |
223| | any) is thrown away. (3) |
224+--------------------------------+-----------------------------------------------+
225| ``+t1`` | Returns a :class:`timedelta` object with the |
226| | same value. (2) |
227+--------------------------------+-----------------------------------------------+
228| ``-t1`` | equivalent to :class:`timedelta`\ |
229| | (-*t1.days*, -*t1.seconds*, |
230| | -*t1.microseconds*), and to *t1*\* -1. (1)(4) |
231+--------------------------------+-----------------------------------------------+
232| ``abs(t)`` | equivalent to +*t* when ``t.days >= 0``, and |
233| | to -*t* when ``t.days < 0``. (2) |
234+--------------------------------+-----------------------------------------------+
235
236Notes:
237
238(1)
239 This is exact, but may overflow.
240
241(2)
242 This is exact, and cannot overflow.
243
244(3)
245 Division by 0 raises :exc:`ZeroDivisionError`.
246
247(4)
248 -*timedelta.max* is not representable as a :class:`timedelta` object.
249
250In addition to the operations listed above :class:`timedelta` objects support
251certain additions and subtractions with :class:`date` and :class:`datetime`
252objects (see below).
253
254Comparisons of :class:`timedelta` objects are supported with the
255:class:`timedelta` object representing the smaller duration considered to be the
256smaller timedelta. In order to stop mixed-type comparisons from falling back to
257the default comparison by object address, when a :class:`timedelta` object is
258compared to an object of a different type, :exc:`TypeError` is raised unless the
259comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
260:const:`True`, respectively.
261
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000262:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl116aa622007-08-15 14:28:22 +0000263efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
264considered to be true if and only if it isn't equal to ``timedelta(0)``.
265
Christian Heimesfe337bf2008-03-23 21:54:12 +0000266Example usage:
Georg Brandl48310cd2009-01-03 21:18:54 +0000267
Christian Heimes895627f2007-12-08 17:28:33 +0000268 >>> from datetime import timedelta
269 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000270 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Christian Heimes895627f2007-12-08 17:28:33 +0000271 ... minutes=50, seconds=600) # adds up to 365 days
272 >>> year == another_year
273 True
274 >>> ten_years = 10 * year
275 >>> ten_years, ten_years.days // 365
276 (datetime.timedelta(3650), 10)
277 >>> nine_years = ten_years - year
278 >>> nine_years, nine_years.days // 365
279 (datetime.timedelta(3285), 9)
280 >>> three_years = nine_years // 3;
281 >>> three_years, three_years.days // 365
282 (datetime.timedelta(1095), 3)
283 >>> abs(three_years - ten_years) == 2 * three_years + year
284 True
285
Georg Brandl116aa622007-08-15 14:28:22 +0000286
287.. _datetime-date:
288
289:class:`date` Objects
290---------------------
291
292A :class:`date` object represents a date (year, month and day) in an idealized
293calendar, the current Gregorian calendar indefinitely extended in both
294directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
295called day number 2, and so on. This matches the definition of the "proleptic
296Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
297where it's the base calendar for all computations. See the book for algorithms
298for converting between proleptic Gregorian ordinals and many other calendar
299systems.
300
301
302.. class:: date(year, month, day)
303
Georg Brandl5c106642007-11-29 17:41:05 +0000304 All arguments are required. Arguments may be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000305 ranges:
306
307 * ``MINYEAR <= year <= MAXYEAR``
308 * ``1 <= month <= 12``
309 * ``1 <= day <= number of days in the given month and year``
310
311 If an argument outside those ranges is given, :exc:`ValueError` is raised.
312
313Other constructors, all class methods:
314
315
316.. method:: date.today()
317
318 Return the current local date. This is equivalent to
319 ``date.fromtimestamp(time.time())``.
320
321
322.. method:: date.fromtimestamp(timestamp)
323
324 Return the local date corresponding to the POSIX timestamp, such as is returned
325 by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out
326 of the range of values supported by the platform C :cfunc:`localtime` function.
327 It's common for this to be restricted to years from 1970 through 2038. Note
328 that on non-POSIX systems that include leap seconds in their notion of a
329 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
330
331
332.. method:: date.fromordinal(ordinal)
333
334 Return the date corresponding to the proleptic Gregorian ordinal, where January
335 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
336 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
337 d``.
338
339Class attributes:
340
341
342.. attribute:: date.min
343
344 The earliest representable date, ``date(MINYEAR, 1, 1)``.
345
346
347.. attribute:: date.max
348
349 The latest representable date, ``date(MAXYEAR, 12, 31)``.
350
351
352.. attribute:: date.resolution
353
354 The smallest possible difference between non-equal date objects,
355 ``timedelta(days=1)``.
356
357Instance attributes (read-only):
358
359
360.. attribute:: date.year
361
362 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
363
364
365.. attribute:: date.month
366
367 Between 1 and 12 inclusive.
368
369
370.. attribute:: date.day
371
372 Between 1 and the number of days in the given month of the given year.
373
374Supported operations:
375
376+-------------------------------+----------------------------------------------+
377| Operation | Result |
378+===============================+==============================================+
379| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
380| | from *date1*. (1) |
381+-------------------------------+----------------------------------------------+
382| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
383| | timedelta == date1``. (2) |
384+-------------------------------+----------------------------------------------+
385| ``timedelta = date1 - date2`` | \(3) |
386+-------------------------------+----------------------------------------------+
387| ``date1 < date2`` | *date1* is considered less than *date2* when |
388| | *date1* precedes *date2* in time. (4) |
389+-------------------------------+----------------------------------------------+
390
391Notes:
392
393(1)
394 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
395 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
396 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
397 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
398 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
399
400(2)
401 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
402 isolation can overflow in cases where date1 - timedelta does not.
403 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
404
405(3)
406 This is exact, and cannot overflow. timedelta.seconds and
407 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
408
409(4)
410 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
411 date2.toordinal()``. In order to stop comparison from falling back to the
412 default scheme of comparing object addresses, date comparison normally raises
413 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
414 However, ``NotImplemented`` is returned instead if the other comparand has a
415 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
416 chance at implementing mixed-type comparison. If not, when a :class:`date`
417 object is compared to an object of a different type, :exc:`TypeError` is raised
418 unless the comparison is ``==`` or ``!=``. The latter cases return
419 :const:`False` or :const:`True`, respectively.
420
421Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
422objects are considered to be true.
423
424Instance methods:
425
426
427.. method:: date.replace(year, month, day)
428
429 Return a date with the same value, except for those members given new values by
430 whichever keyword arguments are specified. For example, if ``d == date(2002,
431 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
432
433
434.. method:: date.timetuple()
435
436 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
437 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
438 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
439 d.weekday(), d.toordinal() - date(d.year, 1, 1).toordinal() + 1, -1))``
440
441
442.. method:: date.toordinal()
443
444 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
445 has ordinal 1. For any :class:`date` object *d*,
446 ``date.fromordinal(d.toordinal()) == d``.
447
448
449.. method:: date.weekday()
450
451 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
452 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
453 :meth:`isoweekday`.
454
455
456.. method:: date.isoweekday()
457
458 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
459 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
460 :meth:`weekday`, :meth:`isocalendar`.
461
462
463.. method:: date.isocalendar()
464
465 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
466
467 The ISO calendar is a widely used variant of the Gregorian calendar. See
468 http://www.phys.uu.nl/ vgent/calendar/isocalendar.htm for a good explanation.
469
470 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
471 Monday and ends on a Sunday. The first week of an ISO year is the first
472 (Gregorian) calendar week of a year containing a Thursday. This is called week
473 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
474
475 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
476 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
477 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
478 4).isocalendar() == (2004, 1, 7)``.
479
480
481.. method:: date.isoformat()
482
483 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
484 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
485
486
487.. method:: date.__str__()
488
489 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
490
491
492.. method:: date.ctime()
493
494 Return a string representing the date, for example ``date(2002, 12,
495 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
496 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
497 :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
498 :meth:`date.ctime` does not invoke) conforms to the C standard.
499
500
501.. method:: date.strftime(format)
502
503 Return a string representing the date, controlled by an explicit format string.
504 Format codes referring to hours, minutes or seconds will see 0 values. See
505 section :ref:`strftime-behavior`.
506
Christian Heimes895627f2007-12-08 17:28:33 +0000507Example of counting days to an event::
508
509 >>> import time
510 >>> from datetime import date
511 >>> today = date.today()
512 >>> today
513 datetime.date(2007, 12, 5)
514 >>> today == date.fromtimestamp(time.time())
515 True
516 >>> my_birthday = date(today.year, 6, 24)
517 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000518 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000519 >>> my_birthday
520 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000521 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000522 >>> time_to_birthday.days
523 202
524
Christian Heimesfe337bf2008-03-23 21:54:12 +0000525Example of working with :class:`date`:
526
527.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000528
529 >>> from datetime import date
530 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
531 >>> d
532 datetime.date(2002, 3, 11)
533 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000534 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000535 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000536 2002 # year
537 3 # month
538 11 # day
539 0
540 0
541 0
542 0 # weekday (0 = Monday)
543 70 # 70th day in the year
544 -1
545 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000546 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000547 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000548 2002 # ISO year
549 11 # ISO week number
550 1 # ISO day number ( 1 = Monday )
551 >>> d.isoformat()
552 '2002-03-11'
553 >>> d.strftime("%d/%m/%y")
554 '11/03/02'
555 >>> d.strftime("%A %d. %B %Y")
556 'Monday 11. March 2002'
557
Georg Brandl116aa622007-08-15 14:28:22 +0000558
559.. _datetime-datetime:
560
561:class:`datetime` Objects
562-------------------------
563
564A :class:`datetime` object is a single object containing all the information
565from a :class:`date` object and a :class:`time` object. Like a :class:`date`
566object, :class:`datetime` assumes the current Gregorian calendar extended in
567both directions; like a time object, :class:`datetime` assumes there are exactly
5683600\*24 seconds in every day.
569
570Constructor:
571
572
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000573.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000574
575 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000576 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
577 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000578
579 * ``MINYEAR <= year <= MAXYEAR``
580 * ``1 <= month <= 12``
581 * ``1 <= day <= number of days in the given month and year``
582 * ``0 <= hour < 24``
583 * ``0 <= minute < 60``
584 * ``0 <= second < 60``
585 * ``0 <= microsecond < 1000000``
586
587 If an argument outside those ranges is given, :exc:`ValueError` is raised.
588
589Other constructors, all class methods:
590
591
592.. method:: datetime.today()
593
594 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
595 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
596 :meth:`fromtimestamp`.
597
598
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000599.. method:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000600
601 Return the current local date and time. If optional argument *tz* is ``None``
602 or not specified, this is like :meth:`today`, but, if possible, supplies more
603 precision than can be gotten from going through a :func:`time.time` timestamp
604 (for example, this may be possible on platforms supplying the C
605 :cfunc:`gettimeofday` function).
606
607 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
608 current date and time are converted to *tz*'s time zone. In this case the
609 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
610 See also :meth:`today`, :meth:`utcnow`.
611
612
613.. method:: datetime.utcnow()
614
615 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
616 :meth:`now`, but returns the current UTC date and time, as a naive
617 :class:`datetime` object. See also :meth:`now`.
618
619
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000620.. method:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000621
622 Return the local date and time corresponding to the POSIX timestamp, such as is
623 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
624 specified, the timestamp is converted to the platform's local date and time, and
625 the returned :class:`datetime` object is naive.
626
627 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
628 timestamp is converted to *tz*'s time zone. In this case the result is
629 equivalent to
630 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
631
632 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
633 the range of values supported by the platform C :cfunc:`localtime` or
634 :cfunc:`gmtime` functions. It's common for this to be restricted to years in
635 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
636 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
637 and then it's possible to have two timestamps differing by a second that yield
638 identical :class:`datetime` objects. See also :meth:`utcfromtimestamp`.
639
640
641.. method:: datetime.utcfromtimestamp(timestamp)
642
643 Return the UTC :class:`datetime` corresponding to the POSIX timestamp, with
644 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
645 out of the range of values supported by the platform C :cfunc:`gmtime` function.
646 It's common for this to be restricted to years in 1970 through 2038. See also
647 :meth:`fromtimestamp`.
648
649
650.. method:: datetime.fromordinal(ordinal)
651
652 Return the :class:`datetime` corresponding to the proleptic Gregorian ordinal,
653 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
654 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
655 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
656
657
658.. method:: datetime.combine(date, time)
659
660 Return a new :class:`datetime` object whose date members are equal to the given
661 :class:`date` object's, and whose time and :attr:`tzinfo` members are equal to
662 the given :class:`time` object's. For any :class:`datetime` object *d*, ``d ==
663 datetime.combine(d.date(), d.timetz())``. If date is a :class:`datetime`
664 object, its time and :attr:`tzinfo` members are ignored.
665
666
667.. method:: datetime.strptime(date_string, format)
668
669 Return a :class:`datetime` corresponding to *date_string*, parsed according to
670 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
671 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
672 can't be parsed by :func:`time.strptime` or if it returns a value which isn't a
673 time tuple.
674
Georg Brandl116aa622007-08-15 14:28:22 +0000675
676Class attributes:
677
678
679.. attribute:: datetime.min
680
681 The earliest representable :class:`datetime`, ``datetime(MINYEAR, 1, 1,
682 tzinfo=None)``.
683
684
685.. attribute:: datetime.max
686
687 The latest representable :class:`datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
688 59, 999999, tzinfo=None)``.
689
690
691.. attribute:: datetime.resolution
692
693 The smallest possible difference between non-equal :class:`datetime` objects,
694 ``timedelta(microseconds=1)``.
695
696Instance attributes (read-only):
697
698
699.. attribute:: datetime.year
700
701 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
702
703
704.. attribute:: datetime.month
705
706 Between 1 and 12 inclusive.
707
708
709.. attribute:: datetime.day
710
711 Between 1 and the number of days in the given month of the given year.
712
713
714.. attribute:: datetime.hour
715
716 In ``range(24)``.
717
718
719.. attribute:: datetime.minute
720
721 In ``range(60)``.
722
723
724.. attribute:: datetime.second
725
726 In ``range(60)``.
727
728
729.. attribute:: datetime.microsecond
730
731 In ``range(1000000)``.
732
733
734.. attribute:: datetime.tzinfo
735
736 The object passed as the *tzinfo* argument to the :class:`datetime` constructor,
737 or ``None`` if none was passed.
738
739Supported operations:
740
741+---------------------------------------+-------------------------------+
742| Operation | Result |
743+=======================================+===============================+
744| ``datetime2 = datetime1 + timedelta`` | \(1) |
745+---------------------------------------+-------------------------------+
746| ``datetime2 = datetime1 - timedelta`` | \(2) |
747+---------------------------------------+-------------------------------+
748| ``timedelta = datetime1 - datetime2`` | \(3) |
749+---------------------------------------+-------------------------------+
750| ``datetime1 < datetime2`` | Compares :class:`datetime` to |
751| | :class:`datetime`. (4) |
752+---------------------------------------+-------------------------------+
753
754(1)
755 datetime2 is a duration of timedelta removed from datetime1, moving forward in
756 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
757 result has the same :attr:`tzinfo` member as the input datetime, and datetime2 -
758 datetime1 == timedelta after. :exc:`OverflowError` is raised if datetime2.year
759 would be smaller than :const:`MINYEAR` or larger than :const:`MAXYEAR`. Note
760 that no time zone adjustments are done even if the input is an aware object.
761
762(2)
763 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
764 addition, the result has the same :attr:`tzinfo` member as the input datetime,
765 and no time zone adjustments are done even if the input is aware. This isn't
766 quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation
767 can overflow in cases where datetime1 - timedelta does not.
768
769(3)
770 Subtraction of a :class:`datetime` from a :class:`datetime` is defined only if
771 both operands are naive, or if both are aware. If one is aware and the other is
772 naive, :exc:`TypeError` is raised.
773
774 If both are naive, or both are aware and have the same :attr:`tzinfo` member,
775 the :attr:`tzinfo` members are ignored, and the result is a :class:`timedelta`
776 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
777 are done in this case.
778
779 If both are aware and have different :attr:`tzinfo` members, ``a-b`` acts as if
780 *a* and *b* were first converted to naive UTC datetimes first. The result is
781 ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) -
782 b.utcoffset())`` except that the implementation never overflows.
783
784(4)
785 *datetime1* is considered less than *datetime2* when *datetime1* precedes
786 *datetime2* in time.
787
788 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
789 If both comparands are aware, and have the same :attr:`tzinfo` member, the
790 common :attr:`tzinfo` member is ignored and the base datetimes are compared. If
791 both comparands are aware and have different :attr:`tzinfo` members, the
792 comparands are first adjusted by subtracting their UTC offsets (obtained from
793 ``self.utcoffset()``).
794
795 .. note::
796
797 In order to stop comparison from falling back to the default scheme of comparing
798 object addresses, datetime comparison normally raises :exc:`TypeError` if the
799 other comparand isn't also a :class:`datetime` object. However,
800 ``NotImplemented`` is returned instead if the other comparand has a
801 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
802 chance at implementing mixed-type comparison. If not, when a :class:`datetime`
803 object is compared to an object of a different type, :exc:`TypeError` is raised
804 unless the comparison is ``==`` or ``!=``. The latter cases return
805 :const:`False` or :const:`True`, respectively.
806
807:class:`datetime` objects can be used as dictionary keys. In Boolean contexts,
808all :class:`datetime` objects are considered to be true.
809
810Instance methods:
811
812
813.. method:: datetime.date()
814
815 Return :class:`date` object with same year, month and day.
816
817
818.. method:: datetime.time()
819
820 Return :class:`time` object with same hour, minute, second and microsecond.
821 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
822
823
824.. method:: datetime.timetz()
825
826 Return :class:`time` object with same hour, minute, second, microsecond, and
827 tzinfo members. See also method :meth:`time`.
828
829
830.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
831
832 Return a datetime with the same members, except for those members given new
833 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
834 can be specified to create a naive datetime from an aware datetime with no
835 conversion of date and time members.
836
837
838.. method:: datetime.astimezone(tz)
839
840 Return a :class:`datetime` object with new :attr:`tzinfo` member *tz*, adjusting
841 the date and time members so the result is the same UTC time as *self*, but in
842 *tz*'s local time.
843
844 *tz* must be an instance of a :class:`tzinfo` subclass, and its
845 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
846 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
847 not return ``None``).
848
849 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
850 adjustment of date or time members is performed. Else the result is local time
851 in time zone *tz*, representing the same UTC time as *self*: after ``astz =
852 dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have the same date
853 and time members as ``dt - dt.utcoffset()``. The discussion of class
854 :class:`tzinfo` explains the cases at Daylight Saving Time transition boundaries
855 where this cannot be achieved (an issue only if *tz* models both standard and
856 daylight time).
857
858 If you merely want to attach a time zone object *tz* to a datetime *dt* without
859 adjustment of date and time members, use ``dt.replace(tzinfo=tz)``. If you
860 merely want to remove the time zone object from an aware datetime *dt* without
861 conversion of date and time members, use ``dt.replace(tzinfo=None)``.
862
863 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
864 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
865 Ignoring error cases, :meth:`astimezone` acts like::
866
867 def astimezone(self, tz):
868 if self.tzinfo is tz:
869 return self
870 # Convert self to UTC, and attach the new time zone object.
871 utc = (self - self.utcoffset()).replace(tzinfo=tz)
872 # Convert from UTC to tz's local time.
873 return tz.fromutc(utc)
874
875
876.. method:: datetime.utcoffset()
877
878 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
879 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
880 return ``None``, or a :class:`timedelta` object representing a whole number of
881 minutes with magnitude less than one day.
882
883
884.. method:: datetime.dst()
885
886 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
887 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
888 ``None``, or a :class:`timedelta` object representing a whole number of minutes
889 with magnitude less than one day.
890
891
892.. method:: datetime.tzname()
893
894 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
895 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
896 ``None`` or a string object,
897
898
899.. method:: datetime.timetuple()
900
901 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
902 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
903 d.hour, d.minute, d.second, d.weekday(), d.toordinal() - date(d.year, 1,
904 1).toordinal() + 1, dst))`` The :attr:`tm_isdst` flag of the result is set
905 according to the :meth:`dst` method: :attr:`tzinfo` is ``None`` or :meth:`dst`
906 returns ``None``, :attr:`tm_isdst` is set to ``-1``; else if :meth:`dst`
907 returns a non-zero value, :attr:`tm_isdst` is set to ``1``; else ``tm_isdst`` is
908 set to ``0``.
909
910
911.. method:: datetime.utctimetuple()
912
913 If :class:`datetime` instance *d* is naive, this is the same as
914 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
915 ``d.dst()`` returns. DST is never in effect for a UTC time.
916
917 If *d* is aware, *d* is normalized to UTC time, by subtracting
918 ``d.utcoffset()``, and a :class:`time.struct_time` for the normalized time is
919 returned. :attr:`tm_isdst` is forced to 0. Note that the result's
920 :attr:`tm_year` member may be :const:`MINYEAR`\ -1 or :const:`MAXYEAR`\ +1, if
921 *d*.year was ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
922 boundary.
923
924
925.. method:: datetime.toordinal()
926
927 Return the proleptic Gregorian ordinal of the date. The same as
928 ``self.date().toordinal()``.
929
930
931.. method:: datetime.weekday()
932
933 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
934 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
935
936
937.. method:: datetime.isoweekday()
938
939 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
940 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
941 :meth:`isocalendar`.
942
943
944.. method:: datetime.isocalendar()
945
946 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
947 ``self.date().isocalendar()``.
948
949
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000950.. method:: datetime.isoformat(sep='T')
Georg Brandl116aa622007-08-15 14:28:22 +0000951
952 Return a string representing the date and time in ISO 8601 format,
953 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
954 YYYY-MM-DDTHH:MM:SS
955
956 If :meth:`utcoffset` does not return ``None``, a 6-character string is
957 appended, giving the UTC offset in (signed) hours and minutes:
958 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
959 YYYY-MM-DDTHH:MM:SS+HH:MM
960
961 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000962 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +0000963
964 >>> from datetime import tzinfo, timedelta, datetime
965 >>> class TZ(tzinfo):
966 ... def utcoffset(self, dt): return timedelta(minutes=-399)
967 ...
968 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
969 '2002-12-25 00:00:00-06:39'
970
971
972.. method:: datetime.__str__()
973
974 For a :class:`datetime` instance *d*, ``str(d)`` is equivalent to
975 ``d.isoformat(' ')``.
976
977
978.. method:: datetime.ctime()
979
980 Return a string representing the date and time, for example ``datetime(2002, 12,
981 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
982 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
983 native C :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
984 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
985
986
987.. method:: datetime.strftime(format)
988
989 Return a string representing the date and time, controlled by an explicit format
990 string. See section :ref:`strftime-behavior`.
991
Christian Heimesfe337bf2008-03-23 21:54:12 +0000992Examples of working with datetime objects:
993
994.. doctest::
995
Christian Heimes895627f2007-12-08 17:28:33 +0000996 >>> from datetime import datetime, date, time
997 >>> # Using datetime.combine()
998 >>> d = date(2005, 7, 14)
999 >>> t = time(12, 30)
1000 >>> datetime.combine(d, t)
1001 datetime.datetime(2005, 7, 14, 12, 30)
1002 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001003 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001004 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001005 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001006 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1007 >>> # Using datetime.strptime()
1008 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1009 >>> dt
1010 datetime.datetime(2006, 11, 21, 16, 30)
1011 >>> # Using datetime.timetuple() to get tuple of all attributes
1012 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001013 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001014 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001015 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001016 2006 # year
1017 11 # month
1018 21 # day
1019 16 # hour
1020 30 # minute
1021 0 # second
1022 1 # weekday (0 = Monday)
1023 325 # number of days since 1st January
1024 -1 # dst - method tzinfo.dst() returned None
1025 >>> # Date in ISO format
1026 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001027 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001028 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001029 ...
1030 2006 # ISO year
1031 47 # ISO week
1032 2 # ISO weekday
1033 >>> # Formatting datetime
1034 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1035 'Tuesday, 21. November 2006 04:30PM'
1036
Christian Heimesfe337bf2008-03-23 21:54:12 +00001037Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001038
1039 >>> from datetime import timedelta, datetime, tzinfo
1040 >>> class GMT1(tzinfo):
1041 ... def __init__(self): # DST starts last Sunday in March
1042 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1043 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001044 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001045 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1046 ... def utcoffset(self, dt):
1047 ... return timedelta(hours=1) + self.dst(dt)
Georg Brandl48310cd2009-01-03 21:18:54 +00001048 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001049 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1050 ... return timedelta(hours=1)
1051 ... else:
1052 ... return timedelta(0)
1053 ... def tzname(self,dt):
1054 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001055 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001056 >>> class GMT2(tzinfo):
1057 ... def __init__(self):
Georg Brandl48310cd2009-01-03 21:18:54 +00001058 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001059 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001060 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001061 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1062 ... def utcoffset(self, dt):
1063 ... return timedelta(hours=1) + self.dst(dt)
1064 ... def dst(self, dt):
1065 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1066 ... return timedelta(hours=2)
1067 ... else:
1068 ... return timedelta(0)
1069 ... def tzname(self,dt):
1070 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001071 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001072 >>> gmt1 = GMT1()
1073 >>> # Daylight Saving Time
1074 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1075 >>> dt1.dst()
1076 datetime.timedelta(0)
1077 >>> dt1.utcoffset()
1078 datetime.timedelta(0, 3600)
1079 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1080 >>> dt2.dst()
1081 datetime.timedelta(0, 3600)
1082 >>> dt2.utcoffset()
1083 datetime.timedelta(0, 7200)
1084 >>> # Convert datetime to another time zone
1085 >>> dt3 = dt2.astimezone(GMT2())
1086 >>> dt3 # doctest: +ELLIPSIS
1087 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1088 >>> dt2 # doctest: +ELLIPSIS
1089 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1090 >>> dt2.utctimetuple() == dt3.utctimetuple()
1091 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001092
Christian Heimes895627f2007-12-08 17:28:33 +00001093
Georg Brandl116aa622007-08-15 14:28:22 +00001094
1095.. _datetime-time:
1096
1097:class:`time` Objects
1098---------------------
1099
1100A time object represents a (local) time of day, independent of any particular
1101day, and subject to adjustment via a :class:`tzinfo` object.
1102
1103
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001104.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001105
1106 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001107 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001108 following ranges:
1109
1110 * ``0 <= hour < 24``
1111 * ``0 <= minute < 60``
1112 * ``0 <= second < 60``
1113 * ``0 <= microsecond < 1000000``.
1114
1115 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1116 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1117
1118Class attributes:
1119
1120
1121.. attribute:: time.min
1122
1123 The earliest representable :class:`time`, ``time(0, 0, 0, 0)``.
1124
1125
1126.. attribute:: time.max
1127
1128 The latest representable :class:`time`, ``time(23, 59, 59, 999999)``.
1129
1130
1131.. attribute:: time.resolution
1132
1133 The smallest possible difference between non-equal :class:`time` objects,
1134 ``timedelta(microseconds=1)``, although note that arithmetic on :class:`time`
1135 objects is not supported.
1136
1137Instance attributes (read-only):
1138
1139
1140.. attribute:: time.hour
1141
1142 In ``range(24)``.
1143
1144
1145.. attribute:: time.minute
1146
1147 In ``range(60)``.
1148
1149
1150.. attribute:: time.second
1151
1152 In ``range(60)``.
1153
1154
1155.. attribute:: time.microsecond
1156
1157 In ``range(1000000)``.
1158
1159
1160.. attribute:: time.tzinfo
1161
1162 The object passed as the tzinfo argument to the :class:`time` constructor, or
1163 ``None`` if none was passed.
1164
1165Supported operations:
1166
1167* comparison of :class:`time` to :class:`time`, where *a* is considered less
1168 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1169 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
1170 the same :attr:`tzinfo` member, the common :attr:`tzinfo` member is ignored and
1171 the base times are compared. If both comparands are aware and have different
1172 :attr:`tzinfo` members, the comparands are first adjusted by subtracting their
1173 UTC offsets (obtained from ``self.utcoffset()``). In order to stop mixed-type
1174 comparisons from falling back to the default comparison by object address, when
1175 a :class:`time` object is compared to an object of a different type,
1176 :exc:`TypeError` is raised unless the comparison is ``==`` or ``!=``. The
1177 latter cases return :const:`False` or :const:`True`, respectively.
1178
1179* hash, use as dict key
1180
1181* efficient pickling
1182
1183* in Boolean contexts, a :class:`time` object is considered to be true if and
1184 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1185 ``0`` if that's ``None``), the result is non-zero.
1186
1187Instance methods:
1188
1189
1190.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1191
1192 Return a :class:`time` with the same value, except for those members given new
1193 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
1194 can be specified to create a naive :class:`time` from an aware :class:`time`,
1195 without conversion of the time members.
1196
1197
1198.. method:: time.isoformat()
1199
1200 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1201 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1202 6-character string is appended, giving the UTC offset in (signed) hours and
1203 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1204
1205
1206.. method:: time.__str__()
1207
1208 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1209
1210
1211.. method:: time.strftime(format)
1212
1213 Return a string representing the time, controlled by an explicit format string.
1214 See section :ref:`strftime-behavior`.
1215
1216
1217.. method:: time.utcoffset()
1218
1219 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1220 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1221 return ``None`` or a :class:`timedelta` object representing a whole number of
1222 minutes with magnitude less than one day.
1223
1224
1225.. method:: time.dst()
1226
1227 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1228 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1229 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1230 with magnitude less than one day.
1231
1232
1233.. method:: time.tzname()
1234
1235 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1236 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1237 return ``None`` or a string object.
1238
Christian Heimesfe337bf2008-03-23 21:54:12 +00001239Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001240
Christian Heimes895627f2007-12-08 17:28:33 +00001241 >>> from datetime import time, tzinfo
1242 >>> class GMT1(tzinfo):
1243 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001244 ... return timedelta(hours=1)
1245 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001246 ... return timedelta(0)
1247 ... def tzname(self,dt):
1248 ... return "Europe/Prague"
1249 ...
1250 >>> t = time(12, 10, 30, tzinfo=GMT1())
1251 >>> t # doctest: +ELLIPSIS
1252 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1253 >>> gmt = GMT1()
1254 >>> t.isoformat()
1255 '12:10:30+01:00'
1256 >>> t.dst()
1257 datetime.timedelta(0)
1258 >>> t.tzname()
1259 'Europe/Prague'
1260 >>> t.strftime("%H:%M:%S %Z")
1261 '12:10:30 Europe/Prague'
1262
Georg Brandl116aa622007-08-15 14:28:22 +00001263
1264.. _datetime-tzinfo:
1265
1266:class:`tzinfo` Objects
1267-----------------------
1268
Brett Cannone1327f72009-01-29 04:10:21 +00001269:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001270instantiated directly. You need to derive a concrete subclass, and (at least)
1271supply implementations of the standard :class:`tzinfo` methods needed by the
1272:class:`datetime` methods you use. The :mod:`datetime` module does not supply
1273any concrete subclasses of :class:`tzinfo`.
1274
1275An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1276constructors for :class:`datetime` and :class:`time` objects. The latter objects
1277view their members as being in local time, and the :class:`tzinfo` object
1278supports methods revealing offset of local time from UTC, the name of the time
1279zone, and DST offset, all relative to a date or time object passed to them.
1280
1281Special requirement for pickling: A :class:`tzinfo` subclass must have an
1282:meth:`__init__` method that can be called with no arguments, else it can be
1283pickled but possibly not unpickled again. This is a technical requirement that
1284may be relaxed in the future.
1285
1286A concrete subclass of :class:`tzinfo` may need to implement the following
1287methods. Exactly which methods are needed depends on the uses made of aware
1288:mod:`datetime` objects. If in doubt, simply implement all of them.
1289
1290
1291.. method:: tzinfo.utcoffset(self, dt)
1292
1293 Return offset of local time from UTC, in minutes east of UTC. If local time is
1294 west of UTC, this should be negative. Note that this is intended to be the
1295 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1296 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1297 the UTC offset isn't known, return ``None``. Else the value returned must be a
1298 :class:`timedelta` object specifying a whole number of minutes in the range
1299 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1300 than one day). Most implementations of :meth:`utcoffset` will probably look
1301 like one of these two::
1302
1303 return CONSTANT # fixed-offset class
1304 return CONSTANT + self.dst(dt) # daylight-aware class
1305
1306 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1307 ``None`` either.
1308
1309 The default implementation of :meth:`utcoffset` raises
1310 :exc:`NotImplementedError`.
1311
1312
1313.. method:: tzinfo.dst(self, dt)
1314
1315 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1316 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1317 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1318 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1319 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1320 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1321 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
1322 member's :meth:`dst` method to determine how the :attr:`tm_isdst` flag should be
1323 set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for DST changes
1324 when crossing time zones.
1325
1326 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1327 daylight times must be consistent in this sense:
1328
1329 ``tz.utcoffset(dt) - tz.dst(dt)``
1330
1331 must return the same result for every :class:`datetime` *dt* with ``dt.tzinfo ==
1332 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1333 zone's "standard offset", which should not depend on the date or the time, but
1334 only on geographic location. The implementation of :meth:`datetime.astimezone`
1335 relies on this, but cannot detect violations; it's the programmer's
1336 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1337 this, it may be able to override the default implementation of
1338 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1339
1340 Most implementations of :meth:`dst` will probably look like one of these two::
1341
1342 def dst(self):
1343 # a fixed-offset class: doesn't account for DST
1344 return timedelta(0)
1345
1346 or ::
1347
1348 def dst(self):
1349 # Code to set dston and dstoff to the time zone's DST
1350 # transition times based on the input dt.year, and expressed
1351 # in standard local time. Then
1352
1353 if dston <= dt.replace(tzinfo=None) < dstoff:
1354 return timedelta(hours=1)
1355 else:
1356 return timedelta(0)
1357
1358 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1359
1360
1361.. method:: tzinfo.tzname(self, dt)
1362
1363 Return the time zone name corresponding to the :class:`datetime` object *dt*, as
1364 a string. Nothing about string names is defined by the :mod:`datetime` module,
1365 and there's no requirement that it mean anything in particular. For example,
1366 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1367 valid replies. Return ``None`` if a string name isn't known. Note that this is
1368 a method rather than a fixed string primarily because some :class:`tzinfo`
1369 subclasses will wish to return different names depending on the specific value
1370 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1371 daylight time.
1372
1373 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1374
1375These methods are called by a :class:`datetime` or :class:`time` object, in
1376response to their methods of the same names. A :class:`datetime` object passes
1377itself as the argument, and a :class:`time` object passes ``None`` as the
1378argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
1379accept a *dt* argument of ``None``, or of class :class:`datetime`.
1380
1381When ``None`` is passed, it's up to the class designer to decide the best
1382response. For example, returning ``None`` is appropriate if the class wishes to
1383say that time objects don't participate in the :class:`tzinfo` protocols. It
1384may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1385there is no other convention for discovering the standard offset.
1386
1387When a :class:`datetime` object is passed in response to a :class:`datetime`
1388method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1389rely on this, unless user code calls :class:`tzinfo` methods directly. The
1390intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1391time, and not need worry about objects in other timezones.
1392
1393There is one more :class:`tzinfo` method that a subclass may wish to override:
1394
1395
1396.. method:: tzinfo.fromutc(self, dt)
1397
1398 This is called from the default :class:`datetime.astimezone()` implementation.
1399 When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members
1400 are to be viewed as expressing a UTC time. The purpose of :meth:`fromutc` is to
1401 adjust the date and time members, returning an equivalent datetime in *self*'s
1402 local time.
1403
1404 Most :class:`tzinfo` subclasses should be able to inherit the default
1405 :meth:`fromutc` implementation without problems. It's strong enough to handle
1406 fixed-offset time zones, and time zones accounting for both standard and
1407 daylight time, and the latter even if the DST transition times differ in
1408 different years. An example of a time zone the default :meth:`fromutc`
1409 implementation may not handle correctly in all cases is one where the standard
1410 offset (from UTC) depends on the specific date and time passed, which can happen
1411 for political reasons. The default implementations of :meth:`astimezone` and
1412 :meth:`fromutc` may not produce the result you want if the result is one of the
1413 hours straddling the moment the standard offset changes.
1414
1415 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1416 like::
1417
1418 def fromutc(self, dt):
1419 # raise ValueError error if dt.tzinfo is not self
1420 dtoff = dt.utcoffset()
1421 dtdst = dt.dst()
1422 # raise ValueError if dtoff is None or dtdst is None
1423 delta = dtoff - dtdst # this is self's standard offset
1424 if delta:
1425 dt += delta # convert to standard local time
1426 dtdst = dt.dst()
1427 # raise ValueError if dtdst is None
1428 if dtdst:
1429 return dt + dtdst
1430 else:
1431 return dt
1432
1433Example :class:`tzinfo` classes:
1434
1435.. literalinclude:: ../includes/tzinfo-examples.py
1436
1437
1438Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1439subclass accounting for both standard and daylight time, at the DST transition
1440points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
1441minute after 1:59 (EST) on the first Sunday in April, and ends the minute after
14421:59 (EDT) on the last Sunday in October::
1443
1444 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1445 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1446 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1447
1448 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1449
1450 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1451
1452When DST starts (the "start" line), the local wall clock leaps from 1:59 to
14533:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1454``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1455begins. In order for :meth:`astimezone` to make this guarantee, the
1456:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1457Eastern) to be in daylight time.
1458
1459When DST ends (the "end" line), there's a potentially worse problem: there's an
1460hour that can't be spelled unambiguously in local wall time: the last hour of
1461daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1462daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1463to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1464:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1465hours into the same local hour then. In the Eastern example, UTC times of the
1466form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1467:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1468consider times in the "repeated hour" to be in standard time. This is easily
1469arranged, as in the example, by expressing DST switch times in the time zone's
1470standard local time.
1471
1472Applications that can't bear such ambiguities should avoid using hybrid
1473:class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any
1474other fixed-offset :class:`tzinfo` subclass (such as a class representing only
1475EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
Georg Brandl48310cd2009-01-03 21:18:54 +00001476
Georg Brandl116aa622007-08-15 14:28:22 +00001477
1478.. _strftime-behavior:
1479
1480:meth:`strftime` Behavior
1481-------------------------
1482
1483:class:`date`, :class:`datetime`, and :class:`time` objects all support a
1484``strftime(format)`` method, to create a string representing the time under the
1485control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1486acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1487although not all objects support a :meth:`timetuple` method.
1488
1489For :class:`time` objects, the format codes for year, month, and day should not
1490be used, as time objects have no such values. If they're used anyway, ``1900``
1491is substituted for the year, and ``0`` for the month and day.
1492
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001493For :class:`date` objects, the format codes for hours, minutes, seconds, and
1494microseconds should not be used, as :class:`date` objects have no such
1495values. If they're used anyway, ``0`` is substituted for them.
1496
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001497For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1498strings.
1499
1500For an aware object:
1501
1502``%z``
1503 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1504 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1505 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1506 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1507 replaced with the string ``'-0330'``.
1508
1509``%Z``
1510 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1511 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl116aa622007-08-15 14:28:22 +00001512
Georg Brandl116aa622007-08-15 14:28:22 +00001513The full set of format codes supported varies across platforms, because Python
1514calls the platform C library's :func:`strftime` function, and platform
Georg Brandl48310cd2009-01-03 21:18:54 +00001515variations are common.
Christian Heimes895627f2007-12-08 17:28:33 +00001516
1517The following is a list of all the format codes that the C standard (1989
1518version) requires, and these work on all platforms with a standard C
1519implementation. Note that the 1999 version of the C standard added additional
1520format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001521
1522The exact range of years for which :meth:`strftime` works also varies across
1523platforms. Regardless of platform, years before 1900 cannot be used.
1524
Christian Heimes895627f2007-12-08 17:28:33 +00001525+-----------+--------------------------------+-------+
1526| Directive | Meaning | Notes |
1527+===========+================================+=======+
1528| ``%a`` | Locale's abbreviated weekday | |
1529| | name. | |
1530+-----------+--------------------------------+-------+
1531| ``%A`` | Locale's full weekday name. | |
1532+-----------+--------------------------------+-------+
1533| ``%b`` | Locale's abbreviated month | |
1534| | name. | |
1535+-----------+--------------------------------+-------+
1536| ``%B`` | Locale's full month name. | |
1537+-----------+--------------------------------+-------+
1538| ``%c`` | Locale's appropriate date and | |
1539| | time representation. | |
1540+-----------+--------------------------------+-------+
1541| ``%d`` | Day of the month as a decimal | |
1542| | number [01,31]. | |
1543+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001544| ``%f`` | Microsecond as a decimal | \(1) |
1545| | number [0,999999], zero-padded | |
1546| | on the left | |
1547+-----------+--------------------------------+-------+
Christian Heimes895627f2007-12-08 17:28:33 +00001548| ``%H`` | Hour (24-hour clock) as a | |
1549| | decimal number [00,23]. | |
1550+-----------+--------------------------------+-------+
1551| ``%I`` | Hour (12-hour clock) as a | |
1552| | decimal number [01,12]. | |
1553+-----------+--------------------------------+-------+
1554| ``%j`` | Day of the year as a decimal | |
1555| | number [001,366]. | |
1556+-----------+--------------------------------+-------+
1557| ``%m`` | Month as a decimal number | |
1558| | [01,12]. | |
1559+-----------+--------------------------------+-------+
1560| ``%M`` | Minute as a decimal number | |
1561| | [00,59]. | |
1562+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001563| ``%p`` | Locale's equivalent of either | \(2) |
Christian Heimes895627f2007-12-08 17:28:33 +00001564| | AM or PM. | |
1565+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001566| ``%S`` | Second as a decimal number | \(3) |
Christian Heimes895627f2007-12-08 17:28:33 +00001567| | [00,61]. | |
1568+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001569| ``%U`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001570| | (Sunday as the first day of | |
1571| | the week) as a decimal number | |
1572| | [00,53]. All days in a new | |
1573| | year preceding the first | |
1574| | Sunday are considered to be in | |
1575| | week 0. | |
1576+-----------+--------------------------------+-------+
1577| ``%w`` | Weekday as a decimal number | |
1578| | [0(Sunday),6]. | |
1579+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001580| ``%W`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001581| | (Monday as the first day of | |
1582| | the week) as a decimal number | |
1583| | [00,53]. All days in a new | |
1584| | year preceding the first | |
1585| | Monday are considered to be in | |
1586| | week 0. | |
1587+-----------+--------------------------------+-------+
1588| ``%x`` | Locale's appropriate date | |
1589| | representation. | |
1590+-----------+--------------------------------+-------+
1591| ``%X`` | Locale's appropriate time | |
1592| | representation. | |
1593+-----------+--------------------------------+-------+
1594| ``%y`` | Year without century as a | |
1595| | decimal number [00,99]. | |
1596+-----------+--------------------------------+-------+
1597| ``%Y`` | Year with century as a decimal | |
1598| | number. | |
1599+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001600| ``%z`` | UTC offset in the form +HHMM | \(5) |
Christian Heimes895627f2007-12-08 17:28:33 +00001601| | or -HHMM (empty string if the | |
1602| | the object is naive). | |
1603+-----------+--------------------------------+-------+
1604| ``%Z`` | Time zone name (empty string | |
1605| | if the object is naive). | |
1606+-----------+--------------------------------+-------+
1607| ``%%`` | A literal ``'%'`` character. | |
1608+-----------+--------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001609
Christian Heimes895627f2007-12-08 17:28:33 +00001610Notes:
1611
1612(1)
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001613 When used with the :func:`strptime` function, the ``%f`` directive
1614 accepts from one to six digits and zero pads on the right. ``%f`` is
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001615 an extension to the set of format characters in the C standard (but
1616 implemented separately in datetime objects, and therefore always
1617 available).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001618
1619(2)
Christian Heimes895627f2007-12-08 17:28:33 +00001620 When used with the :func:`strptime` function, the ``%p`` directive only affects
1621 the output hour field if the ``%I`` directive is used to parse the hour.
1622
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001623(3)
R. David Murraybd25d332009-04-02 04:50:03 +00001624 The range really is ``0`` to ``61``; according to the Posix standard this
1625 accounts for leap seconds and the (very rare) double leap seconds.
1626 The :mod:`time` module may produce and does accept leap seconds since
1627 it is based on the Posix standard, but the :mod:`datetime` module
1628 does not accept leap seconds in :func:`strptime` input nor will it
1629 produce them in :func:`strftime` output.
Christian Heimes895627f2007-12-08 17:28:33 +00001630
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001631(4)
Christian Heimes895627f2007-12-08 17:28:33 +00001632 When used with the :func:`strptime` function, ``%U`` and ``%W`` are only used in
1633 calculations when the day of the week and the year are specified.
1634
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001635(5)
Christian Heimes895627f2007-12-08 17:28:33 +00001636 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1637 ``%z`` is replaced with the string ``'-0330'``.