blob: e8fe81b7b49aa5661f21a1f505c547ce32878568 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`datetime` --- Basic date and time types
2=============================================
3
4.. module:: datetime
5 :synopsis: Basic date and time types.
6.. moduleauthor:: Tim Peters <tim@zope.com>
7.. sectionauthor:: Tim Peters <tim@zope.com>
8.. sectionauthor:: A.M. Kuchling <amk@amk.ca>
9
Georg Brandlb19be572007-12-29 10:57:00 +000010.. XXX what order should the types be discussed in?
Georg Brandl8ec7f652007-08-15 14:28:01 +000011
12.. versionadded:: 2.3
13
14The :mod:`datetime` module supplies classes for manipulating dates and times in
15both simple and complex ways. While date and time arithmetic is supported, the
16focus of the implementation is on efficient member extraction for output
17formatting and manipulation. For related
18functionality, see also the :mod:`time` and :mod:`calendar` modules.
19
20There are two kinds of date and time objects: "naive" and "aware". This
21distinction refers to whether the object has any notion of time zone, daylight
22saving time, or other kind of algorithmic or political time adjustment. Whether
23a naive :class:`datetime` object represents Coordinated Universal Time (UTC),
24local time, or time in some other timezone is purely up to the program, just
25like it's up to the program whether a particular number represents metres,
26miles, or mass. Naive :class:`datetime` objects are easy to understand and to
27work with, at the cost of ignoring some aspects of reality.
28
29For applications requiring more, :class:`datetime` and :class:`time` objects
30have an optional time zone information member, :attr:`tzinfo`, that can contain
31an instance of a subclass of the abstract :class:`tzinfo` class. These
32:class:`tzinfo` objects capture information about the offset from UTC time, the
33time zone name, and whether Daylight Saving Time is in effect. Note that no
34concrete :class:`tzinfo` classes are supplied by the :mod:`datetime` module.
35Supporting timezones at whatever level of detail is required is up to the
36application. The rules for time adjustment across the world are more political
37than rational, and there is no standard suitable for every application.
38
39The :mod:`datetime` module exports the following constants:
40
Georg Brandl8ec7f652007-08-15 14:28:01 +000041.. data:: MINYEAR
42
43 The smallest year number allowed in a :class:`date` or :class:`datetime` object.
44 :const:`MINYEAR` is ``1``.
45
46
47.. data:: MAXYEAR
48
49 The largest year number allowed in a :class:`date` or :class:`datetime` object.
50 :const:`MAXYEAR` is ``9999``.
51
52
53.. seealso::
54
55 Module :mod:`calendar`
56 General calendar related functions.
57
58 Module :mod:`time`
59 Time access and conversions.
60
61
62Available Types
63---------------
64
Georg Brandl8ec7f652007-08-15 14:28:01 +000065.. class:: date
Georg Brandl8a859452009-10-27 14:59:26 +000066 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Georg Brandl8a859452009-10-27 14:59:26 +000074 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Georg Brandl8a859452009-10-27 14:59:26 +000083 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Georg Brandl8a859452009-10-27 14:59:26 +000091 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Georg Brandl8ec7f652007-08-15 14:28:01 +0000134.. class:: timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
135
136 All arguments are optional and default to ``0``. Arguments may be ints, longs,
137 or floats, and may be positive or negative.
138
139 Only *days*, *seconds* and *microseconds* are stored internally. Arguments are
140 converted to those units:
141
142 * A millisecond is converted to 1000 microseconds.
143 * A minute is converted to 60 seconds.
144 * An hour is converted to 3600 seconds.
145 * A week is converted to 7 days.
146
147 and days, seconds and microseconds are then normalized so that the
148 representation is unique, with
149
150 * ``0 <= microseconds < 1000000``
151 * ``0 <= seconds < 3600*24`` (the number of seconds in one day)
152 * ``-999999999 <= days <= 999999999``
153
154 If any argument is a float and there are fractional microseconds, the fractional
155 microseconds left over from all arguments are combined and their sum is rounded
156 to the nearest microsecond. If no argument is a float, the conversion and
157 normalization processes are exact (no information is lost).
158
159 If the normalized value of days lies outside the indicated range,
160 :exc:`OverflowError` is raised.
161
162 Note that normalization of negative values may be surprising at first. For
Georg Brandl3f043032008-03-22 21:21:57 +0000163 example,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000164
Georg Brandle40a6a82007-12-08 11:23:13 +0000165 >>> from datetime import timedelta
Georg Brandl8ec7f652007-08-15 14:28:01 +0000166 >>> d = timedelta(microseconds=-1)
167 >>> (d.days, d.seconds, d.microseconds)
168 (-1, 86399, 999999)
169
Georg Brandl8ec7f652007-08-15 14:28:01 +0000170
Georg Brandlb6453a92010-03-21 19:16:28 +0000171Class attributes are:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000172
173.. attribute:: timedelta.min
174
175 The most negative :class:`timedelta` object, ``timedelta(-999999999)``.
176
177
178.. attribute:: timedelta.max
179
180 The most positive :class:`timedelta` object, ``timedelta(days=999999999,
181 hours=23, minutes=59, seconds=59, microseconds=999999)``.
182
183
184.. attribute:: timedelta.resolution
185
186 The smallest possible difference between non-equal :class:`timedelta` objects,
187 ``timedelta(microseconds=1)``.
188
189Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``.
190``-timedelta.max`` is not representable as a :class:`timedelta` object.
191
192Instance attributes (read-only):
193
194+------------------+--------------------------------------------+
195| Attribute | Value |
196+==================+============================================+
197| ``days`` | Between -999999999 and 999999999 inclusive |
198+------------------+--------------------------------------------+
199| ``seconds`` | Between 0 and 86399 inclusive |
200+------------------+--------------------------------------------+
201| ``microseconds`` | Between 0 and 999999 inclusive |
202+------------------+--------------------------------------------+
203
204Supported operations:
205
Georg Brandlb19be572007-12-29 10:57:00 +0000206.. XXX this table is too wide!
Georg Brandl8ec7f652007-08-15 14:28:01 +0000207
208+--------------------------------+-----------------------------------------------+
209| Operation | Result |
210+================================+===============================================+
211| ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == |
212| | *t3* and *t1*-*t3* == *t2* are true. (1) |
213+--------------------------------+-----------------------------------------------+
214| ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* |
215| | == *t2* - *t3* and *t2* == *t1* + *t3* are |
216| | true. (1) |
217+--------------------------------+-----------------------------------------------+
218| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer or long. |
219| | Afterwards *t1* // i == *t2* is true, |
220| | provided ``i != 0``. |
221+--------------------------------+-----------------------------------------------+
222| | In general, *t1* \* i == *t1* \* (i-1) + *t1* |
223| | is true. (1) |
224+--------------------------------+-----------------------------------------------+
225| ``t1 = t2 // i`` | The floor is computed and the remainder (if |
226| | any) is thrown away. (3) |
227+--------------------------------+-----------------------------------------------+
228| ``+t1`` | Returns a :class:`timedelta` object with the |
229| | same value. (2) |
230+--------------------------------+-----------------------------------------------+
231| ``-t1`` | equivalent to :class:`timedelta`\ |
232| | (-*t1.days*, -*t1.seconds*, |
233| | -*t1.microseconds*), and to *t1*\* -1. (1)(4) |
234+--------------------------------+-----------------------------------------------+
Georg Brandl5d2eb342009-10-27 15:08:27 +0000235| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, and|
Georg Brandl8ec7f652007-08-15 14:28:01 +0000236| | to -*t* when ``t.days < 0``. (2) |
237+--------------------------------+-----------------------------------------------+
238
239Notes:
240
241(1)
242 This is exact, but may overflow.
243
244(2)
245 This is exact, and cannot overflow.
246
247(3)
248 Division by 0 raises :exc:`ZeroDivisionError`.
249
250(4)
251 -*timedelta.max* is not representable as a :class:`timedelta` object.
252
253In addition to the operations listed above :class:`timedelta` objects support
254certain additions and subtractions with :class:`date` and :class:`datetime`
255objects (see below).
256
257Comparisons of :class:`timedelta` objects are supported with the
258:class:`timedelta` object representing the smaller duration considered to be the
259smaller timedelta. In order to stop mixed-type comparisons from falling back to
260the default comparison by object address, when a :class:`timedelta` object is
261compared to an object of a different type, :exc:`TypeError` is raised unless the
262comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
263:const:`True`, respectively.
264
Georg Brandl7c3e79f2007-11-02 20:06:17 +0000265:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl8ec7f652007-08-15 14:28:01 +0000266efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
267considered to be true if and only if it isn't equal to ``timedelta(0)``.
268
Georg Brandl3f043032008-03-22 21:21:57 +0000269Example usage:
Georg Brandl734373c2009-01-03 21:55:17 +0000270
Georg Brandle40a6a82007-12-08 11:23:13 +0000271 >>> from datetime import timedelta
272 >>> year = timedelta(days=365)
Georg Brandl734373c2009-01-03 21:55:17 +0000273 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Georg Brandle40a6a82007-12-08 11:23:13 +0000274 ... minutes=50, seconds=600) # adds up to 365 days
275 >>> year == another_year
276 True
277 >>> ten_years = 10 * year
278 >>> ten_years, ten_years.days // 365
279 (datetime.timedelta(3650), 10)
280 >>> nine_years = ten_years - year
281 >>> nine_years, nine_years.days // 365
282 (datetime.timedelta(3285), 9)
283 >>> three_years = nine_years // 3;
284 >>> three_years, three_years.days // 365
285 (datetime.timedelta(1095), 3)
286 >>> abs(three_years - ten_years) == 2 * three_years + year
287 True
288
Georg Brandl8ec7f652007-08-15 14:28:01 +0000289
290.. _datetime-date:
291
292:class:`date` Objects
293---------------------
294
295A :class:`date` object represents a date (year, month and day) in an idealized
296calendar, the current Gregorian calendar indefinitely extended in both
297directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
298called day number 2, and so on. This matches the definition of the "proleptic
299Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
300where it's the base calendar for all computations. See the book for algorithms
301for converting between proleptic Gregorian ordinals and many other calendar
302systems.
303
304
305.. class:: date(year, month, day)
306
307 All arguments are required. Arguments may be ints or longs, in the following
308 ranges:
309
310 * ``MINYEAR <= year <= MAXYEAR``
311 * ``1 <= month <= 12``
312 * ``1 <= day <= number of days in the given month and year``
313
314 If an argument outside those ranges is given, :exc:`ValueError` is raised.
315
Georg Brandlb6453a92010-03-21 19:16:28 +0000316
Georg Brandl8ec7f652007-08-15 14:28:01 +0000317Other constructors, all class methods:
318
Georg Brandlb6453a92010-03-21 19:16:28 +0000319.. classmethod:: date.today()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000320
321 Return the current local date. This is equivalent to
322 ``date.fromtimestamp(time.time())``.
323
324
Georg Brandlb6453a92010-03-21 19:16:28 +0000325.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000326
327 Return the local date corresponding to the POSIX timestamp, such as is returned
328 by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out
329 of the range of values supported by the platform C :cfunc:`localtime` function.
330 It's common for this to be restricted to years from 1970 through 2038. Note
331 that on non-POSIX systems that include leap seconds in their notion of a
332 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
333
334
Georg Brandlb6453a92010-03-21 19:16:28 +0000335.. classmethod:: date.fromordinal(ordinal)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000336
337 Return the date corresponding to the proleptic Gregorian ordinal, where January
338 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
339 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
340 d``.
341
Georg Brandl8ec7f652007-08-15 14:28:01 +0000342
Georg Brandlb6453a92010-03-21 19:16:28 +0000343Class attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000344
345.. attribute:: date.min
346
347 The earliest representable date, ``date(MINYEAR, 1, 1)``.
348
349
350.. attribute:: date.max
351
352 The latest representable date, ``date(MAXYEAR, 12, 31)``.
353
354
355.. attribute:: date.resolution
356
357 The smallest possible difference between non-equal date objects,
358 ``timedelta(days=1)``.
359
Georg Brandl8ec7f652007-08-15 14:28:01 +0000360
Georg Brandlb6453a92010-03-21 19:16:28 +0000361Instance attributes (read-only):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000362
363.. attribute:: date.year
364
365 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
366
367
368.. attribute:: date.month
369
370 Between 1 and 12 inclusive.
371
372
373.. attribute:: date.day
374
375 Between 1 and the number of days in the given month of the given year.
376
Georg Brandlb6453a92010-03-21 19:16:28 +0000377
Georg Brandl8ec7f652007-08-15 14:28:01 +0000378Supported 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
Georg Brandl8ec7f652007-08-15 14:28:01 +0000430.. method:: date.replace(year, month, day)
431
432 Return a date with the same value, except for those members given new values by
433 whichever keyword arguments are specified. For example, if ``d == date(2002,
434 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
435
436
437.. method:: date.timetuple()
438
439 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
440 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
441 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
442 d.weekday(), d.toordinal() - date(d.year, 1, 1).toordinal() + 1, -1))``
443
444
445.. method:: date.toordinal()
446
447 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
448 has ordinal 1. For any :class:`date` object *d*,
449 ``date.fromordinal(d.toordinal()) == d``.
450
451
452.. method:: date.weekday()
453
454 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
455 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
456 :meth:`isoweekday`.
457
458
459.. method:: date.isoweekday()
460
461 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
462 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
463 :meth:`weekday`, :meth:`isocalendar`.
464
465
466.. method:: date.isocalendar()
467
468 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
469
470 The ISO calendar is a widely used variant of the Gregorian calendar. See
Mark Dickinson675b33a2009-11-03 16:27:23 +0000471 http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
472 explanation.
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Georg Brandlb6453a92010-03-21 19:16:28 +0000509 section :ref:`strftime-strptime-behavior`.
510
Georg Brandl8ec7f652007-08-15 14:28:01 +0000511
Georg Brandle40a6a82007-12-08 11:23:13 +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 Brandl734373c2009-01-03 21:55:17 +0000523 ... my_birthday = my_birthday.replace(year=today.year + 1)
Georg Brandle40a6a82007-12-08 11:23:13 +0000524 >>> my_birthday
525 datetime.date(2008, 6, 24)
Georg Brandl734373c2009-01-03 21:55:17 +0000526 >>> time_to_birthday = abs(my_birthday - today)
Georg Brandle40a6a82007-12-08 11:23:13 +0000527 >>> time_to_birthday.days
528 202
529
Georg Brandl3f043032008-03-22 21:21:57 +0000530Example of working with :class:`date`:
531
532.. doctest::
Georg Brandle40a6a82007-12-08 11:23:13 +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()
Georg Brandl3f043032008-03-22 21:21:57 +0000539 >>> for i in t: # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +0000540 ... print i
541 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()
Georg Brandl3f043032008-03-22 21:21:57 +0000551 >>> for i in ic: # doctest: +SKIP
552 ... print i
Georg Brandle40a6a82007-12-08 11:23:13 +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 Brandl8ec7f652007-08-15 14:28:01 +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
Georg Brandl8ec7f652007-08-15 14:28:01 +0000577.. class:: datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])
578
579 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
580 instance of a :class:`tzinfo` subclass. The remaining arguments may be ints or
581 longs, in the following ranges:
582
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
Georg Brandlb6453a92010-03-21 19:16:28 +0000595.. classmethod:: datetime.today()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000596
597 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
598 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
599 :meth:`fromtimestamp`.
600
601
Georg Brandlb6453a92010-03-21 19:16:28 +0000602.. classmethod:: datetime.now([tz])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000603
604 Return the current local date and time. If optional argument *tz* is ``None``
605 or not specified, this is like :meth:`today`, but, if possible, supplies more
606 precision than can be gotten from going through a :func:`time.time` timestamp
607 (for example, this may be possible on platforms supplying the C
608 :cfunc:`gettimeofday` function).
609
610 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
611 current date and time are converted to *tz*'s time zone. In this case the
612 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
613 See also :meth:`today`, :meth:`utcnow`.
614
615
Georg Brandlb6453a92010-03-21 19:16:28 +0000616.. classmethod:: datetime.utcnow()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000617
618 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
619 :meth:`now`, but returns the current UTC date and time, as a naive
620 :class:`datetime` object. See also :meth:`now`.
621
622
Georg Brandlb6453a92010-03-21 19:16:28 +0000623.. classmethod:: datetime.fromtimestamp(timestamp[, tz])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000624
625 Return the local date and time corresponding to the POSIX timestamp, such as is
626 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
627 specified, the timestamp is converted to the platform's local date and time, and
628 the returned :class:`datetime` object is naive.
629
630 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
631 timestamp is converted to *tz*'s time zone. In this case the result is
632 equivalent to
633 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
634
635 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
636 the range of values supported by the platform C :cfunc:`localtime` or
637 :cfunc:`gmtime` functions. It's common for this to be restricted to years in
638 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
639 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
640 and then it's possible to have two timestamps differing by a second that yield
641 identical :class:`datetime` objects. See also :meth:`utcfromtimestamp`.
642
643
Georg Brandlb6453a92010-03-21 19:16:28 +0000644.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000645
646 Return the UTC :class:`datetime` corresponding to the POSIX timestamp, with
647 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
648 out of the range of values supported by the platform C :cfunc:`gmtime` function.
649 It's common for this to be restricted to years in 1970 through 2038. See also
650 :meth:`fromtimestamp`.
651
652
Georg Brandlb6453a92010-03-21 19:16:28 +0000653.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000654
655 Return the :class:`datetime` corresponding to the proleptic Gregorian ordinal,
656 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
657 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
658 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
659
660
Georg Brandlb6453a92010-03-21 19:16:28 +0000661.. classmethod:: datetime.combine(date, time)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000662
663 Return a new :class:`datetime` object whose date members are equal to the given
664 :class:`date` object's, and whose time and :attr:`tzinfo` members are equal to
665 the given :class:`time` object's. For any :class:`datetime` object *d*, ``d ==
666 datetime.combine(d.date(), d.timetz())``. If date is a :class:`datetime`
667 object, its time and :attr:`tzinfo` members are ignored.
668
669
Georg Brandlb6453a92010-03-21 19:16:28 +0000670.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000671
672 Return a :class:`datetime` corresponding to *date_string*, parsed according to
673 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
674 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
675 can't be parsed by :func:`time.strptime` or if it returns a value which isn't a
Georg Brandlb6453a92010-03-21 19:16:28 +0000676 time tuple. See section :ref:`strftime-strptime-behavior`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000677
678 .. versionadded:: 2.5
679
Georg Brandl8ec7f652007-08-15 14:28:01 +0000680
Georg Brandlb6453a92010-03-21 19:16:28 +0000681Class attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000682
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
Georg Brandl8ec7f652007-08-15 14:28:01 +0000700
Georg Brandlb6453a92010-03-21 19:16:28 +0000701Instance attributes (read-only):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000702
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
Georg Brandlb6453a92010-03-21 19:16:28 +0000743
Georg Brandl8ec7f652007-08-15 14:28:01 +0000744Supported 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
Georg Brandl8ec7f652007-08-15 14:28:01 +0000817.. 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
954.. method:: datetime.isoformat([sep])
955
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,
Georg Brandl3f043032008-03-22 21:21:57 +0000966 placed between the date and time portions of the result. For example,
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Georg Brandlb6453a92010-03-21 19:16:28 +0000994 string. See section :ref:`strftime-strptime-behavior`.
995
Georg Brandl8ec7f652007-08-15 14:28:01 +0000996
Georg Brandl3f043032008-03-22 21:21:57 +0000997Examples of working with datetime objects:
998
999.. doctest::
1000
Georg Brandle40a6a82007-12-08 11:23:13 +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()
Georg Brandl3f043032008-03-22 21:21:57 +00001008 >>> datetime.now() # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +00001009 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Georg Brandl3f043032008-03-22 21:21:57 +00001010 >>> datetime.utcnow() # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +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()
Georg Brandl3f043032008-03-22 21:21:57 +00001018 >>> for it in tt: # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +00001019 ... print it
Georg Brandl734373c2009-01-03 21:55:17 +00001020 ...
Georg Brandle40a6a82007-12-08 11:23:13 +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()
Georg Brandl3f043032008-03-22 21:21:57 +00001032 >>> for it in ic: # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +00001033 ... print it
1034 ...
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
Georg Brandl3f043032008-03-22 21:21:57 +00001042Using datetime with tzinfo:
Georg Brandle40a6a82007-12-08 11:23:13 +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 Brandl734373c2009-01-03 21:55:17 +00001049 ... d = datetime(dt.year, 11, 1)
Georg Brandle40a6a82007-12-08 11:23:13 +00001050 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1051 ... def utcoffset(self, dt):
1052 ... return timedelta(hours=1) + self.dst(dt)
Georg Brandl734373c2009-01-03 21:55:17 +00001053 ... def dst(self, dt):
Georg Brandle40a6a82007-12-08 11:23:13 +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 Brandl734373c2009-01-03 21:55:17 +00001060 ...
Georg Brandle40a6a82007-12-08 11:23:13 +00001061 >>> class GMT2(tzinfo):
1062 ... def __init__(self):
Georg Brandl734373c2009-01-03 21:55:17 +00001063 ... d = datetime(dt.year, 4, 1)
Georg Brandle40a6a82007-12-08 11:23:13 +00001064 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl734373c2009-01-03 21:55:17 +00001065 ... d = datetime(dt.year, 11, 1)
Georg Brandle40a6a82007-12-08 11:23:13 +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 Brandl734373c2009-01-03 21:55:17 +00001076 ...
Georg Brandle40a6a82007-12-08 11:23:13 +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 Brandl734373c2009-01-03 21:55:17 +00001097
Georg Brandle40a6a82007-12-08 11:23:13 +00001098
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Georg Brandl8ec7f652007-08-15 14:28:01 +00001108.. class:: time(hour[, minute[, second[, microsecond[, tzinfo]]]])
1109
1110 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
1111 :class:`tzinfo` subclass. The remaining arguments may be ints or longs, in the
1112 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
Georg Brandl8ec7f652007-08-15 14:28:01 +00001141
Georg Brandlb6453a92010-03-21 19:16:28 +00001142Instance attributes (read-only):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001143
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
Georg Brandlb6453a92010-03-21 19:16:28 +00001169
Georg Brandl8ec7f652007-08-15 14:28:01 +00001170Supported 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
Georg Brandl8ec7f652007-08-15 14:28:01 +00001192
Georg Brandlb6453a92010-03-21 19:16:28 +00001193Instance methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001194
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.
Georg Brandlb6453a92010-03-21 19:16:28 +00001219 See section :ref:`strftime-strptime-behavior`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001220
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
Georg Brandlb6453a92010-03-21 19:16:28 +00001244
Georg Brandl3f043032008-03-22 21:21:57 +00001245Example:
Georg Brandl734373c2009-01-03 21:55:17 +00001246
Georg Brandle40a6a82007-12-08 11:23:13 +00001247 >>> from datetime import time, tzinfo
1248 >>> class GMT1(tzinfo):
1249 ... def utcoffset(self, dt):
Georg Brandl734373c2009-01-03 21:55:17 +00001250 ... return timedelta(hours=1)
1251 ... def dst(self, dt):
Georg Brandle40a6a82007-12-08 11:23:13 +00001252 ... return timedelta(0)
1253 ... def tzname(self,dt):
1254 ... return "Europe/Prague"
1255 ...
1256 >>> t = time(12, 10, 30, tzinfo=GMT1())
1257 >>> t # doctest: +ELLIPSIS
1258 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1259 >>> gmt = GMT1()
1260 >>> t.isoformat()
1261 '12:10:30+01:00'
1262 >>> t.dst()
1263 datetime.timedelta(0)
1264 >>> t.tzname()
1265 'Europe/Prague'
1266 >>> t.strftime("%H:%M:%S %Z")
1267 '12:10:30 Europe/Prague'
1268
Georg Brandl8ec7f652007-08-15 14:28:01 +00001269
1270.. _datetime-tzinfo:
1271
1272:class:`tzinfo` Objects
1273-----------------------
1274
Brett Cannone4b6ab72009-01-29 03:58:16 +00001275:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl8ec7f652007-08-15 14:28:01 +00001276instantiated directly. You need to derive a concrete subclass, and (at least)
1277supply implementations of the standard :class:`tzinfo` methods needed by the
1278:class:`datetime` methods you use. The :mod:`datetime` module does not supply
1279any concrete subclasses of :class:`tzinfo`.
1280
1281An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1282constructors for :class:`datetime` and :class:`time` objects. The latter objects
1283view their members as being in local time, and the :class:`tzinfo` object
1284supports methods revealing offset of local time from UTC, the name of the time
1285zone, and DST offset, all relative to a date or time object passed to them.
1286
1287Special requirement for pickling: A :class:`tzinfo` subclass must have an
1288:meth:`__init__` method that can be called with no arguments, else it can be
1289pickled but possibly not unpickled again. This is a technical requirement that
1290may be relaxed in the future.
1291
1292A concrete subclass of :class:`tzinfo` may need to implement the following
1293methods. Exactly which methods are needed depends on the uses made of aware
1294:mod:`datetime` objects. If in doubt, simply implement all of them.
1295
1296
1297.. method:: tzinfo.utcoffset(self, dt)
1298
1299 Return offset of local time from UTC, in minutes east of UTC. If local time is
1300 west of UTC, this should be negative. Note that this is intended to be the
1301 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1302 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1303 the UTC offset isn't known, return ``None``. Else the value returned must be a
1304 :class:`timedelta` object specifying a whole number of minutes in the range
1305 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1306 than one day). Most implementations of :meth:`utcoffset` will probably look
1307 like one of these two::
1308
1309 return CONSTANT # fixed-offset class
1310 return CONSTANT + self.dst(dt) # daylight-aware class
1311
1312 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1313 ``None`` either.
1314
1315 The default implementation of :meth:`utcoffset` raises
1316 :exc:`NotImplementedError`.
1317
1318
1319.. method:: tzinfo.dst(self, dt)
1320
1321 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1322 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1323 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1324 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1325 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1326 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1327 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
1328 member's :meth:`dst` method to determine how the :attr:`tm_isdst` flag should be
1329 set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for DST changes
1330 when crossing time zones.
1331
1332 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1333 daylight times must be consistent in this sense:
1334
1335 ``tz.utcoffset(dt) - tz.dst(dt)``
1336
1337 must return the same result for every :class:`datetime` *dt* with ``dt.tzinfo ==
1338 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1339 zone's "standard offset", which should not depend on the date or the time, but
1340 only on geographic location. The implementation of :meth:`datetime.astimezone`
1341 relies on this, but cannot detect violations; it's the programmer's
1342 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1343 this, it may be able to override the default implementation of
1344 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1345
1346 Most implementations of :meth:`dst` will probably look like one of these two::
1347
1348 def dst(self):
1349 # a fixed-offset class: doesn't account for DST
1350 return timedelta(0)
1351
1352 or ::
1353
1354 def dst(self):
1355 # Code to set dston and dstoff to the time zone's DST
1356 # transition times based on the input dt.year, and expressed
1357 # in standard local time. Then
1358
1359 if dston <= dt.replace(tzinfo=None) < dstoff:
1360 return timedelta(hours=1)
1361 else:
1362 return timedelta(0)
1363
1364 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1365
1366
1367.. method:: tzinfo.tzname(self, dt)
1368
1369 Return the time zone name corresponding to the :class:`datetime` object *dt*, as
1370 a string. Nothing about string names is defined by the :mod:`datetime` module,
1371 and there's no requirement that it mean anything in particular. For example,
1372 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1373 valid replies. Return ``None`` if a string name isn't known. Note that this is
1374 a method rather than a fixed string primarily because some :class:`tzinfo`
1375 subclasses will wish to return different names depending on the specific value
1376 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1377 daylight time.
1378
1379 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1380
Georg Brandlb6453a92010-03-21 19:16:28 +00001381
Georg Brandl8ec7f652007-08-15 14:28:01 +00001382These methods are called by a :class:`datetime` or :class:`time` object, in
1383response to their methods of the same names. A :class:`datetime` object passes
1384itself as the argument, and a :class:`time` object passes ``None`` as the
1385argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
1386accept a *dt* argument of ``None``, or of class :class:`datetime`.
1387
1388When ``None`` is passed, it's up to the class designer to decide the best
1389response. For example, returning ``None`` is appropriate if the class wishes to
1390say that time objects don't participate in the :class:`tzinfo` protocols. It
1391may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1392there is no other convention for discovering the standard offset.
1393
1394When a :class:`datetime` object is passed in response to a :class:`datetime`
1395method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1396rely on this, unless user code calls :class:`tzinfo` methods directly. The
1397intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1398time, and not need worry about objects in other timezones.
1399
1400There is one more :class:`tzinfo` method that a subclass may wish to override:
1401
1402
1403.. method:: tzinfo.fromutc(self, dt)
1404
1405 This is called from the default :class:`datetime.astimezone()` implementation.
1406 When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members
1407 are to be viewed as expressing a UTC time. The purpose of :meth:`fromutc` is to
1408 adjust the date and time members, returning an equivalent datetime in *self*'s
1409 local time.
1410
1411 Most :class:`tzinfo` subclasses should be able to inherit the default
1412 :meth:`fromutc` implementation without problems. It's strong enough to handle
1413 fixed-offset time zones, and time zones accounting for both standard and
1414 daylight time, and the latter even if the DST transition times differ in
1415 different years. An example of a time zone the default :meth:`fromutc`
1416 implementation may not handle correctly in all cases is one where the standard
1417 offset (from UTC) depends on the specific date and time passed, which can happen
1418 for political reasons. The default implementations of :meth:`astimezone` and
1419 :meth:`fromutc` may not produce the result you want if the result is one of the
1420 hours straddling the moment the standard offset changes.
1421
1422 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1423 like::
1424
1425 def fromutc(self, dt):
1426 # raise ValueError error if dt.tzinfo is not self
1427 dtoff = dt.utcoffset()
1428 dtdst = dt.dst()
1429 # raise ValueError if dtoff is None or dtdst is None
1430 delta = dtoff - dtdst # this is self's standard offset
1431 if delta:
1432 dt += delta # convert to standard local time
1433 dtdst = dt.dst()
1434 # raise ValueError if dtdst is None
1435 if dtdst:
1436 return dt + dtdst
1437 else:
1438 return dt
1439
1440Example :class:`tzinfo` classes:
1441
1442.. literalinclude:: ../includes/tzinfo-examples.py
1443
1444
1445Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1446subclass accounting for both standard and daylight time, at the DST transition
1447points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandl4c86cb32010-03-21 19:34:26 +00001448minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
14491:59 (EDT) on the first Sunday in November::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001450
1451 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1452 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1453 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1454
1455 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1456
1457 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1458
1459When DST starts (the "start" line), the local wall clock leaps from 1:59 to
14603:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1461``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1462begins. In order for :meth:`astimezone` to make this guarantee, the
1463:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1464Eastern) to be in daylight time.
1465
1466When DST ends (the "end" line), there's a potentially worse problem: there's an
1467hour that can't be spelled unambiguously in local wall time: the last hour of
1468daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1469daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1470to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1471:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1472hours into the same local hour then. In the Eastern example, UTC times of the
1473form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1474:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1475consider times in the "repeated hour" to be in standard time. This is easily
1476arranged, as in the example, by expressing DST switch times in the time zone's
1477standard local time.
1478
1479Applications that can't bear such ambiguities should avoid using hybrid
1480:class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any
1481other fixed-offset :class:`tzinfo` subclass (such as a class representing only
1482EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
Georg Brandl734373c2009-01-03 21:55:17 +00001483
Georg Brandl8ec7f652007-08-15 14:28:01 +00001484
Georg Brandlb6453a92010-03-21 19:16:28 +00001485.. _strftime-strptime-behavior:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001486
Georg Brandlb6453a92010-03-21 19:16:28 +00001487:meth:`strftime` and :meth:`strptime` Behavior
1488----------------------------------------------
Georg Brandl8ec7f652007-08-15 14:28:01 +00001489
1490:class:`date`, :class:`datetime`, and :class:`time` objects all support a
1491``strftime(format)`` method, to create a string representing the time under the
1492control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1493acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1494although not all objects support a :meth:`timetuple` method.
1495
Georg Brandlb6453a92010-03-21 19:16:28 +00001496Conversely, the :meth:`datetime.strptime` class method creates a
1497:class:`datetime` object from a string representing a date and time and a
1498corresponding format string. ``datetime.strptime(date_string, format)`` is
1499equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1500
Georg Brandl8ec7f652007-08-15 14:28:01 +00001501For :class:`time` objects, the format codes for year, month, and day should not
1502be used, as time objects have no such values. If they're used anyway, ``1900``
Georg Brandlb6453a92010-03-21 19:16:28 +00001503is substituted for the year, and ``1`` for the month and day.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001504
Skip Montanarofc070d22008-03-15 16:04:45 +00001505For :class:`date` objects, the format codes for hours, minutes, seconds, and
1506microseconds should not be used, as :class:`date` objects have no such
1507values. If they're used anyway, ``0`` is substituted for them.
1508
Skip Montanarofc070d22008-03-15 16:04:45 +00001509.. versionadded:: 2.6
Georg Brandlec7d3902009-02-23 10:41:11 +00001510 :class:`time` and :class:`datetime` objects support a ``%f`` format code
1511 which expands to the number of microseconds in the object, zero-padded on
1512 the left to six places.
Skip Montanarofc070d22008-03-15 16:04:45 +00001513
1514For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1515strings.
1516
1517For an aware object:
1518
1519``%z``
1520 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1521 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1522 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1523 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1524 replaced with the string ``'-0330'``.
1525
1526``%Z``
1527 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1528 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001529
Georg Brandl8ec7f652007-08-15 14:28:01 +00001530The full set of format codes supported varies across platforms, because Python
1531calls the platform C library's :func:`strftime` function, and platform
Georg Brandl734373c2009-01-03 21:55:17 +00001532variations are common.
Georg Brandle40a6a82007-12-08 11:23:13 +00001533
1534The following is a list of all the format codes that the C standard (1989
1535version) requires, and these work on all platforms with a standard C
1536implementation. Note that the 1999 version of the C standard added additional
1537format codes.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001538
1539The exact range of years for which :meth:`strftime` works also varies across
1540platforms. Regardless of platform, years before 1900 cannot be used.
1541
Georg Brandle40a6a82007-12-08 11:23:13 +00001542+-----------+--------------------------------+-------+
1543| Directive | Meaning | Notes |
1544+===========+================================+=======+
1545| ``%a`` | Locale's abbreviated weekday | |
1546| | name. | |
1547+-----------+--------------------------------+-------+
1548| ``%A`` | Locale's full weekday name. | |
1549+-----------+--------------------------------+-------+
1550| ``%b`` | Locale's abbreviated month | |
1551| | name. | |
1552+-----------+--------------------------------+-------+
1553| ``%B`` | Locale's full month name. | |
1554+-----------+--------------------------------+-------+
1555| ``%c`` | Locale's appropriate date and | |
1556| | time representation. | |
1557+-----------+--------------------------------+-------+
1558| ``%d`` | Day of the month as a decimal | |
1559| | number [01,31]. | |
1560+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001561| ``%f`` | Microsecond as a decimal | \(1) |
1562| | number [0,999999], zero-padded | |
1563| | on the left | |
1564+-----------+--------------------------------+-------+
Georg Brandle40a6a82007-12-08 11:23:13 +00001565| ``%H`` | Hour (24-hour clock) as a | |
1566| | decimal number [00,23]. | |
1567+-----------+--------------------------------+-------+
1568| ``%I`` | Hour (12-hour clock) as a | |
1569| | decimal number [01,12]. | |
1570+-----------+--------------------------------+-------+
1571| ``%j`` | Day of the year as a decimal | |
1572| | number [001,366]. | |
1573+-----------+--------------------------------+-------+
1574| ``%m`` | Month as a decimal number | |
1575| | [01,12]. | |
1576+-----------+--------------------------------+-------+
1577| ``%M`` | Minute as a decimal number | |
1578| | [00,59]. | |
1579+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001580| ``%p`` | Locale's equivalent of either | \(2) |
Georg Brandle40a6a82007-12-08 11:23:13 +00001581| | AM or PM. | |
1582+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001583| ``%S`` | Second as a decimal number | \(3) |
Georg Brandle40a6a82007-12-08 11:23:13 +00001584| | [00,61]. | |
1585+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001586| ``%U`` | Week number of the year | \(4) |
Georg Brandle40a6a82007-12-08 11:23:13 +00001587| | (Sunday as the first day of | |
1588| | the week) as a decimal number | |
1589| | [00,53]. All days in a new | |
1590| | year preceding the first | |
1591| | Sunday are considered to be in | |
1592| | week 0. | |
1593+-----------+--------------------------------+-------+
1594| ``%w`` | Weekday as a decimal number | |
1595| | [0(Sunday),6]. | |
1596+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001597| ``%W`` | Week number of the year | \(4) |
Georg Brandle40a6a82007-12-08 11:23:13 +00001598| | (Monday as the first day of | |
1599| | the week) as a decimal number | |
1600| | [00,53]. All days in a new | |
1601| | year preceding the first | |
1602| | Monday are considered to be in | |
1603| | week 0. | |
1604+-----------+--------------------------------+-------+
1605| ``%x`` | Locale's appropriate date | |
1606| | representation. | |
1607+-----------+--------------------------------+-------+
1608| ``%X`` | Locale's appropriate time | |
1609| | representation. | |
1610+-----------+--------------------------------+-------+
1611| ``%y`` | Year without century as a | |
1612| | decimal number [00,99]. | |
1613+-----------+--------------------------------+-------+
1614| ``%Y`` | Year with century as a decimal | |
1615| | number. | |
1616+-----------+--------------------------------+-------+
Skip Montanarofc070d22008-03-15 16:04:45 +00001617| ``%z`` | UTC offset in the form +HHMM | \(5) |
Georg Brandle40a6a82007-12-08 11:23:13 +00001618| | or -HHMM (empty string if the | |
1619| | the object is naive). | |
1620+-----------+--------------------------------+-------+
1621| ``%Z`` | Time zone name (empty string | |
1622| | if the object is naive). | |
1623+-----------+--------------------------------+-------+
1624| ``%%`` | A literal ``'%'`` character. | |
1625+-----------+--------------------------------+-------+
Georg Brandl8ec7f652007-08-15 14:28:01 +00001626
Georg Brandle40a6a82007-12-08 11:23:13 +00001627Notes:
1628
1629(1)
Georg Brandlb6453a92010-03-21 19:16:28 +00001630 When used with the :meth:`strptime` method, the ``%f`` directive
Skip Montanarofc070d22008-03-15 16:04:45 +00001631 accepts from one to six digits and zero pads on the right. ``%f`` is
Georg Brandlec7d3902009-02-23 10:41:11 +00001632 an extension to the set of format characters in the C standard (but
1633 implemented separately in datetime objects, and therefore always
1634 available).
Skip Montanarofc070d22008-03-15 16:04:45 +00001635
1636(2)
Georg Brandlb6453a92010-03-21 19:16:28 +00001637 When used with the :meth:`strptime` method, the ``%p`` directive only affects
Georg Brandle40a6a82007-12-08 11:23:13 +00001638 the output hour field if the ``%I`` directive is used to parse the hour.
1639
Skip Montanarofc070d22008-03-15 16:04:45 +00001640(3)
R. David Murraydc362b02009-04-02 04:52:48 +00001641 The range really is ``0`` to ``61``; according to the Posix standard this
1642 accounts for leap seconds and the (very rare) double leap seconds.
1643 The :mod:`time` module may produce and does accept leap seconds since
1644 it is based on the Posix standard, but the :mod:`datetime` module
Georg Brandlb6453a92010-03-21 19:16:28 +00001645 does not accept leap seconds in :meth:`strptime` input nor will it
R. David Murraydc362b02009-04-02 04:52:48 +00001646 produce them in :func:`strftime` output.
Georg Brandle40a6a82007-12-08 11:23:13 +00001647
Skip Montanarofc070d22008-03-15 16:04:45 +00001648(4)
Georg Brandlb6453a92010-03-21 19:16:28 +00001649 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in
Georg Brandle40a6a82007-12-08 11:23:13 +00001650 calculations when the day of the week and the year are specified.
1651
Skip Montanarofc070d22008-03-15 16:04:45 +00001652(5)
Georg Brandle40a6a82007-12-08 11:23:13 +00001653 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1654 ``%z`` is replaced with the string ``'-0330'``.