blob: 68ae586037253cba2ca289e37085a811e077a33a [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
Mark Dickinsonf964ac22009-11-03 16:29:10 +0000472 http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
473 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000474
475 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
476 Monday and ends on a Sunday. The first week of an ISO year is the first
477 (Gregorian) calendar week of a year containing a Thursday. This is called week
478 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
479
480 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
481 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
482 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
483 4).isocalendar() == (2004, 1, 7)``.
484
485
486.. method:: date.isoformat()
487
488 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
489 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
490
491
492.. method:: date.__str__()
493
494 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
495
496
497.. method:: date.ctime()
498
499 Return a string representing the date, for example ``date(2002, 12,
500 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
501 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
502 :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
503 :meth:`date.ctime` does not invoke) conforms to the C standard.
504
505
506.. method:: date.strftime(format)
507
508 Return a string representing the date, controlled by an explicit format string.
509 Format codes referring to hours, minutes or seconds will see 0 values. See
510 section :ref:`strftime-behavior`.
511
Christian Heimes895627f2007-12-08 17:28:33 +0000512Example of counting days to an event::
513
514 >>> import time
515 >>> from datetime import date
516 >>> today = date.today()
517 >>> today
518 datetime.date(2007, 12, 5)
519 >>> today == date.fromtimestamp(time.time())
520 True
521 >>> my_birthday = date(today.year, 6, 24)
522 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000523 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000524 >>> my_birthday
525 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000526 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000527 >>> time_to_birthday.days
528 202
529
Christian Heimesfe337bf2008-03-23 21:54:12 +0000530Example of working with :class:`date`:
531
532.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000533
534 >>> from datetime import date
535 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
536 >>> d
537 datetime.date(2002, 3, 11)
538 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000539 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000540 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000541 2002 # year
542 3 # month
543 11 # day
544 0
545 0
546 0
547 0 # weekday (0 = Monday)
548 70 # 70th day in the year
549 -1
550 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000551 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000552 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000553 2002 # ISO year
554 11 # ISO week number
555 1 # ISO day number ( 1 = Monday )
556 >>> d.isoformat()
557 '2002-03-11'
558 >>> d.strftime("%d/%m/%y")
559 '11/03/02'
560 >>> d.strftime("%A %d. %B %Y")
561 'Monday 11. March 2002'
562
Georg Brandl116aa622007-08-15 14:28:22 +0000563
564.. _datetime-datetime:
565
566:class:`datetime` Objects
567-------------------------
568
569A :class:`datetime` object is a single object containing all the information
570from a :class:`date` object and a :class:`time` object. Like a :class:`date`
571object, :class:`datetime` assumes the current Gregorian calendar extended in
572both directions; like a time object, :class:`datetime` assumes there are exactly
5733600\*24 seconds in every day.
574
575Constructor:
576
577
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000578.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000579
580 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000581 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
582 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000583
584 * ``MINYEAR <= year <= MAXYEAR``
585 * ``1 <= month <= 12``
586 * ``1 <= day <= number of days in the given month and year``
587 * ``0 <= hour < 24``
588 * ``0 <= minute < 60``
589 * ``0 <= second < 60``
590 * ``0 <= microsecond < 1000000``
591
592 If an argument outside those ranges is given, :exc:`ValueError` is raised.
593
594Other constructors, all class methods:
595
596
597.. method:: datetime.today()
598
599 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
600 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
601 :meth:`fromtimestamp`.
602
603
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000604.. method:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000605
606 Return the current local date and time. If optional argument *tz* is ``None``
607 or not specified, this is like :meth:`today`, but, if possible, supplies more
608 precision than can be gotten from going through a :func:`time.time` timestamp
609 (for example, this may be possible on platforms supplying the C
610 :cfunc:`gettimeofday` function).
611
612 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
613 current date and time are converted to *tz*'s time zone. In this case the
614 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
615 See also :meth:`today`, :meth:`utcnow`.
616
617
618.. method:: datetime.utcnow()
619
620 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
621 :meth:`now`, but returns the current UTC date and time, as a naive
622 :class:`datetime` object. See also :meth:`now`.
623
624
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000625.. method:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000626
627 Return the local date and time corresponding to the POSIX timestamp, such as is
628 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
629 specified, the timestamp is converted to the platform's local date and time, and
630 the returned :class:`datetime` object is naive.
631
632 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
633 timestamp is converted to *tz*'s time zone. In this case the result is
634 equivalent to
635 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
636
637 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
638 the range of values supported by the platform C :cfunc:`localtime` or
639 :cfunc:`gmtime` functions. It's common for this to be restricted to years in
640 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
641 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
642 and then it's possible to have two timestamps differing by a second that yield
643 identical :class:`datetime` objects. See also :meth:`utcfromtimestamp`.
644
645
646.. method:: datetime.utcfromtimestamp(timestamp)
647
648 Return the UTC :class:`datetime` corresponding to the POSIX timestamp, with
649 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
650 out of the range of values supported by the platform C :cfunc:`gmtime` function.
651 It's common for this to be restricted to years in 1970 through 2038. See also
652 :meth:`fromtimestamp`.
653
654
655.. method:: datetime.fromordinal(ordinal)
656
657 Return the :class:`datetime` corresponding to the proleptic Gregorian ordinal,
658 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
659 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
660 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
661
662
663.. method:: datetime.combine(date, time)
664
665 Return a new :class:`datetime` object whose date members are equal to the given
666 :class:`date` object's, and whose time and :attr:`tzinfo` members are equal to
667 the given :class:`time` object's. For any :class:`datetime` object *d*, ``d ==
668 datetime.combine(d.date(), d.timetz())``. If date is a :class:`datetime`
669 object, its time and :attr:`tzinfo` members are ignored.
670
671
672.. method:: datetime.strptime(date_string, format)
673
674 Return a :class:`datetime` corresponding to *date_string*, parsed according to
675 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
676 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
677 can't be parsed by :func:`time.strptime` or if it returns a value which isn't a
678 time tuple.
679
Georg Brandl116aa622007-08-15 14:28:22 +0000680
681Class attributes:
682
683
684.. attribute:: datetime.min
685
686 The earliest representable :class:`datetime`, ``datetime(MINYEAR, 1, 1,
687 tzinfo=None)``.
688
689
690.. attribute:: datetime.max
691
692 The latest representable :class:`datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
693 59, 999999, tzinfo=None)``.
694
695
696.. attribute:: datetime.resolution
697
698 The smallest possible difference between non-equal :class:`datetime` objects,
699 ``timedelta(microseconds=1)``.
700
701Instance attributes (read-only):
702
703
704.. attribute:: datetime.year
705
706 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
707
708
709.. attribute:: datetime.month
710
711 Between 1 and 12 inclusive.
712
713
714.. attribute:: datetime.day
715
716 Between 1 and the number of days in the given month of the given year.
717
718
719.. attribute:: datetime.hour
720
721 In ``range(24)``.
722
723
724.. attribute:: datetime.minute
725
726 In ``range(60)``.
727
728
729.. attribute:: datetime.second
730
731 In ``range(60)``.
732
733
734.. attribute:: datetime.microsecond
735
736 In ``range(1000000)``.
737
738
739.. attribute:: datetime.tzinfo
740
741 The object passed as the *tzinfo* argument to the :class:`datetime` constructor,
742 or ``None`` if none was passed.
743
744Supported operations:
745
746+---------------------------------------+-------------------------------+
747| Operation | Result |
748+=======================================+===============================+
749| ``datetime2 = datetime1 + timedelta`` | \(1) |
750+---------------------------------------+-------------------------------+
751| ``datetime2 = datetime1 - timedelta`` | \(2) |
752+---------------------------------------+-------------------------------+
753| ``timedelta = datetime1 - datetime2`` | \(3) |
754+---------------------------------------+-------------------------------+
755| ``datetime1 < datetime2`` | Compares :class:`datetime` to |
756| | :class:`datetime`. (4) |
757+---------------------------------------+-------------------------------+
758
759(1)
760 datetime2 is a duration of timedelta removed from datetime1, moving forward in
761 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
762 result has the same :attr:`tzinfo` member as the input datetime, and datetime2 -
763 datetime1 == timedelta after. :exc:`OverflowError` is raised if datetime2.year
764 would be smaller than :const:`MINYEAR` or larger than :const:`MAXYEAR`. Note
765 that no time zone adjustments are done even if the input is an aware object.
766
767(2)
768 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
769 addition, the result has the same :attr:`tzinfo` member as the input datetime,
770 and no time zone adjustments are done even if the input is aware. This isn't
771 quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation
772 can overflow in cases where datetime1 - timedelta does not.
773
774(3)
775 Subtraction of a :class:`datetime` from a :class:`datetime` is defined only if
776 both operands are naive, or if both are aware. If one is aware and the other is
777 naive, :exc:`TypeError` is raised.
778
779 If both are naive, or both are aware and have the same :attr:`tzinfo` member,
780 the :attr:`tzinfo` members are ignored, and the result is a :class:`timedelta`
781 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
782 are done in this case.
783
784 If both are aware and have different :attr:`tzinfo` members, ``a-b`` acts as if
785 *a* and *b* were first converted to naive UTC datetimes first. The result is
786 ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) -
787 b.utcoffset())`` except that the implementation never overflows.
788
789(4)
790 *datetime1* is considered less than *datetime2* when *datetime1* precedes
791 *datetime2* in time.
792
793 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
794 If both comparands are aware, and have the same :attr:`tzinfo` member, the
795 common :attr:`tzinfo` member is ignored and the base datetimes are compared. If
796 both comparands are aware and have different :attr:`tzinfo` members, the
797 comparands are first adjusted by subtracting their UTC offsets (obtained from
798 ``self.utcoffset()``).
799
800 .. note::
801
802 In order to stop comparison from falling back to the default scheme of comparing
803 object addresses, datetime comparison normally raises :exc:`TypeError` if the
804 other comparand isn't also a :class:`datetime` object. However,
805 ``NotImplemented`` is returned instead if the other comparand has a
806 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
807 chance at implementing mixed-type comparison. If not, when a :class:`datetime`
808 object is compared to an object of a different type, :exc:`TypeError` is raised
809 unless the comparison is ``==`` or ``!=``. The latter cases return
810 :const:`False` or :const:`True`, respectively.
811
812:class:`datetime` objects can be used as dictionary keys. In Boolean contexts,
813all :class:`datetime` objects are considered to be true.
814
815Instance methods:
816
817
818.. method:: datetime.date()
819
820 Return :class:`date` object with same year, month and day.
821
822
823.. method:: datetime.time()
824
825 Return :class:`time` object with same hour, minute, second and microsecond.
826 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
827
828
829.. method:: datetime.timetz()
830
831 Return :class:`time` object with same hour, minute, second, microsecond, and
832 tzinfo members. See also method :meth:`time`.
833
834
835.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
836
837 Return a datetime with the same members, except for those members given new
838 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
839 can be specified to create a naive datetime from an aware datetime with no
840 conversion of date and time members.
841
842
843.. method:: datetime.astimezone(tz)
844
845 Return a :class:`datetime` object with new :attr:`tzinfo` member *tz*, adjusting
846 the date and time members so the result is the same UTC time as *self*, but in
847 *tz*'s local time.
848
849 *tz* must be an instance of a :class:`tzinfo` subclass, and its
850 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
851 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
852 not return ``None``).
853
854 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
855 adjustment of date or time members is performed. Else the result is local time
856 in time zone *tz*, representing the same UTC time as *self*: after ``astz =
857 dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have the same date
858 and time members as ``dt - dt.utcoffset()``. The discussion of class
859 :class:`tzinfo` explains the cases at Daylight Saving Time transition boundaries
860 where this cannot be achieved (an issue only if *tz* models both standard and
861 daylight time).
862
863 If you merely want to attach a time zone object *tz* to a datetime *dt* without
864 adjustment of date and time members, use ``dt.replace(tzinfo=tz)``. If you
865 merely want to remove the time zone object from an aware datetime *dt* without
866 conversion of date and time members, use ``dt.replace(tzinfo=None)``.
867
868 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
869 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
870 Ignoring error cases, :meth:`astimezone` acts like::
871
872 def astimezone(self, tz):
873 if self.tzinfo is tz:
874 return self
875 # Convert self to UTC, and attach the new time zone object.
876 utc = (self - self.utcoffset()).replace(tzinfo=tz)
877 # Convert from UTC to tz's local time.
878 return tz.fromutc(utc)
879
880
881.. method:: datetime.utcoffset()
882
883 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
884 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
885 return ``None``, or a :class:`timedelta` object representing a whole number of
886 minutes with magnitude less than one day.
887
888
889.. method:: datetime.dst()
890
891 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
892 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
893 ``None``, or a :class:`timedelta` object representing a whole number of minutes
894 with magnitude less than one day.
895
896
897.. method:: datetime.tzname()
898
899 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
900 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
901 ``None`` or a string object,
902
903
904.. method:: datetime.timetuple()
905
906 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
907 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
908 d.hour, d.minute, d.second, d.weekday(), d.toordinal() - date(d.year, 1,
909 1).toordinal() + 1, dst))`` The :attr:`tm_isdst` flag of the result is set
910 according to the :meth:`dst` method: :attr:`tzinfo` is ``None`` or :meth:`dst`
911 returns ``None``, :attr:`tm_isdst` is set to ``-1``; else if :meth:`dst`
912 returns a non-zero value, :attr:`tm_isdst` is set to ``1``; else ``tm_isdst`` is
913 set to ``0``.
914
915
916.. method:: datetime.utctimetuple()
917
918 If :class:`datetime` instance *d* is naive, this is the same as
919 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
920 ``d.dst()`` returns. DST is never in effect for a UTC time.
921
922 If *d* is aware, *d* is normalized to UTC time, by subtracting
923 ``d.utcoffset()``, and a :class:`time.struct_time` for the normalized time is
924 returned. :attr:`tm_isdst` is forced to 0. Note that the result's
925 :attr:`tm_year` member may be :const:`MINYEAR`\ -1 or :const:`MAXYEAR`\ +1, if
926 *d*.year was ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
927 boundary.
928
929
930.. method:: datetime.toordinal()
931
932 Return the proleptic Gregorian ordinal of the date. The same as
933 ``self.date().toordinal()``.
934
935
936.. method:: datetime.weekday()
937
938 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
939 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
940
941
942.. method:: datetime.isoweekday()
943
944 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
945 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
946 :meth:`isocalendar`.
947
948
949.. method:: datetime.isocalendar()
950
951 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
952 ``self.date().isocalendar()``.
953
954
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000955.. method:: datetime.isoformat(sep='T')
Georg Brandl116aa622007-08-15 14:28:22 +0000956
957 Return a string representing the date and time in ISO 8601 format,
958 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
959 YYYY-MM-DDTHH:MM:SS
960
961 If :meth:`utcoffset` does not return ``None``, a 6-character string is
962 appended, giving the UTC offset in (signed) hours and minutes:
963 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
964 YYYY-MM-DDTHH:MM:SS+HH:MM
965
966 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000967 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +0000968
969 >>> from datetime import tzinfo, timedelta, datetime
970 >>> class TZ(tzinfo):
971 ... def utcoffset(self, dt): return timedelta(minutes=-399)
972 ...
973 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
974 '2002-12-25 00:00:00-06:39'
975
976
977.. method:: datetime.__str__()
978
979 For a :class:`datetime` instance *d*, ``str(d)`` is equivalent to
980 ``d.isoformat(' ')``.
981
982
983.. method:: datetime.ctime()
984
985 Return a string representing the date and time, for example ``datetime(2002, 12,
986 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
987 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
988 native C :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
989 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
990
991
992.. method:: datetime.strftime(format)
993
994 Return a string representing the date and time, controlled by an explicit format
995 string. See section :ref:`strftime-behavior`.
996
Christian Heimesfe337bf2008-03-23 21:54:12 +0000997Examples of working with datetime objects:
998
999.. doctest::
1000
Christian Heimes895627f2007-12-08 17:28:33 +00001001 >>> from datetime import datetime, date, time
1002 >>> # Using datetime.combine()
1003 >>> d = date(2005, 7, 14)
1004 >>> t = time(12, 30)
1005 >>> datetime.combine(d, t)
1006 datetime.datetime(2005, 7, 14, 12, 30)
1007 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001008 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001009 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001010 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001011 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1012 >>> # Using datetime.strptime()
1013 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1014 >>> dt
1015 datetime.datetime(2006, 11, 21, 16, 30)
1016 >>> # Using datetime.timetuple() to get tuple of all attributes
1017 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001018 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001019 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001020 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001021 2006 # year
1022 11 # month
1023 21 # day
1024 16 # hour
1025 30 # minute
1026 0 # second
1027 1 # weekday (0 = Monday)
1028 325 # number of days since 1st January
1029 -1 # dst - method tzinfo.dst() returned None
1030 >>> # Date in ISO format
1031 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001032 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001033 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001034 ...
1035 2006 # ISO year
1036 47 # ISO week
1037 2 # ISO weekday
1038 >>> # Formatting datetime
1039 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1040 'Tuesday, 21. November 2006 04:30PM'
1041
Christian Heimesfe337bf2008-03-23 21:54:12 +00001042Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001043
1044 >>> from datetime import timedelta, datetime, tzinfo
1045 >>> class GMT1(tzinfo):
1046 ... def __init__(self): # DST starts last Sunday in March
1047 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1048 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001049 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001050 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1051 ... def utcoffset(self, dt):
1052 ... return timedelta(hours=1) + self.dst(dt)
Georg Brandl48310cd2009-01-03 21:18:54 +00001053 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001054 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1055 ... return timedelta(hours=1)
1056 ... else:
1057 ... return timedelta(0)
1058 ... def tzname(self,dt):
1059 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001060 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001061 >>> class GMT2(tzinfo):
1062 ... def __init__(self):
Georg Brandl48310cd2009-01-03 21:18:54 +00001063 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001064 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001065 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001066 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1067 ... def utcoffset(self, dt):
1068 ... return timedelta(hours=1) + self.dst(dt)
1069 ... def dst(self, dt):
1070 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1071 ... return timedelta(hours=2)
1072 ... else:
1073 ... return timedelta(0)
1074 ... def tzname(self,dt):
1075 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001076 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001077 >>> gmt1 = GMT1()
1078 >>> # Daylight Saving Time
1079 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1080 >>> dt1.dst()
1081 datetime.timedelta(0)
1082 >>> dt1.utcoffset()
1083 datetime.timedelta(0, 3600)
1084 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1085 >>> dt2.dst()
1086 datetime.timedelta(0, 3600)
1087 >>> dt2.utcoffset()
1088 datetime.timedelta(0, 7200)
1089 >>> # Convert datetime to another time zone
1090 >>> dt3 = dt2.astimezone(GMT2())
1091 >>> dt3 # doctest: +ELLIPSIS
1092 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1093 >>> dt2 # doctest: +ELLIPSIS
1094 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1095 >>> dt2.utctimetuple() == dt3.utctimetuple()
1096 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001097
Christian Heimes895627f2007-12-08 17:28:33 +00001098
Georg Brandl116aa622007-08-15 14:28:22 +00001099
1100.. _datetime-time:
1101
1102:class:`time` Objects
1103---------------------
1104
1105A time object represents a (local) time of day, independent of any particular
1106day, and subject to adjustment via a :class:`tzinfo` object.
1107
1108
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001109.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001110
1111 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001112 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001113 following ranges:
1114
1115 * ``0 <= hour < 24``
1116 * ``0 <= minute < 60``
1117 * ``0 <= second < 60``
1118 * ``0 <= microsecond < 1000000``.
1119
1120 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1121 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1122
1123Class attributes:
1124
1125
1126.. attribute:: time.min
1127
1128 The earliest representable :class:`time`, ``time(0, 0, 0, 0)``.
1129
1130
1131.. attribute:: time.max
1132
1133 The latest representable :class:`time`, ``time(23, 59, 59, 999999)``.
1134
1135
1136.. attribute:: time.resolution
1137
1138 The smallest possible difference between non-equal :class:`time` objects,
1139 ``timedelta(microseconds=1)``, although note that arithmetic on :class:`time`
1140 objects is not supported.
1141
1142Instance attributes (read-only):
1143
1144
1145.. attribute:: time.hour
1146
1147 In ``range(24)``.
1148
1149
1150.. attribute:: time.minute
1151
1152 In ``range(60)``.
1153
1154
1155.. attribute:: time.second
1156
1157 In ``range(60)``.
1158
1159
1160.. attribute:: time.microsecond
1161
1162 In ``range(1000000)``.
1163
1164
1165.. attribute:: time.tzinfo
1166
1167 The object passed as the tzinfo argument to the :class:`time` constructor, or
1168 ``None`` if none was passed.
1169
1170Supported operations:
1171
1172* comparison of :class:`time` to :class:`time`, where *a* is considered less
1173 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1174 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
1175 the same :attr:`tzinfo` member, the common :attr:`tzinfo` member is ignored and
1176 the base times are compared. If both comparands are aware and have different
1177 :attr:`tzinfo` members, the comparands are first adjusted by subtracting their
1178 UTC offsets (obtained from ``self.utcoffset()``). In order to stop mixed-type
1179 comparisons from falling back to the default comparison by object address, when
1180 a :class:`time` object is compared to an object of a different type,
1181 :exc:`TypeError` is raised unless the comparison is ``==`` or ``!=``. The
1182 latter cases return :const:`False` or :const:`True`, respectively.
1183
1184* hash, use as dict key
1185
1186* efficient pickling
1187
1188* in Boolean contexts, a :class:`time` object is considered to be true if and
1189 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1190 ``0`` if that's ``None``), the result is non-zero.
1191
1192Instance methods:
1193
1194
1195.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1196
1197 Return a :class:`time` with the same value, except for those members given new
1198 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
1199 can be specified to create a naive :class:`time` from an aware :class:`time`,
1200 without conversion of the time members.
1201
1202
1203.. method:: time.isoformat()
1204
1205 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1206 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1207 6-character string is appended, giving the UTC offset in (signed) hours and
1208 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1209
1210
1211.. method:: time.__str__()
1212
1213 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1214
1215
1216.. method:: time.strftime(format)
1217
1218 Return a string representing the time, controlled by an explicit format string.
1219 See section :ref:`strftime-behavior`.
1220
1221
1222.. method:: time.utcoffset()
1223
1224 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1225 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1226 return ``None`` or a :class:`timedelta` object representing a whole number of
1227 minutes with magnitude less than one day.
1228
1229
1230.. method:: time.dst()
1231
1232 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1233 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1234 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1235 with magnitude less than one day.
1236
1237
1238.. method:: time.tzname()
1239
1240 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1241 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1242 return ``None`` or a string object.
1243
Christian Heimesfe337bf2008-03-23 21:54:12 +00001244Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001245
Christian Heimes895627f2007-12-08 17:28:33 +00001246 >>> from datetime import time, tzinfo
1247 >>> class GMT1(tzinfo):
1248 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001249 ... return timedelta(hours=1)
1250 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001251 ... return timedelta(0)
1252 ... def tzname(self,dt):
1253 ... return "Europe/Prague"
1254 ...
1255 >>> t = time(12, 10, 30, tzinfo=GMT1())
1256 >>> t # doctest: +ELLIPSIS
1257 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1258 >>> gmt = GMT1()
1259 >>> t.isoformat()
1260 '12:10:30+01:00'
1261 >>> t.dst()
1262 datetime.timedelta(0)
1263 >>> t.tzname()
1264 'Europe/Prague'
1265 >>> t.strftime("%H:%M:%S %Z")
1266 '12:10:30 Europe/Prague'
1267
Georg Brandl116aa622007-08-15 14:28:22 +00001268
1269.. _datetime-tzinfo:
1270
1271:class:`tzinfo` Objects
1272-----------------------
1273
Brett Cannone1327f72009-01-29 04:10:21 +00001274:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001275instantiated directly. You need to derive a concrete subclass, and (at least)
1276supply implementations of the standard :class:`tzinfo` methods needed by the
1277:class:`datetime` methods you use. The :mod:`datetime` module does not supply
1278any concrete subclasses of :class:`tzinfo`.
1279
1280An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1281constructors for :class:`datetime` and :class:`time` objects. The latter objects
1282view their members as being in local time, and the :class:`tzinfo` object
1283supports methods revealing offset of local time from UTC, the name of the time
1284zone, and DST offset, all relative to a date or time object passed to them.
1285
1286Special requirement for pickling: A :class:`tzinfo` subclass must have an
1287:meth:`__init__` method that can be called with no arguments, else it can be
1288pickled but possibly not unpickled again. This is a technical requirement that
1289may be relaxed in the future.
1290
1291A concrete subclass of :class:`tzinfo` may need to implement the following
1292methods. Exactly which methods are needed depends on the uses made of aware
1293:mod:`datetime` objects. If in doubt, simply implement all of them.
1294
1295
1296.. method:: tzinfo.utcoffset(self, dt)
1297
1298 Return offset of local time from UTC, in minutes east of UTC. If local time is
1299 west of UTC, this should be negative. Note that this is intended to be the
1300 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1301 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1302 the UTC offset isn't known, return ``None``. Else the value returned must be a
1303 :class:`timedelta` object specifying a whole number of minutes in the range
1304 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1305 than one day). Most implementations of :meth:`utcoffset` will probably look
1306 like one of these two::
1307
1308 return CONSTANT # fixed-offset class
1309 return CONSTANT + self.dst(dt) # daylight-aware class
1310
1311 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1312 ``None`` either.
1313
1314 The default implementation of :meth:`utcoffset` raises
1315 :exc:`NotImplementedError`.
1316
1317
1318.. method:: tzinfo.dst(self, dt)
1319
1320 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1321 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1322 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1323 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1324 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1325 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1326 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
1327 member's :meth:`dst` method to determine how the :attr:`tm_isdst` flag should be
1328 set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for DST changes
1329 when crossing time zones.
1330
1331 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1332 daylight times must be consistent in this sense:
1333
1334 ``tz.utcoffset(dt) - tz.dst(dt)``
1335
1336 must return the same result for every :class:`datetime` *dt* with ``dt.tzinfo ==
1337 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1338 zone's "standard offset", which should not depend on the date or the time, but
1339 only on geographic location. The implementation of :meth:`datetime.astimezone`
1340 relies on this, but cannot detect violations; it's the programmer's
1341 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1342 this, it may be able to override the default implementation of
1343 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1344
1345 Most implementations of :meth:`dst` will probably look like one of these two::
1346
1347 def dst(self):
1348 # a fixed-offset class: doesn't account for DST
1349 return timedelta(0)
1350
1351 or ::
1352
1353 def dst(self):
1354 # Code to set dston and dstoff to the time zone's DST
1355 # transition times based on the input dt.year, and expressed
1356 # in standard local time. Then
1357
1358 if dston <= dt.replace(tzinfo=None) < dstoff:
1359 return timedelta(hours=1)
1360 else:
1361 return timedelta(0)
1362
1363 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1364
1365
1366.. method:: tzinfo.tzname(self, dt)
1367
1368 Return the time zone name corresponding to the :class:`datetime` object *dt*, as
1369 a string. Nothing about string names is defined by the :mod:`datetime` module,
1370 and there's no requirement that it mean anything in particular. For example,
1371 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1372 valid replies. Return ``None`` if a string name isn't known. Note that this is
1373 a method rather than a fixed string primarily because some :class:`tzinfo`
1374 subclasses will wish to return different names depending on the specific value
1375 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1376 daylight time.
1377
1378 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1379
1380These methods are called by a :class:`datetime` or :class:`time` object, in
1381response to their methods of the same names. A :class:`datetime` object passes
1382itself as the argument, and a :class:`time` object passes ``None`` as the
1383argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
1384accept a *dt* argument of ``None``, or of class :class:`datetime`.
1385
1386When ``None`` is passed, it's up to the class designer to decide the best
1387response. For example, returning ``None`` is appropriate if the class wishes to
1388say that time objects don't participate in the :class:`tzinfo` protocols. It
1389may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1390there is no other convention for discovering the standard offset.
1391
1392When a :class:`datetime` object is passed in response to a :class:`datetime`
1393method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1394rely on this, unless user code calls :class:`tzinfo` methods directly. The
1395intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1396time, and not need worry about objects in other timezones.
1397
1398There is one more :class:`tzinfo` method that a subclass may wish to override:
1399
1400
1401.. method:: tzinfo.fromutc(self, dt)
1402
1403 This is called from the default :class:`datetime.astimezone()` implementation.
1404 When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members
1405 are to be viewed as expressing a UTC time. The purpose of :meth:`fromutc` is to
1406 adjust the date and time members, returning an equivalent datetime in *self*'s
1407 local time.
1408
1409 Most :class:`tzinfo` subclasses should be able to inherit the default
1410 :meth:`fromutc` implementation without problems. It's strong enough to handle
1411 fixed-offset time zones, and time zones accounting for both standard and
1412 daylight time, and the latter even if the DST transition times differ in
1413 different years. An example of a time zone the default :meth:`fromutc`
1414 implementation may not handle correctly in all cases is one where the standard
1415 offset (from UTC) depends on the specific date and time passed, which can happen
1416 for political reasons. The default implementations of :meth:`astimezone` and
1417 :meth:`fromutc` may not produce the result you want if the result is one of the
1418 hours straddling the moment the standard offset changes.
1419
1420 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1421 like::
1422
1423 def fromutc(self, dt):
1424 # raise ValueError error if dt.tzinfo is not self
1425 dtoff = dt.utcoffset()
1426 dtdst = dt.dst()
1427 # raise ValueError if dtoff is None or dtdst is None
1428 delta = dtoff - dtdst # this is self's standard offset
1429 if delta:
1430 dt += delta # convert to standard local time
1431 dtdst = dt.dst()
1432 # raise ValueError if dtdst is None
1433 if dtdst:
1434 return dt + dtdst
1435 else:
1436 return dt
1437
1438Example :class:`tzinfo` classes:
1439
1440.. literalinclude:: ../includes/tzinfo-examples.py
1441
1442
1443Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1444subclass accounting for both standard and daylight time, at the DST transition
1445points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
1446minute after 1:59 (EST) on the first Sunday in April, and ends the minute after
14471:59 (EDT) on the last Sunday in October::
1448
1449 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1450 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1451 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1452
1453 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1454
1455 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1456
1457When DST starts (the "start" line), the local wall clock leaps from 1:59 to
14583:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1459``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1460begins. In order for :meth:`astimezone` to make this guarantee, the
1461:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1462Eastern) to be in daylight time.
1463
1464When DST ends (the "end" line), there's a potentially worse problem: there's an
1465hour that can't be spelled unambiguously in local wall time: the last hour of
1466daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1467daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1468to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1469:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1470hours into the same local hour then. In the Eastern example, UTC times of the
1471form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1472:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1473consider times in the "repeated hour" to be in standard time. This is easily
1474arranged, as in the example, by expressing DST switch times in the time zone's
1475standard local time.
1476
1477Applications that can't bear such ambiguities should avoid using hybrid
1478:class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any
1479other fixed-offset :class:`tzinfo` subclass (such as a class representing only
1480EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
Georg Brandl48310cd2009-01-03 21:18:54 +00001481
Georg Brandl116aa622007-08-15 14:28:22 +00001482
1483.. _strftime-behavior:
1484
1485:meth:`strftime` Behavior
1486-------------------------
1487
1488:class:`date`, :class:`datetime`, and :class:`time` objects all support a
1489``strftime(format)`` method, to create a string representing the time under the
1490control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1491acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1492although not all objects support a :meth:`timetuple` method.
1493
1494For :class:`time` objects, the format codes for year, month, and day should not
1495be used, as time objects have no such values. If they're used anyway, ``1900``
1496is substituted for the year, and ``0`` for the month and day.
1497
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001498For :class:`date` objects, the format codes for hours, minutes, seconds, and
1499microseconds should not be used, as :class:`date` objects have no such
1500values. If they're used anyway, ``0`` is substituted for them.
1501
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001502For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1503strings.
1504
1505For an aware object:
1506
1507``%z``
1508 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1509 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1510 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1511 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1512 replaced with the string ``'-0330'``.
1513
1514``%Z``
1515 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1516 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl116aa622007-08-15 14:28:22 +00001517
Georg Brandl116aa622007-08-15 14:28:22 +00001518The full set of format codes supported varies across platforms, because Python
1519calls the platform C library's :func:`strftime` function, and platform
Georg Brandl48310cd2009-01-03 21:18:54 +00001520variations are common.
Christian Heimes895627f2007-12-08 17:28:33 +00001521
1522The following is a list of all the format codes that the C standard (1989
1523version) requires, and these work on all platforms with a standard C
1524implementation. Note that the 1999 version of the C standard added additional
1525format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001526
1527The exact range of years for which :meth:`strftime` works also varies across
1528platforms. Regardless of platform, years before 1900 cannot be used.
1529
Christian Heimes895627f2007-12-08 17:28:33 +00001530+-----------+--------------------------------+-------+
1531| Directive | Meaning | Notes |
1532+===========+================================+=======+
1533| ``%a`` | Locale's abbreviated weekday | |
1534| | name. | |
1535+-----------+--------------------------------+-------+
1536| ``%A`` | Locale's full weekday name. | |
1537+-----------+--------------------------------+-------+
1538| ``%b`` | Locale's abbreviated month | |
1539| | name. | |
1540+-----------+--------------------------------+-------+
1541| ``%B`` | Locale's full month name. | |
1542+-----------+--------------------------------+-------+
1543| ``%c`` | Locale's appropriate date and | |
1544| | time representation. | |
1545+-----------+--------------------------------+-------+
1546| ``%d`` | Day of the month as a decimal | |
1547| | number [01,31]. | |
1548+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001549| ``%f`` | Microsecond as a decimal | \(1) |
1550| | number [0,999999], zero-padded | |
1551| | on the left | |
1552+-----------+--------------------------------+-------+
Christian Heimes895627f2007-12-08 17:28:33 +00001553| ``%H`` | Hour (24-hour clock) as a | |
1554| | decimal number [00,23]. | |
1555+-----------+--------------------------------+-------+
1556| ``%I`` | Hour (12-hour clock) as a | |
1557| | decimal number [01,12]. | |
1558+-----------+--------------------------------+-------+
1559| ``%j`` | Day of the year as a decimal | |
1560| | number [001,366]. | |
1561+-----------+--------------------------------+-------+
1562| ``%m`` | Month as a decimal number | |
1563| | [01,12]. | |
1564+-----------+--------------------------------+-------+
1565| ``%M`` | Minute as a decimal number | |
1566| | [00,59]. | |
1567+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001568| ``%p`` | Locale's equivalent of either | \(2) |
Christian Heimes895627f2007-12-08 17:28:33 +00001569| | AM or PM. | |
1570+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001571| ``%S`` | Second as a decimal number | \(3) |
Christian Heimes895627f2007-12-08 17:28:33 +00001572| | [00,61]. | |
1573+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001574| ``%U`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001575| | (Sunday as the first day of | |
1576| | the week) as a decimal number | |
1577| | [00,53]. All days in a new | |
1578| | year preceding the first | |
1579| | Sunday are considered to be in | |
1580| | week 0. | |
1581+-----------+--------------------------------+-------+
1582| ``%w`` | Weekday as a decimal number | |
1583| | [0(Sunday),6]. | |
1584+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001585| ``%W`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001586| | (Monday as the first day of | |
1587| | the week) as a decimal number | |
1588| | [00,53]. All days in a new | |
1589| | year preceding the first | |
1590| | Monday are considered to be in | |
1591| | week 0. | |
1592+-----------+--------------------------------+-------+
1593| ``%x`` | Locale's appropriate date | |
1594| | representation. | |
1595+-----------+--------------------------------+-------+
1596| ``%X`` | Locale's appropriate time | |
1597| | representation. | |
1598+-----------+--------------------------------+-------+
1599| ``%y`` | Year without century as a | |
1600| | decimal number [00,99]. | |
1601+-----------+--------------------------------+-------+
1602| ``%Y`` | Year with century as a decimal | |
1603| | number. | |
1604+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001605| ``%z`` | UTC offset in the form +HHMM | \(5) |
Christian Heimes895627f2007-12-08 17:28:33 +00001606| | or -HHMM (empty string if the | |
1607| | the object is naive). | |
1608+-----------+--------------------------------+-------+
1609| ``%Z`` | Time zone name (empty string | |
1610| | if the object is naive). | |
1611+-----------+--------------------------------+-------+
1612| ``%%`` | A literal ``'%'`` character. | |
1613+-----------+--------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001614
Christian Heimes895627f2007-12-08 17:28:33 +00001615Notes:
1616
1617(1)
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001618 When used with the :func:`strptime` function, the ``%f`` directive
1619 accepts from one to six digits and zero pads on the right. ``%f`` is
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001620 an extension to the set of format characters in the C standard (but
1621 implemented separately in datetime objects, and therefore always
1622 available).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001623
1624(2)
Christian Heimes895627f2007-12-08 17:28:33 +00001625 When used with the :func:`strptime` function, the ``%p`` directive only affects
1626 the output hour field if the ``%I`` directive is used to parse the hour.
1627
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001628(3)
R. David Murraybd25d332009-04-02 04:50:03 +00001629 The range really is ``0`` to ``61``; according to the Posix standard this
1630 accounts for leap seconds and the (very rare) double leap seconds.
1631 The :mod:`time` module may produce and does accept leap seconds since
1632 it is based on the Posix standard, but the :mod:`datetime` module
1633 does not accept leap seconds in :func:`strptime` input nor will it
1634 produce them in :func:`strftime` output.
Christian Heimes895627f2007-12-08 17:28:33 +00001635
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001636(4)
Christian Heimes895627f2007-12-08 17:28:33 +00001637 When used with the :func:`strptime` function, ``%U`` and ``%W`` are only used in
1638 calculations when the day of the week and the year are specified.
1639
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001640(5)
Christian Heimes895627f2007-12-08 17:28:33 +00001641 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1642 ``%z`` is replaced with the string ``'-0330'``.