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