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