blob: bcc95309037661f009420bdfa39f9c469be6609e [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
279
Georg Brandl3f043032008-03-22 21:21:57 +0000280Example usage:
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000281
Georg Brandle40a6a82007-12-08 11:23:13 +0000282 >>> from datetime import timedelta
283 >>> year = timedelta(days=365)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000284 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Georg Brandle40a6a82007-12-08 11:23:13 +0000285 ... minutes=50, seconds=600) # adds up to 365 days
Antoine Pitroubcfaf802009-11-25 22:59:36 +0000286 >>> year.total_seconds()
287 31536000.0
Georg Brandle40a6a82007-12-08 11:23:13 +0000288 >>> year == another_year
289 True
290 >>> ten_years = 10 * year
291 >>> ten_years, ten_years.days // 365
292 (datetime.timedelta(3650), 10)
293 >>> nine_years = ten_years - year
294 >>> nine_years, nine_years.days // 365
295 (datetime.timedelta(3285), 9)
296 >>> three_years = nine_years // 3;
297 >>> three_years, three_years.days // 365
298 (datetime.timedelta(1095), 3)
299 >>> abs(three_years - ten_years) == 2 * three_years + year
300 True
301
Georg Brandl8ec7f652007-08-15 14:28:01 +0000302
303.. _datetime-date:
304
305:class:`date` Objects
306---------------------
307
308A :class:`date` object represents a date (year, month and day) in an idealized
309calendar, the current Gregorian calendar indefinitely extended in both
310directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
311called day number 2, and so on. This matches the definition of the "proleptic
312Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
313where it's the base calendar for all computations. See the book for algorithms
314for converting between proleptic Gregorian ordinals and many other calendar
315systems.
316
317
318.. class:: date(year, month, day)
319
320 All arguments are required. Arguments may be ints or longs, in the following
321 ranges:
322
323 * ``MINYEAR <= year <= MAXYEAR``
324 * ``1 <= month <= 12``
325 * ``1 <= day <= number of days in the given month and year``
326
327 If an argument outside those ranges is given, :exc:`ValueError` is raised.
328
329Other constructors, all class methods:
330
331
332.. method:: date.today()
333
334 Return the current local date. This is equivalent to
335 ``date.fromtimestamp(time.time())``.
336
337
338.. method:: date.fromtimestamp(timestamp)
339
340 Return the local date corresponding to the POSIX timestamp, such as is returned
341 by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out
342 of the range of values supported by the platform C :cfunc:`localtime` function.
343 It's common for this to be restricted to years from 1970 through 2038. Note
344 that on non-POSIX systems that include leap seconds in their notion of a
345 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
346
347
348.. method:: date.fromordinal(ordinal)
349
350 Return the date corresponding to the proleptic Gregorian ordinal, where January
351 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
352 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
353 d``.
354
355Class attributes:
356
357
358.. attribute:: date.min
359
360 The earliest representable date, ``date(MINYEAR, 1, 1)``.
361
362
363.. attribute:: date.max
364
365 The latest representable date, ``date(MAXYEAR, 12, 31)``.
366
367
368.. attribute:: date.resolution
369
370 The smallest possible difference between non-equal date objects,
371 ``timedelta(days=1)``.
372
373Instance attributes (read-only):
374
375
376.. attribute:: date.year
377
378 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
379
380
381.. attribute:: date.month
382
383 Between 1 and 12 inclusive.
384
385
386.. attribute:: date.day
387
388 Between 1 and the number of days in the given month of the given year.
389
390Supported operations:
391
392+-------------------------------+----------------------------------------------+
393| Operation | Result |
394+===============================+==============================================+
395| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
396| | from *date1*. (1) |
397+-------------------------------+----------------------------------------------+
398| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
399| | timedelta == date1``. (2) |
400+-------------------------------+----------------------------------------------+
401| ``timedelta = date1 - date2`` | \(3) |
402+-------------------------------+----------------------------------------------+
403| ``date1 < date2`` | *date1* is considered less than *date2* when |
404| | *date1* precedes *date2* in time. (4) |
405+-------------------------------+----------------------------------------------+
406
407Notes:
408
409(1)
410 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
411 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
412 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
413 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
414 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
415
416(2)
417 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
418 isolation can overflow in cases where date1 - timedelta does not.
419 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
420
421(3)
422 This is exact, and cannot overflow. timedelta.seconds and
423 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
424
425(4)
426 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
427 date2.toordinal()``. In order to stop comparison from falling back to the
428 default scheme of comparing object addresses, date comparison normally raises
429 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
430 However, ``NotImplemented`` is returned instead if the other comparand has a
431 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
432 chance at implementing mixed-type comparison. If not, when a :class:`date`
433 object is compared to an object of a different type, :exc:`TypeError` is raised
434 unless the comparison is ``==`` or ``!=``. The latter cases return
435 :const:`False` or :const:`True`, respectively.
436
437Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
438objects are considered to be true.
439
440Instance methods:
441
442
443.. method:: date.replace(year, month, day)
444
445 Return a date with the same value, except for those members given new values by
446 whichever keyword arguments are specified. For example, if ``d == date(2002,
447 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
448
449
450.. method:: date.timetuple()
451
452 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
453 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
454 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
455 d.weekday(), d.toordinal() - date(d.year, 1, 1).toordinal() + 1, -1))``
456
457
458.. method:: date.toordinal()
459
460 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
461 has ordinal 1. For any :class:`date` object *d*,
462 ``date.fromordinal(d.toordinal()) == d``.
463
464
465.. method:: date.weekday()
466
467 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
468 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
469 :meth:`isoweekday`.
470
471
472.. method:: date.isoweekday()
473
474 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
475 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
476 :meth:`weekday`, :meth:`isocalendar`.
477
478
479.. method:: date.isocalendar()
480
481 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
482
483 The ISO calendar is a widely used variant of the Gregorian calendar. See
Mark Dickinson5b544322009-11-03 16:26:14 +0000484 http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
485 explanation.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000486
487 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
488 Monday and ends on a Sunday. The first week of an ISO year is the first
489 (Gregorian) calendar week of a year containing a Thursday. This is called week
490 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
491
492 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
493 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
494 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
495 4).isocalendar() == (2004, 1, 7)``.
496
497
498.. method:: date.isoformat()
499
500 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
501 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
502
503
504.. method:: date.__str__()
505
506 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
507
508
509.. method:: date.ctime()
510
511 Return a string representing the date, for example ``date(2002, 12,
512 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
513 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
514 :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
515 :meth:`date.ctime` does not invoke) conforms to the C standard.
516
517
518.. method:: date.strftime(format)
519
520 Return a string representing the date, controlled by an explicit format string.
521 Format codes referring to hours, minutes or seconds will see 0 values. See
522 section :ref:`strftime-behavior`.
523
Georg Brandle40a6a82007-12-08 11:23:13 +0000524Example of counting days to an event::
525
526 >>> import time
527 >>> from datetime import date
528 >>> today = date.today()
529 >>> today
530 datetime.date(2007, 12, 5)
531 >>> today == date.fromtimestamp(time.time())
532 True
533 >>> my_birthday = date(today.year, 6, 24)
534 >>> if my_birthday < today:
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000535 ... my_birthday = my_birthday.replace(year=today.year + 1)
Georg Brandle40a6a82007-12-08 11:23:13 +0000536 >>> my_birthday
537 datetime.date(2008, 6, 24)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000538 >>> time_to_birthday = abs(my_birthday - today)
Georg Brandle40a6a82007-12-08 11:23:13 +0000539 >>> time_to_birthday.days
540 202
541
Georg Brandl3f043032008-03-22 21:21:57 +0000542Example of working with :class:`date`:
543
544.. doctest::
Georg Brandle40a6a82007-12-08 11:23:13 +0000545
546 >>> from datetime import date
547 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
548 >>> d
549 datetime.date(2002, 3, 11)
550 >>> t = d.timetuple()
Georg Brandl3f043032008-03-22 21:21:57 +0000551 >>> for i in t: # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +0000552 ... print i
553 2002 # year
554 3 # month
555 11 # day
556 0
557 0
558 0
559 0 # weekday (0 = Monday)
560 70 # 70th day in the year
561 -1
562 >>> ic = d.isocalendar()
Georg Brandl3f043032008-03-22 21:21:57 +0000563 >>> for i in ic: # doctest: +SKIP
564 ... print i
Georg Brandle40a6a82007-12-08 11:23:13 +0000565 2002 # ISO year
566 11 # ISO week number
567 1 # ISO day number ( 1 = Monday )
568 >>> d.isoformat()
569 '2002-03-11'
570 >>> d.strftime("%d/%m/%y")
571 '11/03/02'
572 >>> d.strftime("%A %d. %B %Y")
573 'Monday 11. March 2002'
574
Georg Brandl8ec7f652007-08-15 14:28:01 +0000575
576.. _datetime-datetime:
577
578:class:`datetime` Objects
579-------------------------
580
581A :class:`datetime` object is a single object containing all the information
582from a :class:`date` object and a :class:`time` object. Like a :class:`date`
583object, :class:`datetime` assumes the current Gregorian calendar extended in
584both directions; like a time object, :class:`datetime` assumes there are exactly
5853600\*24 seconds in every day.
586
587Constructor:
588
589
590.. class:: datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])
591
592 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
593 instance of a :class:`tzinfo` subclass. The remaining arguments may be ints or
594 longs, in the following ranges:
595
596 * ``MINYEAR <= year <= MAXYEAR``
597 * ``1 <= month <= 12``
598 * ``1 <= day <= number of days in the given month and year``
599 * ``0 <= hour < 24``
600 * ``0 <= minute < 60``
601 * ``0 <= second < 60``
602 * ``0 <= microsecond < 1000000``
603
604 If an argument outside those ranges is given, :exc:`ValueError` is raised.
605
606Other constructors, all class methods:
607
608
609.. method:: datetime.today()
610
611 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
612 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
613 :meth:`fromtimestamp`.
614
615
616.. method:: datetime.now([tz])
617
618 Return the current local date and time. If optional argument *tz* is ``None``
619 or not specified, this is like :meth:`today`, but, if possible, supplies more
620 precision than can be gotten from going through a :func:`time.time` timestamp
621 (for example, this may be possible on platforms supplying the C
622 :cfunc:`gettimeofday` function).
623
624 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
625 current date and time are converted to *tz*'s time zone. In this case the
626 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
627 See also :meth:`today`, :meth:`utcnow`.
628
629
630.. method:: datetime.utcnow()
631
632 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
633 :meth:`now`, but returns the current UTC date and time, as a naive
634 :class:`datetime` object. See also :meth:`now`.
635
636
637.. method:: datetime.fromtimestamp(timestamp[, tz])
638
639 Return the local date and time corresponding to the POSIX timestamp, such as is
640 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
641 specified, the timestamp is converted to the platform's local date and time, and
642 the returned :class:`datetime` object is naive.
643
644 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
645 timestamp is converted to *tz*'s time zone. In this case the result is
646 equivalent to
647 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
648
649 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
650 the range of values supported by the platform C :cfunc:`localtime` or
651 :cfunc:`gmtime` functions. It's common for this to be restricted to years in
652 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
653 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
654 and then it's possible to have two timestamps differing by a second that yield
655 identical :class:`datetime` objects. See also :meth:`utcfromtimestamp`.
656
657
658.. method:: datetime.utcfromtimestamp(timestamp)
659
660 Return the UTC :class:`datetime` corresponding to the POSIX timestamp, with
661 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
662 out of the range of values supported by the platform C :cfunc:`gmtime` function.
663 It's common for this to be restricted to years in 1970 through 2038. See also
664 :meth:`fromtimestamp`.
665
666
667.. method:: datetime.fromordinal(ordinal)
668
669 Return the :class:`datetime` corresponding to the proleptic Gregorian ordinal,
670 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
671 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
672 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
673
674
675.. method:: datetime.combine(date, time)
676
677 Return a new :class:`datetime` object whose date members are equal to the given
678 :class:`date` object's, and whose time and :attr:`tzinfo` members are equal to
679 the given :class:`time` object's. For any :class:`datetime` object *d*, ``d ==
680 datetime.combine(d.date(), d.timetz())``. If date is a :class:`datetime`
681 object, its time and :attr:`tzinfo` members are ignored.
682
683
684.. method:: datetime.strptime(date_string, format)
685
686 Return a :class:`datetime` corresponding to *date_string*, parsed according to
687 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
688 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
689 can't be parsed by :func:`time.strptime` or if it returns a value which isn't a
690 time tuple.
691
692 .. versionadded:: 2.5
693
694Class attributes:
695
696
697.. attribute:: datetime.min
698
699 The earliest representable :class:`datetime`, ``datetime(MINYEAR, 1, 1,
700 tzinfo=None)``.
701
702
703.. attribute:: datetime.max
704
705 The latest representable :class:`datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
706 59, 999999, tzinfo=None)``.
707
708
709.. attribute:: datetime.resolution
710
711 The smallest possible difference between non-equal :class:`datetime` objects,
712 ``timedelta(microseconds=1)``.
713
714Instance attributes (read-only):
715
716
717.. attribute:: datetime.year
718
719 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
720
721
722.. attribute:: datetime.month
723
724 Between 1 and 12 inclusive.
725
726
727.. attribute:: datetime.day
728
729 Between 1 and the number of days in the given month of the given year.
730
731
732.. attribute:: datetime.hour
733
734 In ``range(24)``.
735
736
737.. attribute:: datetime.minute
738
739 In ``range(60)``.
740
741
742.. attribute:: datetime.second
743
744 In ``range(60)``.
745
746
747.. attribute:: datetime.microsecond
748
749 In ``range(1000000)``.
750
751
752.. attribute:: datetime.tzinfo
753
754 The object passed as the *tzinfo* argument to the :class:`datetime` constructor,
755 or ``None`` if none was passed.
756
757Supported operations:
758
759+---------------------------------------+-------------------------------+
760| Operation | Result |
761+=======================================+===============================+
762| ``datetime2 = datetime1 + timedelta`` | \(1) |
763+---------------------------------------+-------------------------------+
764| ``datetime2 = datetime1 - timedelta`` | \(2) |
765+---------------------------------------+-------------------------------+
766| ``timedelta = datetime1 - datetime2`` | \(3) |
767+---------------------------------------+-------------------------------+
768| ``datetime1 < datetime2`` | Compares :class:`datetime` to |
769| | :class:`datetime`. (4) |
770+---------------------------------------+-------------------------------+
771
772(1)
773 datetime2 is a duration of timedelta removed from datetime1, moving forward in
774 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
775 result has the same :attr:`tzinfo` member as the input datetime, and datetime2 -
776 datetime1 == timedelta after. :exc:`OverflowError` is raised if datetime2.year
777 would be smaller than :const:`MINYEAR` or larger than :const:`MAXYEAR`. Note
778 that no time zone adjustments are done even if the input is an aware object.
779
780(2)
781 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
782 addition, the result has the same :attr:`tzinfo` member as the input datetime,
783 and no time zone adjustments are done even if the input is aware. This isn't
784 quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation
785 can overflow in cases where datetime1 - timedelta does not.
786
787(3)
788 Subtraction of a :class:`datetime` from a :class:`datetime` is defined only if
789 both operands are naive, or if both are aware. If one is aware and the other is
790 naive, :exc:`TypeError` is raised.
791
792 If both are naive, or both are aware and have the same :attr:`tzinfo` member,
793 the :attr:`tzinfo` members are ignored, and the result is a :class:`timedelta`
794 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
795 are done in this case.
796
797 If both are aware and have different :attr:`tzinfo` members, ``a-b`` acts as if
798 *a* and *b* were first converted to naive UTC datetimes first. The result is
799 ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) -
800 b.utcoffset())`` except that the implementation never overflows.
801
802(4)
803 *datetime1* is considered less than *datetime2* when *datetime1* precedes
804 *datetime2* in time.
805
806 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
807 If both comparands are aware, and have the same :attr:`tzinfo` member, the
808 common :attr:`tzinfo` member is ignored and the base datetimes are compared. If
809 both comparands are aware and have different :attr:`tzinfo` members, the
810 comparands are first adjusted by subtracting their UTC offsets (obtained from
811 ``self.utcoffset()``).
812
813 .. note::
814
815 In order to stop comparison from falling back to the default scheme of comparing
816 object addresses, datetime comparison normally raises :exc:`TypeError` if the
817 other comparand isn't also a :class:`datetime` object. However,
818 ``NotImplemented`` is returned instead if the other comparand has a
819 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
820 chance at implementing mixed-type comparison. If not, when a :class:`datetime`
821 object is compared to an object of a different type, :exc:`TypeError` is raised
822 unless the comparison is ``==`` or ``!=``. The latter cases return
823 :const:`False` or :const:`True`, respectively.
824
825:class:`datetime` objects can be used as dictionary keys. In Boolean contexts,
826all :class:`datetime` objects are considered to be true.
827
828Instance methods:
829
830
831.. method:: datetime.date()
832
833 Return :class:`date` object with same year, month and day.
834
835
836.. method:: datetime.time()
837
838 Return :class:`time` object with same hour, minute, second and microsecond.
839 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
840
841
842.. method:: datetime.timetz()
843
844 Return :class:`time` object with same hour, minute, second, microsecond, and
845 tzinfo members. See also method :meth:`time`.
846
847
848.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
849
850 Return a datetime with the same members, except for those members given new
851 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
852 can be specified to create a naive datetime from an aware datetime with no
853 conversion of date and time members.
854
855
856.. method:: datetime.astimezone(tz)
857
858 Return a :class:`datetime` object with new :attr:`tzinfo` member *tz*, adjusting
859 the date and time members so the result is the same UTC time as *self*, but in
860 *tz*'s local time.
861
862 *tz* must be an instance of a :class:`tzinfo` subclass, and its
863 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
864 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
865 not return ``None``).
866
867 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
868 adjustment of date or time members is performed. Else the result is local time
869 in time zone *tz*, representing the same UTC time as *self*: after ``astz =
870 dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have the same date
871 and time members as ``dt - dt.utcoffset()``. The discussion of class
872 :class:`tzinfo` explains the cases at Daylight Saving Time transition boundaries
873 where this cannot be achieved (an issue only if *tz* models both standard and
874 daylight time).
875
876 If you merely want to attach a time zone object *tz* to a datetime *dt* without
877 adjustment of date and time members, use ``dt.replace(tzinfo=tz)``. If you
878 merely want to remove the time zone object from an aware datetime *dt* without
879 conversion of date and time members, use ``dt.replace(tzinfo=None)``.
880
881 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
882 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
883 Ignoring error cases, :meth:`astimezone` acts like::
884
885 def astimezone(self, tz):
886 if self.tzinfo is tz:
887 return self
888 # Convert self to UTC, and attach the new time zone object.
889 utc = (self - self.utcoffset()).replace(tzinfo=tz)
890 # Convert from UTC to tz's local time.
891 return tz.fromutc(utc)
892
893
894.. method:: datetime.utcoffset()
895
896 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
897 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
898 return ``None``, or a :class:`timedelta` object representing a whole number of
899 minutes with magnitude less than one day.
900
901
902.. method:: datetime.dst()
903
904 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
905 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
906 ``None``, or a :class:`timedelta` object representing a whole number of minutes
907 with magnitude less than one day.
908
909
910.. method:: datetime.tzname()
911
912 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
913 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
914 ``None`` or a string object,
915
916
917.. method:: datetime.timetuple()
918
919 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
920 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
921 d.hour, d.minute, d.second, d.weekday(), d.toordinal() - date(d.year, 1,
922 1).toordinal() + 1, dst))`` The :attr:`tm_isdst` flag of the result is set
923 according to the :meth:`dst` method: :attr:`tzinfo` is ``None`` or :meth:`dst`
924 returns ``None``, :attr:`tm_isdst` is set to ``-1``; else if :meth:`dst`
925 returns a non-zero value, :attr:`tm_isdst` is set to ``1``; else ``tm_isdst`` is
926 set to ``0``.
927
928
929.. method:: datetime.utctimetuple()
930
931 If :class:`datetime` instance *d* is naive, this is the same as
932 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
933 ``d.dst()`` returns. DST is never in effect for a UTC time.
934
935 If *d* is aware, *d* is normalized to UTC time, by subtracting
936 ``d.utcoffset()``, and a :class:`time.struct_time` for the normalized time is
937 returned. :attr:`tm_isdst` is forced to 0. Note that the result's
938 :attr:`tm_year` member may be :const:`MINYEAR`\ -1 or :const:`MAXYEAR`\ +1, if
939 *d*.year was ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
940 boundary.
941
942
943.. method:: datetime.toordinal()
944
945 Return the proleptic Gregorian ordinal of the date. The same as
946 ``self.date().toordinal()``.
947
948
949.. method:: datetime.weekday()
950
951 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
952 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
953
954
955.. method:: datetime.isoweekday()
956
957 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
958 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
959 :meth:`isocalendar`.
960
961
962.. method:: datetime.isocalendar()
963
964 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
965 ``self.date().isocalendar()``.
966
967
968.. method:: datetime.isoformat([sep])
969
970 Return a string representing the date and time in ISO 8601 format,
971 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
972 YYYY-MM-DDTHH:MM:SS
973
974 If :meth:`utcoffset` does not return ``None``, a 6-character string is
975 appended, giving the UTC offset in (signed) hours and minutes:
976 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
977 YYYY-MM-DDTHH:MM:SS+HH:MM
978
979 The optional argument *sep* (default ``'T'``) is a one-character separator,
Georg Brandl3f043032008-03-22 21:21:57 +0000980 placed between the date and time portions of the result. For example,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000981
982 >>> from datetime import tzinfo, timedelta, datetime
983 >>> class TZ(tzinfo):
984 ... def utcoffset(self, dt): return timedelta(minutes=-399)
985 ...
986 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
987 '2002-12-25 00:00:00-06:39'
988
989
990.. method:: datetime.__str__()
991
992 For a :class:`datetime` instance *d*, ``str(d)`` is equivalent to
993 ``d.isoformat(' ')``.
994
995
996.. method:: datetime.ctime()
997
998 Return a string representing the date and time, for example ``datetime(2002, 12,
999 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1000 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
1001 native C :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
1002 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1003
1004
1005.. method:: datetime.strftime(format)
1006
1007 Return a string representing the date and time, controlled by an explicit format
1008 string. See section :ref:`strftime-behavior`.
1009
Georg Brandl3f043032008-03-22 21:21:57 +00001010Examples of working with datetime objects:
1011
1012.. doctest::
1013
Georg Brandle40a6a82007-12-08 11:23:13 +00001014 >>> from datetime import datetime, date, time
1015 >>> # Using datetime.combine()
1016 >>> d = date(2005, 7, 14)
1017 >>> t = time(12, 30)
1018 >>> datetime.combine(d, t)
1019 datetime.datetime(2005, 7, 14, 12, 30)
1020 >>> # Using datetime.now() or datetime.utcnow()
Georg Brandl3f043032008-03-22 21:21:57 +00001021 >>> datetime.now() # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +00001022 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Georg Brandl3f043032008-03-22 21:21:57 +00001023 >>> datetime.utcnow() # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +00001024 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1025 >>> # Using datetime.strptime()
1026 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1027 >>> dt
1028 datetime.datetime(2006, 11, 21, 16, 30)
1029 >>> # Using datetime.timetuple() to get tuple of all attributes
1030 >>> tt = dt.timetuple()
Georg Brandl3f043032008-03-22 21:21:57 +00001031 >>> for it in tt: # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +00001032 ... print it
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001033 ...
Georg Brandle40a6a82007-12-08 11:23:13 +00001034 2006 # year
1035 11 # month
1036 21 # day
1037 16 # hour
1038 30 # minute
1039 0 # second
1040 1 # weekday (0 = Monday)
1041 325 # number of days since 1st January
1042 -1 # dst - method tzinfo.dst() returned None
1043 >>> # Date in ISO format
1044 >>> ic = dt.isocalendar()
Georg Brandl3f043032008-03-22 21:21:57 +00001045 >>> for it in ic: # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +00001046 ... print it
1047 ...
1048 2006 # ISO year
1049 47 # ISO week
1050 2 # ISO weekday
1051 >>> # Formatting datetime
1052 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1053 'Tuesday, 21. November 2006 04:30PM'
1054
Georg Brandl3f043032008-03-22 21:21:57 +00001055Using datetime with tzinfo:
Georg Brandle40a6a82007-12-08 11:23:13 +00001056
1057 >>> from datetime import timedelta, datetime, tzinfo
1058 >>> class GMT1(tzinfo):
1059 ... def __init__(self): # DST starts last Sunday in March
1060 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1061 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001062 ... d = datetime(dt.year, 11, 1)
Georg Brandle40a6a82007-12-08 11:23:13 +00001063 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1064 ... def utcoffset(self, dt):
1065 ... return timedelta(hours=1) + self.dst(dt)
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001066 ... def dst(self, dt):
Georg Brandle40a6a82007-12-08 11:23:13 +00001067 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1068 ... return timedelta(hours=1)
1069 ... else:
1070 ... return timedelta(0)
1071 ... def tzname(self,dt):
1072 ... return "GMT +1"
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001073 ...
Georg Brandle40a6a82007-12-08 11:23:13 +00001074 >>> class GMT2(tzinfo):
1075 ... def __init__(self):
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001076 ... d = datetime(dt.year, 4, 1)
Georg Brandle40a6a82007-12-08 11:23:13 +00001077 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001078 ... d = datetime(dt.year, 11, 1)
Georg Brandle40a6a82007-12-08 11:23:13 +00001079 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1080 ... def utcoffset(self, dt):
1081 ... return timedelta(hours=1) + self.dst(dt)
1082 ... def dst(self, dt):
1083 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1084 ... return timedelta(hours=2)
1085 ... else:
1086 ... return timedelta(0)
1087 ... def tzname(self,dt):
1088 ... return "GMT +2"
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001089 ...
Georg Brandle40a6a82007-12-08 11:23:13 +00001090 >>> gmt1 = GMT1()
1091 >>> # Daylight Saving Time
1092 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1093 >>> dt1.dst()
1094 datetime.timedelta(0)
1095 >>> dt1.utcoffset()
1096 datetime.timedelta(0, 3600)
1097 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1098 >>> dt2.dst()
1099 datetime.timedelta(0, 3600)
1100 >>> dt2.utcoffset()
1101 datetime.timedelta(0, 7200)
1102 >>> # Convert datetime to another time zone
1103 >>> dt3 = dt2.astimezone(GMT2())
1104 >>> dt3 # doctest: +ELLIPSIS
1105 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1106 >>> dt2 # doctest: +ELLIPSIS
1107 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1108 >>> dt2.utctimetuple() == dt3.utctimetuple()
1109 True
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001110
Georg Brandle40a6a82007-12-08 11:23:13 +00001111
Georg Brandl8ec7f652007-08-15 14:28:01 +00001112
1113.. _datetime-time:
1114
1115:class:`time` Objects
1116---------------------
1117
1118A time object represents a (local) time of day, independent of any particular
1119day, and subject to adjustment via a :class:`tzinfo` object.
1120
1121
1122.. class:: time(hour[, minute[, second[, microsecond[, tzinfo]]]])
1123
1124 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
1125 :class:`tzinfo` subclass. The remaining arguments may be ints or longs, in the
1126 following ranges:
1127
1128 * ``0 <= hour < 24``
1129 * ``0 <= minute < 60``
1130 * ``0 <= second < 60``
1131 * ``0 <= microsecond < 1000000``.
1132
1133 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1134 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1135
1136Class attributes:
1137
1138
1139.. attribute:: time.min
1140
1141 The earliest representable :class:`time`, ``time(0, 0, 0, 0)``.
1142
1143
1144.. attribute:: time.max
1145
1146 The latest representable :class:`time`, ``time(23, 59, 59, 999999)``.
1147
1148
1149.. attribute:: time.resolution
1150
1151 The smallest possible difference between non-equal :class:`time` objects,
1152 ``timedelta(microseconds=1)``, although note that arithmetic on :class:`time`
1153 objects is not supported.
1154
1155Instance attributes (read-only):
1156
1157
1158.. attribute:: time.hour
1159
1160 In ``range(24)``.
1161
1162
1163.. attribute:: time.minute
1164
1165 In ``range(60)``.
1166
1167
1168.. attribute:: time.second
1169
1170 In ``range(60)``.
1171
1172
1173.. attribute:: time.microsecond
1174
1175 In ``range(1000000)``.
1176
1177
1178.. attribute:: time.tzinfo
1179
1180 The object passed as the tzinfo argument to the :class:`time` constructor, or
1181 ``None`` if none was passed.
1182
1183Supported operations:
1184
1185* comparison of :class:`time` to :class:`time`, where *a* is considered less
1186 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1187 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
1188 the same :attr:`tzinfo` member, the common :attr:`tzinfo` member is ignored and
1189 the base times are compared. If both comparands are aware and have different
1190 :attr:`tzinfo` members, the comparands are first adjusted by subtracting their
1191 UTC offsets (obtained from ``self.utcoffset()``). In order to stop mixed-type
1192 comparisons from falling back to the default comparison by object address, when
1193 a :class:`time` object is compared to an object of a different type,
1194 :exc:`TypeError` is raised unless the comparison is ``==`` or ``!=``. The
1195 latter cases return :const:`False` or :const:`True`, respectively.
1196
1197* hash, use as dict key
1198
1199* efficient pickling
1200
1201* in Boolean contexts, a :class:`time` object is considered to be true if and
1202 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1203 ``0`` if that's ``None``), the result is non-zero.
1204
1205Instance methods:
1206
1207
1208.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1209
1210 Return a :class:`time` with the same value, except for those members given new
1211 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
1212 can be specified to create a naive :class:`time` from an aware :class:`time`,
1213 without conversion of the time members.
1214
1215
1216.. method:: time.isoformat()
1217
1218 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1219 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1220 6-character string is appended, giving the UTC offset in (signed) hours and
1221 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1222
1223
1224.. method:: time.__str__()
1225
1226 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1227
1228
1229.. method:: time.strftime(format)
1230
1231 Return a string representing the time, controlled by an explicit format string.
1232 See section :ref:`strftime-behavior`.
1233
1234
1235.. method:: time.utcoffset()
1236
1237 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1238 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1239 return ``None`` or a :class:`timedelta` object representing a whole number of
1240 minutes with magnitude less than one day.
1241
1242
1243.. method:: time.dst()
1244
1245 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1246 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1247 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1248 with magnitude less than one day.
1249
1250
1251.. method:: time.tzname()
1252
1253 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1254 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1255 return ``None`` or a string object.
1256
Georg Brandl3f043032008-03-22 21:21:57 +00001257Example:
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001258
Georg Brandle40a6a82007-12-08 11:23:13 +00001259 >>> from datetime import time, tzinfo
1260 >>> class GMT1(tzinfo):
1261 ... def utcoffset(self, dt):
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001262 ... return timedelta(hours=1)
1263 ... def dst(self, dt):
Georg Brandle40a6a82007-12-08 11:23:13 +00001264 ... return timedelta(0)
1265 ... def tzname(self,dt):
1266 ... return "Europe/Prague"
1267 ...
1268 >>> t = time(12, 10, 30, tzinfo=GMT1())
1269 >>> t # doctest: +ELLIPSIS
1270 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1271 >>> gmt = GMT1()
1272 >>> t.isoformat()
1273 '12:10:30+01:00'
1274 >>> t.dst()
1275 datetime.timedelta(0)
1276 >>> t.tzname()
1277 'Europe/Prague'
1278 >>> t.strftime("%H:%M:%S %Z")
1279 '12:10:30 Europe/Prague'
1280
Georg Brandl8ec7f652007-08-15 14:28:01 +00001281
1282.. _datetime-tzinfo:
1283
1284:class:`tzinfo` Objects
1285-----------------------
1286
Brett Cannon8aa2c6c2009-01-29 00:54:32 +00001287:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl8ec7f652007-08-15 14:28:01 +00001288instantiated directly. You need to derive a concrete subclass, and (at least)
1289supply implementations of the standard :class:`tzinfo` methods needed by the
1290:class:`datetime` methods you use. The :mod:`datetime` module does not supply
1291any concrete subclasses of :class:`tzinfo`.
1292
1293An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1294constructors for :class:`datetime` and :class:`time` objects. The latter objects
1295view their members as being in local time, and the :class:`tzinfo` object
1296supports methods revealing offset of local time from UTC, the name of the time
1297zone, and DST offset, all relative to a date or time object passed to them.
1298
1299Special requirement for pickling: A :class:`tzinfo` subclass must have an
1300:meth:`__init__` method that can be called with no arguments, else it can be
1301pickled but possibly not unpickled again. This is a technical requirement that
1302may be relaxed in the future.
1303
1304A concrete subclass of :class:`tzinfo` may need to implement the following
1305methods. Exactly which methods are needed depends on the uses made of aware
1306:mod:`datetime` objects. If in doubt, simply implement all of them.
1307
1308
1309.. method:: tzinfo.utcoffset(self, dt)
1310
1311 Return offset of local time from UTC, in minutes east of UTC. If local time is
1312 west of UTC, this should be negative. Note that this is intended to be the
1313 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1314 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1315 the UTC offset isn't known, return ``None``. Else the value returned must be a
1316 :class:`timedelta` object specifying a whole number of minutes in the range
1317 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1318 than one day). Most implementations of :meth:`utcoffset` will probably look
1319 like one of these two::
1320
1321 return CONSTANT # fixed-offset class
1322 return CONSTANT + self.dst(dt) # daylight-aware class
1323
1324 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1325 ``None`` either.
1326
1327 The default implementation of :meth:`utcoffset` raises
1328 :exc:`NotImplementedError`.
1329
1330
1331.. method:: tzinfo.dst(self, dt)
1332
1333 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1334 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1335 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1336 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1337 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1338 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1339 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
1340 member's :meth:`dst` method to determine how the :attr:`tm_isdst` flag should be
1341 set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for DST changes
1342 when crossing time zones.
1343
1344 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1345 daylight times must be consistent in this sense:
1346
1347 ``tz.utcoffset(dt) - tz.dst(dt)``
1348
1349 must return the same result for every :class:`datetime` *dt* with ``dt.tzinfo ==
1350 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1351 zone's "standard offset", which should not depend on the date or the time, but
1352 only on geographic location. The implementation of :meth:`datetime.astimezone`
1353 relies on this, but cannot detect violations; it's the programmer's
1354 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1355 this, it may be able to override the default implementation of
1356 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1357
1358 Most implementations of :meth:`dst` will probably look like one of these two::
1359
1360 def dst(self):
1361 # a fixed-offset class: doesn't account for DST
1362 return timedelta(0)
1363
1364 or ::
1365
1366 def dst(self):
1367 # Code to set dston and dstoff to the time zone's DST
1368 # transition times based on the input dt.year, and expressed
1369 # in standard local time. Then
1370
1371 if dston <= dt.replace(tzinfo=None) < dstoff:
1372 return timedelta(hours=1)
1373 else:
1374 return timedelta(0)
1375
1376 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1377
1378
1379.. method:: tzinfo.tzname(self, dt)
1380
1381 Return the time zone name corresponding to the :class:`datetime` object *dt*, as
1382 a string. Nothing about string names is defined by the :mod:`datetime` module,
1383 and there's no requirement that it mean anything in particular. For example,
1384 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1385 valid replies. Return ``None`` if a string name isn't known. Note that this is
1386 a method rather than a fixed string primarily because some :class:`tzinfo`
1387 subclasses will wish to return different names depending on the specific value
1388 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1389 daylight time.
1390
1391 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1392
1393These methods are called by a :class:`datetime` or :class:`time` object, in
1394response to their methods of the same names. A :class:`datetime` object passes
1395itself as the argument, and a :class:`time` object passes ``None`` as the
1396argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
1397accept a *dt* argument of ``None``, or of class :class:`datetime`.
1398
1399When ``None`` is passed, it's up to the class designer to decide the best
1400response. For example, returning ``None`` is appropriate if the class wishes to
1401say that time objects don't participate in the :class:`tzinfo` protocols. It
1402may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1403there is no other convention for discovering the standard offset.
1404
1405When a :class:`datetime` object is passed in response to a :class:`datetime`
1406method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1407rely on this, unless user code calls :class:`tzinfo` methods directly. The
1408intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1409time, and not need worry about objects in other timezones.
1410
1411There is one more :class:`tzinfo` method that a subclass may wish to override:
1412
1413
1414.. method:: tzinfo.fromutc(self, dt)
1415
1416 This is called from the default :class:`datetime.astimezone()` implementation.
1417 When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members
1418 are to be viewed as expressing a UTC time. The purpose of :meth:`fromutc` is to
1419 adjust the date and time members, returning an equivalent datetime in *self*'s
1420 local time.
1421
1422 Most :class:`tzinfo` subclasses should be able to inherit the default
1423 :meth:`fromutc` implementation without problems. It's strong enough to handle
1424 fixed-offset time zones, and time zones accounting for both standard and
1425 daylight time, and the latter even if the DST transition times differ in
1426 different years. An example of a time zone the default :meth:`fromutc`
1427 implementation may not handle correctly in all cases is one where the standard
1428 offset (from UTC) depends on the specific date and time passed, which can happen
1429 for political reasons. The default implementations of :meth:`astimezone` and
1430 :meth:`fromutc` may not produce the result you want if the result is one of the
1431 hours straddling the moment the standard offset changes.
1432
1433 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1434 like::
1435
1436 def fromutc(self, dt):
1437 # raise ValueError error if dt.tzinfo is not self
1438 dtoff = dt.utcoffset()
1439 dtdst = dt.dst()
1440 # raise ValueError if dtoff is None or dtdst is None
1441 delta = dtoff - dtdst # this is self's standard offset
1442 if delta:
1443 dt += delta # convert to standard local time
1444 dtdst = dt.dst()
1445 # raise ValueError if dtdst is None
1446 if dtdst:
1447 return dt + dtdst
1448 else:
1449 return dt
1450
1451Example :class:`tzinfo` classes:
1452
1453.. literalinclude:: ../includes/tzinfo-examples.py
1454
1455
1456Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1457subclass accounting for both standard and daylight time, at the DST transition
1458points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
1459minute after 1:59 (EST) on the first Sunday in April, and ends the minute after
14601:59 (EDT) on the last Sunday in October::
1461
1462 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1463 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1464 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1465
1466 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1467
1468 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1469
1470When DST starts (the "start" line), the local wall clock leaps from 1:59 to
14713:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1472``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1473begins. In order for :meth:`astimezone` to make this guarantee, the
1474:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1475Eastern) to be in daylight time.
1476
1477When DST ends (the "end" line), there's a potentially worse problem: there's an
1478hour that can't be spelled unambiguously in local wall time: the last hour of
1479daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1480daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1481to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1482:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1483hours into the same local hour then. In the Eastern example, UTC times of the
1484form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1485:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1486consider times in the "repeated hour" to be in standard time. This is easily
1487arranged, as in the example, by expressing DST switch times in the time zone's
1488standard local time.
1489
1490Applications that can't bear such ambiguities should avoid using hybrid
1491:class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any
1492other fixed-offset :class:`tzinfo` subclass (such as a class representing only
1493EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001494
Georg Brandl8ec7f652007-08-15 14:28:01 +00001495
1496.. _strftime-behavior:
1497
1498:meth:`strftime` Behavior
1499-------------------------
1500
1501:class:`date`, :class:`datetime`, and :class:`time` objects all support a
1502``strftime(format)`` method, to create a string representing the time under the
1503control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1504acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1505although not all objects support a :meth:`timetuple` method.
1506
1507For :class:`time` objects, the format codes for year, month, and day should not
1508be used, as time objects have no such values. If they're used anyway, ``1900``
1509is substituted for the year, and ``0`` for the month and day.
1510
Skip Montanarofc070d22008-03-15 16:04:45 +00001511For :class:`date` objects, the format codes for hours, minutes, seconds, and
1512microseconds should not be used, as :class:`date` objects have no such
1513values. If they're used anyway, ``0`` is substituted for them.
1514
Skip Montanarofc070d22008-03-15 16:04:45 +00001515.. versionadded:: 2.6
Georg Brandlaf9a97b2009-01-18 14:41:52 +00001516 :class:`time` and :class:`datetime` objects support a ``%f`` format code
1517 which expands to the number of microseconds in the object, zero-padded on
1518 the left to six places.
Skip Montanarofc070d22008-03-15 16:04:45 +00001519
1520For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1521strings.
1522
1523For an aware object:
1524
1525``%z``
1526 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1527 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1528 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1529 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1530 replaced with the string ``'-0330'``.
1531
1532``%Z``
1533 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1534 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001535
Georg Brandl8ec7f652007-08-15 14:28:01 +00001536The full set of format codes supported varies across platforms, because Python
1537calls the platform C library's :func:`strftime` function, and platform
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001538variations are common.
Georg Brandle40a6a82007-12-08 11:23:13 +00001539
1540The following is a list of all the format codes that the C standard (1989
1541version) requires, and these work on all platforms with a standard C
1542implementation. Note that the 1999 version of the C standard added additional
1543format codes.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001544
1545The exact range of years for which :meth:`strftime` works also varies across
1546platforms. Regardless of platform, years before 1900 cannot be used.
1547
Georg Brandle40a6a82007-12-08 11:23:13 +00001548+-----------+--------------------------------+-------+
1549| Directive | Meaning | Notes |
1550+===========+================================+=======+
1551| ``%a`` | Locale's abbreviated weekday | |
1552| | name. | |
1553+-----------+--------------------------------+-------+
1554| ``%A`` | Locale's full weekday name. | |
1555+-----------+--------------------------------+-------+
1556| ``%b`` | Locale's abbreviated month | |
1557| | name. | |
1558+-----------+--------------------------------+-------+
1559| ``%B`` | Locale's full month name. | |
1560+-----------+--------------------------------+-------+
1561| ``%c`` | Locale's appropriate date and | |
1562| | time representation. | |
1563+-----------+--------------------------------+-------+
1564| ``%d`` | Day of the month as a decimal | |
1565| | number [01,31]. | |
1566+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001567| ``%f`` | Microsecond as a decimal | \(1) |
1568| | number [0,999999], zero-padded | |
1569| | on the left | |
1570+-----------+--------------------------------+-------+
Georg Brandle40a6a82007-12-08 11:23:13 +00001571| ``%H`` | Hour (24-hour clock) as a | |
1572| | decimal number [00,23]. | |
1573+-----------+--------------------------------+-------+
1574| ``%I`` | Hour (12-hour clock) as a | |
1575| | decimal number [01,12]. | |
1576+-----------+--------------------------------+-------+
1577| ``%j`` | Day of the year as a decimal | |
1578| | number [001,366]. | |
1579+-----------+--------------------------------+-------+
1580| ``%m`` | Month as a decimal number | |
1581| | [01,12]. | |
1582+-----------+--------------------------------+-------+
1583| ``%M`` | Minute as a decimal number | |
1584| | [00,59]. | |
1585+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001586| ``%p`` | Locale's equivalent of either | \(2) |
Georg Brandle40a6a82007-12-08 11:23:13 +00001587| | AM or PM. | |
1588+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001589| ``%S`` | Second as a decimal number | \(3) |
Georg Brandle40a6a82007-12-08 11:23:13 +00001590| | [00,61]. | |
1591+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001592| ``%U`` | Week number of the year | \(4) |
Georg Brandle40a6a82007-12-08 11:23:13 +00001593| | (Sunday as the first day of | |
1594| | the week) as a decimal number | |
1595| | [00,53]. All days in a new | |
1596| | year preceding the first | |
1597| | Sunday are considered to be in | |
1598| | week 0. | |
1599+-----------+--------------------------------+-------+
1600| ``%w`` | Weekday as a decimal number | |
1601| | [0(Sunday),6]. | |
1602+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001603| ``%W`` | Week number of the year | \(4) |
Georg Brandle40a6a82007-12-08 11:23:13 +00001604| | (Monday as the first day of | |
1605| | the week) as a decimal number | |
1606| | [00,53]. All days in a new | |
1607| | year preceding the first | |
1608| | Monday are considered to be in | |
1609| | week 0. | |
1610+-----------+--------------------------------+-------+
1611| ``%x`` | Locale's appropriate date | |
1612| | representation. | |
1613+-----------+--------------------------------+-------+
1614| ``%X`` | Locale's appropriate time | |
1615| | representation. | |
1616+-----------+--------------------------------+-------+
1617| ``%y`` | Year without century as a | |
1618| | decimal number [00,99]. | |
1619+-----------+--------------------------------+-------+
1620| ``%Y`` | Year with century as a decimal | |
1621| | number. | |
1622+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001623| ``%z`` | UTC offset in the form +HHMM | \(5) |
Georg Brandle40a6a82007-12-08 11:23:13 +00001624| | or -HHMM (empty string if the | |
1625| | the object is naive). | |
1626+-----------+--------------------------------+-------+
1627| ``%Z`` | Time zone name (empty string | |
1628| | if the object is naive). | |
1629+-----------+--------------------------------+-------+
1630| ``%%`` | A literal ``'%'`` character. | |
1631+-----------+--------------------------------+-------+
Georg Brandl8ec7f652007-08-15 14:28:01 +00001632
Georg Brandle40a6a82007-12-08 11:23:13 +00001633Notes:
1634
1635(1)
Skip Montanarofc070d22008-03-15 16:04:45 +00001636 When used with the :func:`strptime` function, the ``%f`` directive
1637 accepts from one to six digits and zero pads on the right. ``%f`` is
Georg Brandlaf9a97b2009-01-18 14:41:52 +00001638 an extension to the set of format characters in the C standard (but
1639 implemented separately in datetime objects, and therefore always
1640 available).
Skip Montanarofc070d22008-03-15 16:04:45 +00001641
1642(2)
Georg Brandle40a6a82007-12-08 11:23:13 +00001643 When used with the :func:`strptime` function, the ``%p`` directive only affects
1644 the output hour field if the ``%I`` directive is used to parse the hour.
1645
Skip Montanarofc070d22008-03-15 16:04:45 +00001646(3)
R. David Murrayd56bab42009-04-02 04:34:04 +00001647 The range really is ``0`` to ``61``; according to the Posix standard this
1648 accounts for leap seconds and the (very rare) double leap seconds.
1649 The :mod:`time` module may produce and does accept leap seconds since
1650 it is based on the Posix standard, but the :mod:`datetime` module
1651 does not accept leap seconds in :func:`strptime` input nor will it
1652 produce them in :func:`strftime` output.
Georg Brandle40a6a82007-12-08 11:23:13 +00001653
Skip Montanarofc070d22008-03-15 16:04:45 +00001654(4)
Georg Brandle40a6a82007-12-08 11:23:13 +00001655 When used with the :func:`strptime` function, ``%U`` and ``%W`` are only used in
1656 calculations when the day of the week and the year are specified.
1657
Skip Montanarofc070d22008-03-15 16:04:45 +00001658(5)
Georg Brandle40a6a82007-12-08 11:23:13 +00001659 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1660 ``%z`` is replaced with the string ``'-0330'``.