blob: edcd1f1f8e9c40a57a133a443525be7cf870af5a [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
Georg Brandl116aa622007-08-15 14:28:22 +000039.. data:: MINYEAR
40
41 The smallest year number allowed in a :class:`date` or :class:`datetime` object.
42 :const:`MINYEAR` is ``1``.
43
44
45.. data:: MAXYEAR
46
47 The largest year number allowed in a :class:`date` or :class:`datetime` object.
48 :const:`MAXYEAR` is ``9999``.
49
50
51.. seealso::
52
53 Module :mod:`calendar`
54 General calendar related functions.
55
56 Module :mod:`time`
57 Time access and conversions.
58
59
60Available Types
61---------------
62
Georg Brandl116aa622007-08-15 14:28:22 +000063.. class:: date
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000064 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000065
66 An idealized naive date, assuming the current Gregorian calendar always was, and
67 always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and
68 :attr:`day`.
69
70
71.. class:: time
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000072 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000073
74 An idealized time, independent of any particular day, assuming that every day
75 has exactly 24\*60\*60 seconds (there is no notion of "leap seconds" here).
76 Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
77 and :attr:`tzinfo`.
78
79
80.. class:: datetime
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000081 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000082
83 A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`,
84 :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
85 and :attr:`tzinfo`.
86
87
88.. class:: timedelta
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000089 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000090
91 A duration expressing the difference between two :class:`date`, :class:`time`,
92 or :class:`datetime` instances to microsecond resolution.
93
94
95.. class:: tzinfo
96
97 An abstract base class for time zone information objects. These are used by the
98 :class:`datetime` and :class:`time` classes to provide a customizable notion of
99 time adjustment (for example, to account for time zone and/or daylight saving
100 time).
101
102Objects of these types are immutable.
103
104Objects of the :class:`date` type are always naive.
105
106An object *d* of type :class:`time` or :class:`datetime` may be naive or aware.
107*d* is aware if ``d.tzinfo`` is not ``None`` and ``d.tzinfo.utcoffset(d)`` does
108not return ``None``. If ``d.tzinfo`` is ``None``, or if ``d.tzinfo`` is not
109``None`` but ``d.tzinfo.utcoffset(d)`` returns ``None``, *d* is naive.
110
111The distinction between naive and aware doesn't apply to :class:`timedelta`
112objects.
113
114Subclass relationships::
115
116 object
117 timedelta
118 tzinfo
119 time
120 date
121 datetime
122
123
124.. _datetime-timedelta:
125
126:class:`timedelta` Objects
127--------------------------
128
129A :class:`timedelta` object represents a duration, the difference between two
130dates or times.
131
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000132.. class:: timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000133
Georg Brandl5c106642007-11-29 17:41:05 +0000134 All arguments are optional and default to ``0``. Arguments may be integers
Georg Brandl116aa622007-08-15 14:28:22 +0000135 or floats, and may be positive or negative.
136
137 Only *days*, *seconds* and *microseconds* are stored internally. Arguments are
138 converted to those units:
139
140 * A millisecond is converted to 1000 microseconds.
141 * A minute is converted to 60 seconds.
142 * An hour is converted to 3600 seconds.
143 * A week is converted to 7 days.
144
145 and days, seconds and microseconds are then normalized so that the
146 representation is unique, with
147
148 * ``0 <= microseconds < 1000000``
149 * ``0 <= seconds < 3600*24`` (the number of seconds in one day)
150 * ``-999999999 <= days <= 999999999``
151
152 If any argument is a float and there are fractional microseconds, the fractional
153 microseconds left over from all arguments are combined and their sum is rounded
154 to the nearest microsecond. If no argument is a float, the conversion and
155 normalization processes are exact (no information is lost).
156
157 If the normalized value of days lies outside the indicated range,
158 :exc:`OverflowError` is raised.
159
160 Note that normalization of negative values may be surprising at first. For
Christian Heimesfe337bf2008-03-23 21:54:12 +0000161 example,
Georg Brandl116aa622007-08-15 14:28:22 +0000162
Christian Heimes895627f2007-12-08 17:28:33 +0000163 >>> from datetime import timedelta
Georg Brandl116aa622007-08-15 14:28:22 +0000164 >>> d = timedelta(microseconds=-1)
165 >>> (d.days, d.seconds, d.microseconds)
166 (-1, 86399, 999999)
167
Georg Brandl116aa622007-08-15 14:28:22 +0000168
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000169Class attributes are:
Georg Brandl116aa622007-08-15 14:28:22 +0000170
171.. attribute:: timedelta.min
172
173 The most negative :class:`timedelta` object, ``timedelta(-999999999)``.
174
175
176.. attribute:: timedelta.max
177
178 The most positive :class:`timedelta` object, ``timedelta(days=999999999,
179 hours=23, minutes=59, seconds=59, microseconds=999999)``.
180
181
182.. attribute:: timedelta.resolution
183
184 The smallest possible difference between non-equal :class:`timedelta` objects,
185 ``timedelta(microseconds=1)``.
186
187Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``.
188``-timedelta.max`` is not representable as a :class:`timedelta` object.
189
190Instance attributes (read-only):
191
192+------------------+--------------------------------------------+
193| Attribute | Value |
194+==================+============================================+
195| ``days`` | Between -999999999 and 999999999 inclusive |
196+------------------+--------------------------------------------+
197| ``seconds`` | Between 0 and 86399 inclusive |
198+------------------+--------------------------------------------+
199| ``microseconds`` | Between 0 and 999999 inclusive |
200+------------------+--------------------------------------------+
201
202Supported operations:
203
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000204.. XXX this table is too wide!
Georg Brandl116aa622007-08-15 14:28:22 +0000205
206+--------------------------------+-----------------------------------------------+
207| Operation | Result |
208+================================+===============================================+
209| ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == |
210| | *t3* and *t1*-*t3* == *t2* are true. (1) |
211+--------------------------------+-----------------------------------------------+
212| ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* |
213| | == *t2* - *t3* and *t2* == *t1* + *t3* are |
214| | true. (1) |
215+--------------------------------+-----------------------------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000216| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer. |
Georg Brandl116aa622007-08-15 14:28:22 +0000217| | Afterwards *t1* // i == *t2* is true, |
218| | provided ``i != 0``. |
219+--------------------------------+-----------------------------------------------+
220| | In general, *t1* \* i == *t1* \* (i-1) + *t1* |
221| | is true. (1) |
222+--------------------------------+-----------------------------------------------+
223| ``t1 = t2 // i`` | The floor is computed and the remainder (if |
224| | any) is thrown away. (3) |
225+--------------------------------+-----------------------------------------------+
226| ``+t1`` | Returns a :class:`timedelta` object with the |
227| | same value. (2) |
228+--------------------------------+-----------------------------------------------+
229| ``-t1`` | equivalent to :class:`timedelta`\ |
230| | (-*t1.days*, -*t1.seconds*, |
231| | -*t1.microseconds*), and to *t1*\* -1. (1)(4) |
232+--------------------------------+-----------------------------------------------+
Georg Brandl495f7b52009-10-27 15:28:25 +0000233| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, and|
Georg Brandl116aa622007-08-15 14:28:22 +0000234| | to -*t* when ``t.days < 0``. (2) |
235+--------------------------------+-----------------------------------------------+
236
237Notes:
238
239(1)
240 This is exact, but may overflow.
241
242(2)
243 This is exact, and cannot overflow.
244
245(3)
246 Division by 0 raises :exc:`ZeroDivisionError`.
247
248(4)
249 -*timedelta.max* is not representable as a :class:`timedelta` object.
250
251In addition to the operations listed above :class:`timedelta` objects support
252certain additions and subtractions with :class:`date` and :class:`datetime`
253objects (see below).
254
255Comparisons of :class:`timedelta` objects are supported with the
256:class:`timedelta` object representing the smaller duration considered to be the
257smaller timedelta. In order to stop mixed-type comparisons from falling back to
258the default comparison by object address, when a :class:`timedelta` object is
259compared to an object of a different type, :exc:`TypeError` is raised unless the
260comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
261:const:`True`, respectively.
262
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000263:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl116aa622007-08-15 14:28:22 +0000264efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
265considered to be true if and only if it isn't equal to ``timedelta(0)``.
266
Antoine Pitroube6859d2009-11-25 23:02:32 +0000267Instance methods:
268
269.. method:: timedelta.total_seconds()
270
271 Return the total number of seconds contained in the duration. Equivalent to
272 ``td.microseconds / 1000000 + td.seconds + td.days * 24 * 3600``.
273
274 .. versionadded:: 3.2
275
276
Christian Heimesfe337bf2008-03-23 21:54:12 +0000277Example usage:
Georg Brandl48310cd2009-01-03 21:18:54 +0000278
Christian Heimes895627f2007-12-08 17:28:33 +0000279 >>> from datetime import timedelta
280 >>> year = timedelta(days=365)
Georg Brandl48310cd2009-01-03 21:18:54 +0000281 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Christian Heimes895627f2007-12-08 17:28:33 +0000282 ... minutes=50, seconds=600) # adds up to 365 days
Antoine Pitroube6859d2009-11-25 23:02:32 +0000283 >>> year.total_seconds()
284 31536000.0
Christian Heimes895627f2007-12-08 17:28:33 +0000285 >>> year == another_year
286 True
287 >>> ten_years = 10 * year
288 >>> ten_years, ten_years.days // 365
289 (datetime.timedelta(3650), 10)
290 >>> nine_years = ten_years - year
291 >>> nine_years, nine_years.days // 365
292 (datetime.timedelta(3285), 9)
293 >>> three_years = nine_years // 3;
294 >>> three_years, three_years.days // 365
295 (datetime.timedelta(1095), 3)
296 >>> abs(three_years - ten_years) == 2 * three_years + year
297 True
298
Georg Brandl116aa622007-08-15 14:28:22 +0000299
300.. _datetime-date:
301
302:class:`date` Objects
303---------------------
304
305A :class:`date` object represents a date (year, month and day) in an idealized
306calendar, the current Gregorian calendar indefinitely extended in both
307directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
308called day number 2, and so on. This matches the definition of the "proleptic
309Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
310where it's the base calendar for all computations. See the book for algorithms
311for converting between proleptic Gregorian ordinals and many other calendar
312systems.
313
314
315.. class:: date(year, month, day)
316
Georg Brandl5c106642007-11-29 17:41:05 +0000317 All arguments are required. Arguments may be integers, in the following
Georg Brandl116aa622007-08-15 14:28:22 +0000318 ranges:
319
320 * ``MINYEAR <= year <= MAXYEAR``
321 * ``1 <= month <= 12``
322 * ``1 <= day <= number of days in the given month and year``
323
324 If an argument outside those ranges is given, :exc:`ValueError` is raised.
325
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000326
Georg Brandl116aa622007-08-15 14:28:22 +0000327Other constructors, all class methods:
328
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000329.. classmethod:: date.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000330
331 Return the current local date. This is equivalent to
332 ``date.fromtimestamp(time.time())``.
333
334
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000335.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000336
337 Return the local date corresponding to the POSIX timestamp, such as is returned
338 by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out
339 of the range of values supported by the platform C :cfunc:`localtime` function.
340 It's common for this to be restricted to years from 1970 through 2038. Note
341 that on non-POSIX systems that include leap seconds in their notion of a
342 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
343
344
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000345.. classmethod:: date.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000346
347 Return the date corresponding to the proleptic Gregorian ordinal, where January
348 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
349 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
350 d``.
351
Georg Brandl116aa622007-08-15 14:28:22 +0000352
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000353Class attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000354
355.. attribute:: date.min
356
357 The earliest representable date, ``date(MINYEAR, 1, 1)``.
358
359
360.. attribute:: date.max
361
362 The latest representable date, ``date(MAXYEAR, 12, 31)``.
363
364
365.. attribute:: date.resolution
366
367 The smallest possible difference between non-equal date objects,
368 ``timedelta(days=1)``.
369
Georg Brandl116aa622007-08-15 14:28:22 +0000370
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000371Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000372
373.. attribute:: date.year
374
375 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
376
377
378.. attribute:: date.month
379
380 Between 1 and 12 inclusive.
381
382
383.. attribute:: date.day
384
385 Between 1 and the number of days in the given month of the given year.
386
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000387
Georg Brandl116aa622007-08-15 14:28:22 +0000388Supported operations:
389
390+-------------------------------+----------------------------------------------+
391| Operation | Result |
392+===============================+==============================================+
393| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
394| | from *date1*. (1) |
395+-------------------------------+----------------------------------------------+
396| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
397| | timedelta == date1``. (2) |
398+-------------------------------+----------------------------------------------+
399| ``timedelta = date1 - date2`` | \(3) |
400+-------------------------------+----------------------------------------------+
401| ``date1 < date2`` | *date1* is considered less than *date2* when |
402| | *date1* precedes *date2* in time. (4) |
403+-------------------------------+----------------------------------------------+
404
405Notes:
406
407(1)
408 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
409 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
410 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
411 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
412 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
413
414(2)
415 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
416 isolation can overflow in cases where date1 - timedelta does not.
417 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
418
419(3)
420 This is exact, and cannot overflow. timedelta.seconds and
421 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
422
423(4)
424 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
425 date2.toordinal()``. In order to stop comparison from falling back to the
426 default scheme of comparing object addresses, date comparison normally raises
427 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
428 However, ``NotImplemented`` is returned instead if the other comparand has a
429 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
430 chance at implementing mixed-type comparison. If not, when a :class:`date`
431 object is compared to an object of a different type, :exc:`TypeError` is raised
432 unless the comparison is ``==`` or ``!=``. The latter cases return
433 :const:`False` or :const:`True`, respectively.
434
435Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
436objects are considered to be true.
437
438Instance methods:
439
Georg Brandl116aa622007-08-15 14:28:22 +0000440.. method:: date.replace(year, month, day)
441
442 Return a date with the same value, except for those members given new values by
443 whichever keyword arguments are specified. For example, if ``d == date(2002,
444 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
445
446
447.. method:: date.timetuple()
448
449 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
450 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
451 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
452 d.weekday(), d.toordinal() - date(d.year, 1, 1).toordinal() + 1, -1))``
453
454
455.. method:: date.toordinal()
456
457 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
458 has ordinal 1. For any :class:`date` object *d*,
459 ``date.fromordinal(d.toordinal()) == d``.
460
461
462.. method:: date.weekday()
463
464 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
465 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
466 :meth:`isoweekday`.
467
468
469.. method:: date.isoweekday()
470
471 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
472 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
473 :meth:`weekday`, :meth:`isocalendar`.
474
475
476.. method:: date.isocalendar()
477
478 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
479
480 The ISO calendar is a widely used variant of the Gregorian calendar. See
Mark Dickinsonf964ac22009-11-03 16:29:10 +0000481 http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
482 explanation.
Georg Brandl116aa622007-08-15 14:28:22 +0000483
484 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
485 Monday and ends on a Sunday. The first week of an ISO year is the first
486 (Gregorian) calendar week of a year containing a Thursday. This is called week
487 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
488
489 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
490 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
491 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
492 4).isocalendar() == (2004, 1, 7)``.
493
494
495.. method:: date.isoformat()
496
497 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
498 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
499
500
501.. method:: date.__str__()
502
503 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
504
505
506.. method:: date.ctime()
507
508 Return a string representing the date, for example ``date(2002, 12,
509 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
510 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
511 :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
512 :meth:`date.ctime` does not invoke) conforms to the C standard.
513
514
515.. method:: date.strftime(format)
516
517 Return a string representing the date, controlled by an explicit format string.
518 Format codes referring to hours, minutes or seconds will see 0 values. See
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000519 section :ref:`strftime-strptime-behavior`.
520
Georg Brandl116aa622007-08-15 14:28:22 +0000521
Christian Heimes895627f2007-12-08 17:28:33 +0000522Example of counting days to an event::
523
524 >>> import time
525 >>> from datetime import date
526 >>> today = date.today()
527 >>> today
528 datetime.date(2007, 12, 5)
529 >>> today == date.fromtimestamp(time.time())
530 True
531 >>> my_birthday = date(today.year, 6, 24)
532 >>> if my_birthday < today:
Georg Brandl48310cd2009-01-03 21:18:54 +0000533 ... my_birthday = my_birthday.replace(year=today.year + 1)
Christian Heimes895627f2007-12-08 17:28:33 +0000534 >>> my_birthday
535 datetime.date(2008, 6, 24)
Georg Brandl48310cd2009-01-03 21:18:54 +0000536 >>> time_to_birthday = abs(my_birthday - today)
Christian Heimes895627f2007-12-08 17:28:33 +0000537 >>> time_to_birthday.days
538 202
539
Christian Heimesfe337bf2008-03-23 21:54:12 +0000540Example of working with :class:`date`:
541
542.. doctest::
Christian Heimes895627f2007-12-08 17:28:33 +0000543
544 >>> from datetime import date
545 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
546 >>> d
547 datetime.date(2002, 3, 11)
548 >>> t = d.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000549 >>> for i in t: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000550 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000551 2002 # year
552 3 # month
553 11 # day
554 0
555 0
556 0
557 0 # weekday (0 = Monday)
558 70 # 70th day in the year
559 -1
560 >>> ic = d.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +0000561 >>> for i in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +0000562 ... print(i)
Christian Heimes895627f2007-12-08 17:28:33 +0000563 2002 # ISO year
564 11 # ISO week number
565 1 # ISO day number ( 1 = Monday )
566 >>> d.isoformat()
567 '2002-03-11'
568 >>> d.strftime("%d/%m/%y")
569 '11/03/02'
570 >>> d.strftime("%A %d. %B %Y")
571 'Monday 11. March 2002'
572
Georg Brandl116aa622007-08-15 14:28:22 +0000573
574.. _datetime-datetime:
575
576:class:`datetime` Objects
577-------------------------
578
579A :class:`datetime` object is a single object containing all the information
580from a :class:`date` object and a :class:`time` object. Like a :class:`date`
581object, :class:`datetime` assumes the current Gregorian calendar extended in
582both directions; like a time object, :class:`datetime` assumes there are exactly
5833600\*24 seconds in every day.
584
585Constructor:
586
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000587.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000588
589 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
Georg Brandl5c106642007-11-29 17:41:05 +0000590 instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
591 in the following ranges:
Georg Brandl116aa622007-08-15 14:28:22 +0000592
593 * ``MINYEAR <= year <= MAXYEAR``
594 * ``1 <= month <= 12``
595 * ``1 <= day <= number of days in the given month and year``
596 * ``0 <= hour < 24``
597 * ``0 <= minute < 60``
598 * ``0 <= second < 60``
599 * ``0 <= microsecond < 1000000``
600
601 If an argument outside those ranges is given, :exc:`ValueError` is raised.
602
603Other constructors, all class methods:
604
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000605.. classmethod:: datetime.today()
Georg Brandl116aa622007-08-15 14:28:22 +0000606
607 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
608 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
609 :meth:`fromtimestamp`.
610
611
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000612.. classmethod:: datetime.now(tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000613
614 Return the current local date and time. If optional argument *tz* is ``None``
615 or not specified, this is like :meth:`today`, but, if possible, supplies more
616 precision than can be gotten from going through a :func:`time.time` timestamp
617 (for example, this may be possible on platforms supplying the C
618 :cfunc:`gettimeofday` function).
619
620 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
621 current date and time are converted to *tz*'s time zone. In this case the
622 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
623 See also :meth:`today`, :meth:`utcnow`.
624
625
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000626.. classmethod:: datetime.utcnow()
Georg Brandl116aa622007-08-15 14:28:22 +0000627
628 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
629 :meth:`now`, but returns the current UTC date and time, as a naive
630 :class:`datetime` object. See also :meth:`now`.
631
632
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000633.. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000634
635 Return the local date and time corresponding to the POSIX timestamp, such as is
636 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
637 specified, the timestamp is converted to the platform's local date and time, and
638 the returned :class:`datetime` object is naive.
639
640 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
641 timestamp is converted to *tz*'s time zone. In this case the result is
642 equivalent to
643 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
644
645 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
646 the range of values supported by the platform C :cfunc:`localtime` or
647 :cfunc:`gmtime` functions. It's common for this to be restricted to years in
648 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
649 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
650 and then it's possible to have two timestamps differing by a second that yield
651 identical :class:`datetime` objects. See also :meth:`utcfromtimestamp`.
652
653
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000654.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl116aa622007-08-15 14:28:22 +0000655
656 Return the UTC :class:`datetime` corresponding to the POSIX timestamp, with
657 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
658 out of the range of values supported by the platform C :cfunc:`gmtime` function.
659 It's common for this to be restricted to years in 1970 through 2038. See also
660 :meth:`fromtimestamp`.
661
662
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000663.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl116aa622007-08-15 14:28:22 +0000664
665 Return the :class:`datetime` corresponding to the proleptic Gregorian ordinal,
666 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
667 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
668 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
669
670
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000671.. classmethod:: datetime.combine(date, time)
Georg Brandl116aa622007-08-15 14:28:22 +0000672
673 Return a new :class:`datetime` object whose date members are equal to the given
674 :class:`date` object's, and whose time and :attr:`tzinfo` members are equal to
675 the given :class:`time` object's. For any :class:`datetime` object *d*, ``d ==
676 datetime.combine(d.date(), d.timetz())``. If date is a :class:`datetime`
677 object, its time and :attr:`tzinfo` members are ignored.
678
679
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000680.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl116aa622007-08-15 14:28:22 +0000681
682 Return a :class:`datetime` corresponding to *date_string*, parsed according to
683 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
684 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
685 can't be parsed by :func:`time.strptime` or if it returns a value which isn't a
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000686 time tuple. See section :ref:`strftime-strptime-behavior`.
687
Georg Brandl116aa622007-08-15 14:28:22 +0000688
Georg Brandl116aa622007-08-15 14:28:22 +0000689
690Class attributes:
691
Georg Brandl116aa622007-08-15 14:28:22 +0000692.. attribute:: datetime.min
693
694 The earliest representable :class:`datetime`, ``datetime(MINYEAR, 1, 1,
695 tzinfo=None)``.
696
697
698.. attribute:: datetime.max
699
700 The latest representable :class:`datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
701 59, 999999, tzinfo=None)``.
702
703
704.. attribute:: datetime.resolution
705
706 The smallest possible difference between non-equal :class:`datetime` objects,
707 ``timedelta(microseconds=1)``.
708
Georg Brandl116aa622007-08-15 14:28:22 +0000709
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000710Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +0000711
712.. attribute:: datetime.year
713
714 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
715
716
717.. attribute:: datetime.month
718
719 Between 1 and 12 inclusive.
720
721
722.. attribute:: datetime.day
723
724 Between 1 and the number of days in the given month of the given year.
725
726
727.. attribute:: datetime.hour
728
729 In ``range(24)``.
730
731
732.. attribute:: datetime.minute
733
734 In ``range(60)``.
735
736
737.. attribute:: datetime.second
738
739 In ``range(60)``.
740
741
742.. attribute:: datetime.microsecond
743
744 In ``range(1000000)``.
745
746
747.. attribute:: datetime.tzinfo
748
749 The object passed as the *tzinfo* argument to the :class:`datetime` constructor,
750 or ``None`` if none was passed.
751
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000752
Georg Brandl116aa622007-08-15 14:28:22 +0000753Supported operations:
754
755+---------------------------------------+-------------------------------+
756| Operation | Result |
757+=======================================+===============================+
758| ``datetime2 = datetime1 + timedelta`` | \(1) |
759+---------------------------------------+-------------------------------+
760| ``datetime2 = datetime1 - timedelta`` | \(2) |
761+---------------------------------------+-------------------------------+
762| ``timedelta = datetime1 - datetime2`` | \(3) |
763+---------------------------------------+-------------------------------+
764| ``datetime1 < datetime2`` | Compares :class:`datetime` to |
765| | :class:`datetime`. (4) |
766+---------------------------------------+-------------------------------+
767
768(1)
769 datetime2 is a duration of timedelta removed from datetime1, moving forward in
770 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
771 result has the same :attr:`tzinfo` member as the input datetime, and datetime2 -
772 datetime1 == timedelta after. :exc:`OverflowError` is raised if datetime2.year
773 would be smaller than :const:`MINYEAR` or larger than :const:`MAXYEAR`. Note
774 that no time zone adjustments are done even if the input is an aware object.
775
776(2)
777 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
778 addition, the result has the same :attr:`tzinfo` member as the input datetime,
779 and no time zone adjustments are done even if the input is aware. This isn't
780 quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation
781 can overflow in cases where datetime1 - timedelta does not.
782
783(3)
784 Subtraction of a :class:`datetime` from a :class:`datetime` is defined only if
785 both operands are naive, or if both are aware. If one is aware and the other is
786 naive, :exc:`TypeError` is raised.
787
788 If both are naive, or both are aware and have the same :attr:`tzinfo` member,
789 the :attr:`tzinfo` members are ignored, and the result is a :class:`timedelta`
790 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
791 are done in this case.
792
793 If both are aware and have different :attr:`tzinfo` members, ``a-b`` acts as if
794 *a* and *b* were first converted to naive UTC datetimes first. The result is
795 ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) -
796 b.utcoffset())`` except that the implementation never overflows.
797
798(4)
799 *datetime1* is considered less than *datetime2* when *datetime1* precedes
800 *datetime2* in time.
801
802 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
803 If both comparands are aware, and have the same :attr:`tzinfo` member, the
804 common :attr:`tzinfo` member is ignored and the base datetimes are compared. If
805 both comparands are aware and have different :attr:`tzinfo` members, the
806 comparands are first adjusted by subtracting their UTC offsets (obtained from
807 ``self.utcoffset()``).
808
809 .. note::
810
811 In order to stop comparison from falling back to the default scheme of comparing
812 object addresses, datetime comparison normally raises :exc:`TypeError` if the
813 other comparand isn't also a :class:`datetime` object. However,
814 ``NotImplemented`` is returned instead if the other comparand has a
815 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
816 chance at implementing mixed-type comparison. If not, when a :class:`datetime`
817 object is compared to an object of a different type, :exc:`TypeError` is raised
818 unless the comparison is ``==`` or ``!=``. The latter cases return
819 :const:`False` or :const:`True`, respectively.
820
821:class:`datetime` objects can be used as dictionary keys. In Boolean contexts,
822all :class:`datetime` objects are considered to be true.
823
824Instance methods:
825
Georg Brandl116aa622007-08-15 14:28:22 +0000826.. method:: datetime.date()
827
828 Return :class:`date` object with same year, month and day.
829
830
831.. method:: datetime.time()
832
833 Return :class:`time` object with same hour, minute, second and microsecond.
834 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
835
836
837.. method:: datetime.timetz()
838
839 Return :class:`time` object with same hour, minute, second, microsecond, and
840 tzinfo members. See also method :meth:`time`.
841
842
843.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
844
845 Return a datetime with the same members, except for those members given new
846 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
847 can be specified to create a naive datetime from an aware datetime with no
848 conversion of date and time members.
849
850
851.. method:: datetime.astimezone(tz)
852
853 Return a :class:`datetime` object with new :attr:`tzinfo` member *tz*, adjusting
854 the date and time members so the result is the same UTC time as *self*, but in
855 *tz*'s local time.
856
857 *tz* must be an instance of a :class:`tzinfo` subclass, and its
858 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
859 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
860 not return ``None``).
861
862 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
863 adjustment of date or time members is performed. Else the result is local time
864 in time zone *tz*, representing the same UTC time as *self*: after ``astz =
865 dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have the same date
866 and time members as ``dt - dt.utcoffset()``. The discussion of class
867 :class:`tzinfo` explains the cases at Daylight Saving Time transition boundaries
868 where this cannot be achieved (an issue only if *tz* models both standard and
869 daylight time).
870
871 If you merely want to attach a time zone object *tz* to a datetime *dt* without
872 adjustment of date and time members, use ``dt.replace(tzinfo=tz)``. If you
873 merely want to remove the time zone object from an aware datetime *dt* without
874 conversion of date and time members, use ``dt.replace(tzinfo=None)``.
875
876 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
877 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
878 Ignoring error cases, :meth:`astimezone` acts like::
879
880 def astimezone(self, tz):
881 if self.tzinfo is tz:
882 return self
883 # Convert self to UTC, and attach the new time zone object.
884 utc = (self - self.utcoffset()).replace(tzinfo=tz)
885 # Convert from UTC to tz's local time.
886 return tz.fromutc(utc)
887
888
889.. method:: datetime.utcoffset()
890
891 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
892 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
893 return ``None``, or a :class:`timedelta` object representing a whole number of
894 minutes with magnitude less than one day.
895
896
897.. method:: datetime.dst()
898
899 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
900 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
901 ``None``, or a :class:`timedelta` object representing a whole number of minutes
902 with magnitude less than one day.
903
904
905.. method:: datetime.tzname()
906
907 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
908 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
909 ``None`` or a string object,
910
911
912.. method:: datetime.timetuple()
913
914 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
915 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
916 d.hour, d.minute, d.second, d.weekday(), d.toordinal() - date(d.year, 1,
917 1).toordinal() + 1, dst))`` The :attr:`tm_isdst` flag of the result is set
918 according to the :meth:`dst` method: :attr:`tzinfo` is ``None`` or :meth:`dst`
919 returns ``None``, :attr:`tm_isdst` is set to ``-1``; else if :meth:`dst`
920 returns a non-zero value, :attr:`tm_isdst` is set to ``1``; else ``tm_isdst`` is
921 set to ``0``.
922
923
924.. method:: datetime.utctimetuple()
925
926 If :class:`datetime` instance *d* is naive, this is the same as
927 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
928 ``d.dst()`` returns. DST is never in effect for a UTC time.
929
930 If *d* is aware, *d* is normalized to UTC time, by subtracting
931 ``d.utcoffset()``, and a :class:`time.struct_time` for the normalized time is
932 returned. :attr:`tm_isdst` is forced to 0. Note that the result's
933 :attr:`tm_year` member may be :const:`MINYEAR`\ -1 or :const:`MAXYEAR`\ +1, if
934 *d*.year was ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
935 boundary.
936
937
938.. method:: datetime.toordinal()
939
940 Return the proleptic Gregorian ordinal of the date. The same as
941 ``self.date().toordinal()``.
942
943
944.. method:: datetime.weekday()
945
946 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
947 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
948
949
950.. method:: datetime.isoweekday()
951
952 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
953 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
954 :meth:`isocalendar`.
955
956
957.. method:: datetime.isocalendar()
958
959 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
960 ``self.date().isocalendar()``.
961
962
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000963.. method:: datetime.isoformat(sep='T')
Georg Brandl116aa622007-08-15 14:28:22 +0000964
965 Return a string representing the date and time in ISO 8601 format,
966 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
967 YYYY-MM-DDTHH:MM:SS
968
969 If :meth:`utcoffset` does not return ``None``, a 6-character string is
970 appended, giving the UTC offset in (signed) hours and minutes:
971 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
972 YYYY-MM-DDTHH:MM:SS+HH:MM
973
974 The optional argument *sep* (default ``'T'``) is a one-character separator,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000975 placed between the date and time portions of the result. For example,
Georg Brandl116aa622007-08-15 14:28:22 +0000976
977 >>> from datetime import tzinfo, timedelta, datetime
978 >>> class TZ(tzinfo):
979 ... def utcoffset(self, dt): return timedelta(minutes=-399)
980 ...
981 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
982 '2002-12-25 00:00:00-06:39'
983
984
985.. method:: datetime.__str__()
986
987 For a :class:`datetime` instance *d*, ``str(d)`` is equivalent to
988 ``d.isoformat(' ')``.
989
990
991.. method:: datetime.ctime()
992
993 Return a string representing the date and time, for example ``datetime(2002, 12,
994 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
995 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
996 native C :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
997 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
998
999
1000.. method:: datetime.strftime(format)
1001
1002 Return a string representing the date and time, controlled by an explicit format
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001003 string. See section :ref:`strftime-strptime-behavior`.
1004
Georg Brandl116aa622007-08-15 14:28:22 +00001005
Christian Heimesfe337bf2008-03-23 21:54:12 +00001006Examples of working with datetime objects:
1007
1008.. doctest::
1009
Christian Heimes895627f2007-12-08 17:28:33 +00001010 >>> from datetime import datetime, date, time
1011 >>> # Using datetime.combine()
1012 >>> d = date(2005, 7, 14)
1013 >>> t = time(12, 30)
1014 >>> datetime.combine(d, t)
1015 datetime.datetime(2005, 7, 14, 12, 30)
1016 >>> # Using datetime.now() or datetime.utcnow()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001017 >>> datetime.now() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001018 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Christian Heimesfe337bf2008-03-23 21:54:12 +00001019 >>> datetime.utcnow() # doctest: +SKIP
Christian Heimes895627f2007-12-08 17:28:33 +00001020 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1021 >>> # Using datetime.strptime()
1022 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1023 >>> dt
1024 datetime.datetime(2006, 11, 21, 16, 30)
1025 >>> # Using datetime.timetuple() to get tuple of all attributes
1026 >>> tt = dt.timetuple()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001027 >>> for it in tt: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001028 ... print(it)
Georg Brandl48310cd2009-01-03 21:18:54 +00001029 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001030 2006 # year
1031 11 # month
1032 21 # day
1033 16 # hour
1034 30 # minute
1035 0 # second
1036 1 # weekday (0 = Monday)
1037 325 # number of days since 1st January
1038 -1 # dst - method tzinfo.dst() returned None
1039 >>> # Date in ISO format
1040 >>> ic = dt.isocalendar()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001041 >>> for it in ic: # doctest: +SKIP
Neal Norwitz752abd02008-05-13 04:55:24 +00001042 ... print(it)
Christian Heimes895627f2007-12-08 17:28:33 +00001043 ...
1044 2006 # ISO year
1045 47 # ISO week
1046 2 # ISO weekday
1047 >>> # Formatting datetime
1048 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1049 'Tuesday, 21. November 2006 04:30PM'
1050
Christian Heimesfe337bf2008-03-23 21:54:12 +00001051Using datetime with tzinfo:
Christian Heimes895627f2007-12-08 17:28:33 +00001052
1053 >>> from datetime import timedelta, datetime, tzinfo
1054 >>> class GMT1(tzinfo):
1055 ... def __init__(self): # DST starts last Sunday in March
1056 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1057 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001058 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001059 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1060 ... def utcoffset(self, dt):
1061 ... return timedelta(hours=1) + self.dst(dt)
Georg Brandl48310cd2009-01-03 21:18:54 +00001062 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001063 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1064 ... return timedelta(hours=1)
1065 ... else:
1066 ... return timedelta(0)
1067 ... def tzname(self,dt):
1068 ... return "GMT +1"
Georg Brandl48310cd2009-01-03 21:18:54 +00001069 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001070 >>> class GMT2(tzinfo):
1071 ... def __init__(self):
Georg Brandl48310cd2009-01-03 21:18:54 +00001072 ... d = datetime(dt.year, 4, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001073 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandl48310cd2009-01-03 21:18:54 +00001074 ... d = datetime(dt.year, 11, 1)
Christian Heimes895627f2007-12-08 17:28:33 +00001075 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1076 ... def utcoffset(self, dt):
1077 ... return timedelta(hours=1) + self.dst(dt)
1078 ... def dst(self, dt):
1079 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1080 ... return timedelta(hours=2)
1081 ... else:
1082 ... return timedelta(0)
1083 ... def tzname(self,dt):
1084 ... return "GMT +2"
Georg Brandl48310cd2009-01-03 21:18:54 +00001085 ...
Christian Heimes895627f2007-12-08 17:28:33 +00001086 >>> gmt1 = GMT1()
1087 >>> # Daylight Saving Time
1088 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1089 >>> dt1.dst()
1090 datetime.timedelta(0)
1091 >>> dt1.utcoffset()
1092 datetime.timedelta(0, 3600)
1093 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1094 >>> dt2.dst()
1095 datetime.timedelta(0, 3600)
1096 >>> dt2.utcoffset()
1097 datetime.timedelta(0, 7200)
1098 >>> # Convert datetime to another time zone
1099 >>> dt3 = dt2.astimezone(GMT2())
1100 >>> dt3 # doctest: +ELLIPSIS
1101 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1102 >>> dt2 # doctest: +ELLIPSIS
1103 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1104 >>> dt2.utctimetuple() == dt3.utctimetuple()
1105 True
Georg Brandl48310cd2009-01-03 21:18:54 +00001106
Christian Heimes895627f2007-12-08 17:28:33 +00001107
Georg Brandl116aa622007-08-15 14:28:22 +00001108
1109.. _datetime-time:
1110
1111:class:`time` Objects
1112---------------------
1113
1114A time object represents a (local) time of day, independent of any particular
1115day, and subject to adjustment via a :class:`tzinfo` object.
1116
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001117.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001118
1119 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
Georg Brandl5c106642007-11-29 17:41:05 +00001120 :class:`tzinfo` subclass. The remaining arguments may be integers, in the
Georg Brandl116aa622007-08-15 14:28:22 +00001121 following ranges:
1122
1123 * ``0 <= hour < 24``
1124 * ``0 <= minute < 60``
1125 * ``0 <= second < 60``
1126 * ``0 <= microsecond < 1000000``.
1127
1128 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1129 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1130
1131Class attributes:
1132
1133
1134.. attribute:: time.min
1135
1136 The earliest representable :class:`time`, ``time(0, 0, 0, 0)``.
1137
1138
1139.. attribute:: time.max
1140
1141 The latest representable :class:`time`, ``time(23, 59, 59, 999999)``.
1142
1143
1144.. attribute:: time.resolution
1145
1146 The smallest possible difference between non-equal :class:`time` objects,
1147 ``timedelta(microseconds=1)``, although note that arithmetic on :class:`time`
1148 objects is not supported.
1149
Georg Brandl116aa622007-08-15 14:28:22 +00001150
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001151Instance attributes (read-only):
Georg Brandl116aa622007-08-15 14:28:22 +00001152
1153.. attribute:: time.hour
1154
1155 In ``range(24)``.
1156
1157
1158.. attribute:: time.minute
1159
1160 In ``range(60)``.
1161
1162
1163.. attribute:: time.second
1164
1165 In ``range(60)``.
1166
1167
1168.. attribute:: time.microsecond
1169
1170 In ``range(1000000)``.
1171
1172
1173.. attribute:: time.tzinfo
1174
1175 The object passed as the tzinfo argument to the :class:`time` constructor, or
1176 ``None`` if none was passed.
1177
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001178
Georg Brandl116aa622007-08-15 14:28:22 +00001179Supported operations:
1180
1181* comparison of :class:`time` to :class:`time`, where *a* is considered less
1182 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1183 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
1184 the same :attr:`tzinfo` member, the common :attr:`tzinfo` member is ignored and
1185 the base times are compared. If both comparands are aware and have different
1186 :attr:`tzinfo` members, the comparands are first adjusted by subtracting their
1187 UTC offsets (obtained from ``self.utcoffset()``). In order to stop mixed-type
1188 comparisons from falling back to the default comparison by object address, when
1189 a :class:`time` object is compared to an object of a different type,
1190 :exc:`TypeError` is raised unless the comparison is ``==`` or ``!=``. The
1191 latter cases return :const:`False` or :const:`True`, respectively.
1192
1193* hash, use as dict key
1194
1195* efficient pickling
1196
1197* in Boolean contexts, a :class:`time` object is considered to be true if and
1198 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1199 ``0`` if that's ``None``), the result is non-zero.
1200
Georg Brandl116aa622007-08-15 14:28:22 +00001201
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001202Instance methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001203
1204.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1205
1206 Return a :class:`time` with the same value, except for those members given new
1207 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
1208 can be specified to create a naive :class:`time` from an aware :class:`time`,
1209 without conversion of the time members.
1210
1211
1212.. method:: time.isoformat()
1213
1214 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1215 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1216 6-character string is appended, giving the UTC offset in (signed) hours and
1217 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1218
1219
1220.. method:: time.__str__()
1221
1222 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1223
1224
1225.. method:: time.strftime(format)
1226
1227 Return a string representing the time, controlled by an explicit format string.
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001228 See section :ref:`strftime-strptime-behavior`.
Georg Brandl116aa622007-08-15 14:28:22 +00001229
1230
1231.. method:: time.utcoffset()
1232
1233 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1234 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1235 return ``None`` or a :class:`timedelta` object representing a whole number of
1236 minutes with magnitude less than one day.
1237
1238
1239.. method:: time.dst()
1240
1241 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1242 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1243 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1244 with magnitude less than one day.
1245
1246
1247.. method:: time.tzname()
1248
1249 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1250 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1251 return ``None`` or a string object.
1252
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001253
Christian Heimesfe337bf2008-03-23 21:54:12 +00001254Example:
Georg Brandl48310cd2009-01-03 21:18:54 +00001255
Christian Heimes895627f2007-12-08 17:28:33 +00001256 >>> from datetime import time, tzinfo
1257 >>> class GMT1(tzinfo):
1258 ... def utcoffset(self, dt):
Georg Brandl48310cd2009-01-03 21:18:54 +00001259 ... return timedelta(hours=1)
1260 ... def dst(self, dt):
Christian Heimes895627f2007-12-08 17:28:33 +00001261 ... return timedelta(0)
1262 ... def tzname(self,dt):
1263 ... return "Europe/Prague"
1264 ...
1265 >>> t = time(12, 10, 30, tzinfo=GMT1())
1266 >>> t # doctest: +ELLIPSIS
1267 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1268 >>> gmt = GMT1()
1269 >>> t.isoformat()
1270 '12:10:30+01:00'
1271 >>> t.dst()
1272 datetime.timedelta(0)
1273 >>> t.tzname()
1274 'Europe/Prague'
1275 >>> t.strftime("%H:%M:%S %Z")
1276 '12:10:30 Europe/Prague'
1277
Georg Brandl116aa622007-08-15 14:28:22 +00001278
1279.. _datetime-tzinfo:
1280
1281:class:`tzinfo` Objects
1282-----------------------
1283
Brett Cannone1327f72009-01-29 04:10:21 +00001284:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl116aa622007-08-15 14:28:22 +00001285instantiated directly. You need to derive a concrete subclass, and (at least)
1286supply implementations of the standard :class:`tzinfo` methods needed by the
1287:class:`datetime` methods you use. The :mod:`datetime` module does not supply
1288any concrete subclasses of :class:`tzinfo`.
1289
1290An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1291constructors for :class:`datetime` and :class:`time` objects. The latter objects
1292view their members as being in local time, and the :class:`tzinfo` object
1293supports methods revealing offset of local time from UTC, the name of the time
1294zone, and DST offset, all relative to a date or time object passed to them.
1295
1296Special requirement for pickling: A :class:`tzinfo` subclass must have an
1297:meth:`__init__` method that can be called with no arguments, else it can be
1298pickled but possibly not unpickled again. This is a technical requirement that
1299may be relaxed in the future.
1300
1301A concrete subclass of :class:`tzinfo` may need to implement the following
1302methods. Exactly which methods are needed depends on the uses made of aware
1303:mod:`datetime` objects. If in doubt, simply implement all of them.
1304
1305
1306.. method:: tzinfo.utcoffset(self, dt)
1307
1308 Return offset of local time from UTC, in minutes east of UTC. If local time is
1309 west of UTC, this should be negative. Note that this is intended to be the
1310 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1311 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1312 the UTC offset isn't known, return ``None``. Else the value returned must be a
1313 :class:`timedelta` object specifying a whole number of minutes in the range
1314 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1315 than one day). Most implementations of :meth:`utcoffset` will probably look
1316 like one of these two::
1317
1318 return CONSTANT # fixed-offset class
1319 return CONSTANT + self.dst(dt) # daylight-aware class
1320
1321 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1322 ``None`` either.
1323
1324 The default implementation of :meth:`utcoffset` raises
1325 :exc:`NotImplementedError`.
1326
1327
1328.. method:: tzinfo.dst(self, dt)
1329
1330 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1331 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1332 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1333 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1334 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1335 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1336 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
1337 member's :meth:`dst` method to determine how the :attr:`tm_isdst` flag should be
1338 set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for DST changes
1339 when crossing time zones.
1340
1341 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1342 daylight times must be consistent in this sense:
1343
1344 ``tz.utcoffset(dt) - tz.dst(dt)``
1345
1346 must return the same result for every :class:`datetime` *dt* with ``dt.tzinfo ==
1347 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1348 zone's "standard offset", which should not depend on the date or the time, but
1349 only on geographic location. The implementation of :meth:`datetime.astimezone`
1350 relies on this, but cannot detect violations; it's the programmer's
1351 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1352 this, it may be able to override the default implementation of
1353 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1354
1355 Most implementations of :meth:`dst` will probably look like one of these two::
1356
1357 def dst(self):
1358 # a fixed-offset class: doesn't account for DST
1359 return timedelta(0)
1360
1361 or ::
1362
1363 def dst(self):
1364 # Code to set dston and dstoff to the time zone's DST
1365 # transition times based on the input dt.year, and expressed
1366 # in standard local time. Then
1367
1368 if dston <= dt.replace(tzinfo=None) < dstoff:
1369 return timedelta(hours=1)
1370 else:
1371 return timedelta(0)
1372
1373 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1374
1375
1376.. method:: tzinfo.tzname(self, dt)
1377
1378 Return the time zone name corresponding to the :class:`datetime` object *dt*, as
1379 a string. Nothing about string names is defined by the :mod:`datetime` module,
1380 and there's no requirement that it mean anything in particular. For example,
1381 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1382 valid replies. Return ``None`` if a string name isn't known. Note that this is
1383 a method rather than a fixed string primarily because some :class:`tzinfo`
1384 subclasses will wish to return different names depending on the specific value
1385 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1386 daylight time.
1387
1388 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1389
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001390
Georg Brandl116aa622007-08-15 14:28:22 +00001391These methods are called by a :class:`datetime` or :class:`time` object, in
1392response to their methods of the same names. A :class:`datetime` object passes
1393itself as the argument, and a :class:`time` object passes ``None`` as the
1394argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
1395accept a *dt* argument of ``None``, or of class :class:`datetime`.
1396
1397When ``None`` is passed, it's up to the class designer to decide the best
1398response. For example, returning ``None`` is appropriate if the class wishes to
1399say that time objects don't participate in the :class:`tzinfo` protocols. It
1400may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1401there is no other convention for discovering the standard offset.
1402
1403When a :class:`datetime` object is passed in response to a :class:`datetime`
1404method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1405rely on this, unless user code calls :class:`tzinfo` methods directly. The
1406intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1407time, and not need worry about objects in other timezones.
1408
1409There is one more :class:`tzinfo` method that a subclass may wish to override:
1410
1411
1412.. method:: tzinfo.fromutc(self, dt)
1413
1414 This is called from the default :class:`datetime.astimezone()` implementation.
1415 When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members
1416 are to be viewed as expressing a UTC time. The purpose of :meth:`fromutc` is to
1417 adjust the date and time members, returning an equivalent datetime in *self*'s
1418 local time.
1419
1420 Most :class:`tzinfo` subclasses should be able to inherit the default
1421 :meth:`fromutc` implementation without problems. It's strong enough to handle
1422 fixed-offset time zones, and time zones accounting for both standard and
1423 daylight time, and the latter even if the DST transition times differ in
1424 different years. An example of a time zone the default :meth:`fromutc`
1425 implementation may not handle correctly in all cases is one where the standard
1426 offset (from UTC) depends on the specific date and time passed, which can happen
1427 for political reasons. The default implementations of :meth:`astimezone` and
1428 :meth:`fromutc` may not produce the result you want if the result is one of the
1429 hours straddling the moment the standard offset changes.
1430
1431 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1432 like::
1433
1434 def fromutc(self, dt):
1435 # raise ValueError error if dt.tzinfo is not self
1436 dtoff = dt.utcoffset()
1437 dtdst = dt.dst()
1438 # raise ValueError if dtoff is None or dtdst is None
1439 delta = dtoff - dtdst # this is self's standard offset
1440 if delta:
1441 dt += delta # convert to standard local time
1442 dtdst = dt.dst()
1443 # raise ValueError if dtdst is None
1444 if dtdst:
1445 return dt + dtdst
1446 else:
1447 return dt
1448
1449Example :class:`tzinfo` classes:
1450
1451.. literalinclude:: ../includes/tzinfo-examples.py
1452
1453
1454Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1455subclass accounting for both standard and daylight time, at the DST transition
1456points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
1457minute after 1:59 (EST) on the first Sunday in April, and ends the minute after
14581:59 (EDT) on the last Sunday in October::
1459
1460 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1461 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1462 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1463
1464 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1465
1466 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1467
1468When DST starts (the "start" line), the local wall clock leaps from 1:59 to
14693:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1470``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1471begins. In order for :meth:`astimezone` to make this guarantee, the
1472:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1473Eastern) to be in daylight time.
1474
1475When DST ends (the "end" line), there's a potentially worse problem: there's an
1476hour that can't be spelled unambiguously in local wall time: the last hour of
1477daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1478daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1479to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1480:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1481hours into the same local hour then. In the Eastern example, UTC times of the
1482form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1483:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1484consider times in the "repeated hour" to be in standard time. This is easily
1485arranged, as in the example, by expressing DST switch times in the time zone's
1486standard local time.
1487
1488Applications that can't bear such ambiguities should avoid using hybrid
1489:class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any
1490other fixed-offset :class:`tzinfo` subclass (such as a class representing only
1491EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
Georg Brandl48310cd2009-01-03 21:18:54 +00001492
Georg Brandl116aa622007-08-15 14:28:22 +00001493
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001494.. _strftime-strptime-behavior:
Georg Brandl116aa622007-08-15 14:28:22 +00001495
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001496:meth:`strftime` and :meth:`strptime` Behavior
1497----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001498
1499:class:`date`, :class:`datetime`, and :class:`time` objects all support a
1500``strftime(format)`` method, to create a string representing the time under the
1501control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1502acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1503although not all objects support a :meth:`timetuple` method.
1504
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001505Conversely, the :meth:`datetime.strptime` class method creates a
1506:class:`datetime` object from a string representing a date and time and a
1507corresponding format string. ``datetime.strptime(date_string, format)`` is
1508equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1509
Georg Brandl116aa622007-08-15 14:28:22 +00001510For :class:`time` objects, the format codes for year, month, and day should not
1511be used, as time objects have no such values. If they're used anyway, ``1900``
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001512is substituted for the year, and ``1`` for the month and day.
Georg Brandl116aa622007-08-15 14:28:22 +00001513
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001514For :class:`date` objects, the format codes for hours, minutes, seconds, and
1515microseconds should not be used, as :class:`date` objects have no such
1516values. If they're used anyway, ``0`` is substituted for them.
1517
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001518For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1519strings.
1520
1521For an aware object:
1522
1523``%z``
1524 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1525 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and
1526 MM is a 2-digit string giving the number of UTC offset minutes. For example, if
1527 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is
1528 replaced with the string ``'-0330'``.
1529
1530``%Z``
1531 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1532 Otherwise ``%Z`` is replaced by the returned value, which must be a string.
Georg Brandl116aa622007-08-15 14:28:22 +00001533
Georg Brandl116aa622007-08-15 14:28:22 +00001534The full set of format codes supported varies across platforms, because Python
1535calls the platform C library's :func:`strftime` function, and platform
Georg Brandl48310cd2009-01-03 21:18:54 +00001536variations are common.
Christian Heimes895627f2007-12-08 17:28:33 +00001537
1538The following is a list of all the format codes that the C standard (1989
1539version) requires, and these work on all platforms with a standard C
1540implementation. Note that the 1999 version of the C standard added additional
1541format codes.
Georg Brandl116aa622007-08-15 14:28:22 +00001542
1543The exact range of years for which :meth:`strftime` works also varies across
1544platforms. Regardless of platform, years before 1900 cannot be used.
1545
Christian Heimes895627f2007-12-08 17:28:33 +00001546+-----------+--------------------------------+-------+
1547| Directive | Meaning | Notes |
1548+===========+================================+=======+
1549| ``%a`` | Locale's abbreviated weekday | |
1550| | name. | |
1551+-----------+--------------------------------+-------+
1552| ``%A`` | Locale's full weekday name. | |
1553+-----------+--------------------------------+-------+
1554| ``%b`` | Locale's abbreviated month | |
1555| | name. | |
1556+-----------+--------------------------------+-------+
1557| ``%B`` | Locale's full month name. | |
1558+-----------+--------------------------------+-------+
1559| ``%c`` | Locale's appropriate date and | |
1560| | time representation. | |
1561+-----------+--------------------------------+-------+
1562| ``%d`` | Day of the month as a decimal | |
1563| | number [01,31]. | |
1564+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001565| ``%f`` | Microsecond as a decimal | \(1) |
1566| | number [0,999999], zero-padded | |
1567| | on the left | |
1568+-----------+--------------------------------+-------+
Christian Heimes895627f2007-12-08 17:28:33 +00001569| ``%H`` | Hour (24-hour clock) as a | |
1570| | decimal number [00,23]. | |
1571+-----------+--------------------------------+-------+
1572| ``%I`` | Hour (12-hour clock) as a | |
1573| | decimal number [01,12]. | |
1574+-----------+--------------------------------+-------+
1575| ``%j`` | Day of the year as a decimal | |
1576| | number [001,366]. | |
1577+-----------+--------------------------------+-------+
1578| ``%m`` | Month as a decimal number | |
1579| | [01,12]. | |
1580+-----------+--------------------------------+-------+
1581| ``%M`` | Minute as a decimal number | |
1582| | [00,59]. | |
1583+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001584| ``%p`` | Locale's equivalent of either | \(2) |
Christian Heimes895627f2007-12-08 17:28:33 +00001585| | AM or PM. | |
1586+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001587| ``%S`` | Second as a decimal number | \(3) |
Christian Heimes895627f2007-12-08 17:28:33 +00001588| | [00,61]. | |
1589+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001590| ``%U`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001591| | (Sunday as the first day of | |
1592| | the week) as a decimal number | |
1593| | [00,53]. All days in a new | |
1594| | year preceding the first | |
1595| | Sunday are considered to be in | |
1596| | week 0. | |
1597+-----------+--------------------------------+-------+
1598| ``%w`` | Weekday as a decimal number | |
1599| | [0(Sunday),6]. | |
1600+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001601| ``%W`` | Week number of the year | \(4) |
Christian Heimes895627f2007-12-08 17:28:33 +00001602| | (Monday as the first day of | |
1603| | the week) as a decimal number | |
1604| | [00,53]. All days in a new | |
1605| | year preceding the first | |
1606| | Monday are considered to be in | |
1607| | week 0. | |
1608+-----------+--------------------------------+-------+
1609| ``%x`` | Locale's appropriate date | |
1610| | representation. | |
1611+-----------+--------------------------------+-------+
1612| ``%X`` | Locale's appropriate time | |
1613| | representation. | |
1614+-----------+--------------------------------+-------+
1615| ``%y`` | Year without century as a | |
1616| | decimal number [00,99]. | |
1617+-----------+--------------------------------+-------+
1618| ``%Y`` | Year with century as a decimal | |
1619| | number. | |
1620+-----------+--------------------------------+-------+
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001621| ``%z`` | UTC offset in the form +HHMM | \(5) |
Christian Heimes895627f2007-12-08 17:28:33 +00001622| | or -HHMM (empty string if the | |
1623| | the object is naive). | |
1624+-----------+--------------------------------+-------+
1625| ``%Z`` | Time zone name (empty string | |
1626| | if the object is naive). | |
1627+-----------+--------------------------------+-------+
1628| ``%%`` | A literal ``'%'`` character. | |
1629+-----------+--------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001630
Christian Heimes895627f2007-12-08 17:28:33 +00001631Notes:
1632
1633(1)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001634 When used with the :meth:`strptime` method, the ``%f`` directive
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001635 accepts from one to six digits and zero pads on the right. ``%f`` is
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001636 an extension to the set of format characters in the C standard (but
1637 implemented separately in datetime objects, and therefore always
1638 available).
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001639
1640(2)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001641 When used with the :meth:`strptime` method, the ``%p`` directive only affects
Christian Heimes895627f2007-12-08 17:28:33 +00001642 the output hour field if the ``%I`` directive is used to parse the hour.
1643
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001644(3)
R. David Murraybd25d332009-04-02 04:50:03 +00001645 The range really is ``0`` to ``61``; according to the Posix standard this
1646 accounts for leap seconds and the (very rare) double leap seconds.
1647 The :mod:`time` module may produce and does accept leap seconds since
1648 it is based on the Posix standard, but the :mod:`datetime` module
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001649 does not accept leap seconds in :meth:`strptime` input nor will it
R. David Murraybd25d332009-04-02 04:50:03 +00001650 produce them in :func:`strftime` output.
Christian Heimes895627f2007-12-08 17:28:33 +00001651
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001652(4)
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001653 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in
Christian Heimes895627f2007-12-08 17:28:33 +00001654 calculations when the day of the week and the year are specified.
1655
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001656(5)
Christian Heimes895627f2007-12-08 17:28:33 +00001657 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1658 ``%z`` is replaced with the string ``'-0330'``.