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