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