1 :mod:`datetime` --- Basic date and time types
2 =============================================
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>
10 .. XXX what order should the types be discussed in?
14 The :mod:`datetime` module supplies classes for manipulating dates and times in
15 both simple and complex ways. While date and time arithmetic is supported, the
16 focus of the implementation is on efficient member extraction for output
17 formatting and manipulation. For related
18 functionality, see also the :mod:`time` and :mod:`calendar` modules.
20 There are two kinds of date and time objects: "naive" and "aware". This
21 distinction refers to whether the object has any notion of time zone, daylight
22 saving time, or other kind of algorithmic or political time adjustment. Whether
23 a naive :class:`datetime` object represents Coordinated Universal Time (UTC),
24 local time, or time in some other timezone is purely up to the program, just
25 like it's up to the program whether a particular number represents metres,
26 miles, or mass. Naive :class:`datetime` objects are easy to understand and to
27 work with, at the cost of ignoring some aspects of reality.
29 For applications requiring more, :class:`datetime` and :class:`time` objects
30 have an optional time zone information member, :attr:`tzinfo`, that can contain
31 an instance of a subclass of the abstract :class:`tzinfo` class. These
32 :class:`tzinfo` objects capture information about the offset from UTC time, the
33 time zone name, and whether Daylight Saving Time is in effect. Note that no
34 concrete :class:`tzinfo` classes are supplied by the :mod:`datetime` module.
35 Supporting timezones at whatever level of detail is required is up to the
36 application. The rules for time adjustment across the world are more political
37 than rational, and there is no standard suitable for every application.
39 The :mod:`datetime` module exports the following constants:
44 The smallest year number allowed in a :class:`date` or :class:`datetime` object.
45 :const:`MINYEAR` is ``1``.
50 The largest year number allowed in a :class:`date` or :class:`datetime` object.
51 :const:`MAXYEAR` is ``9999``.
56 Module :mod:`calendar`
57 General calendar related functions.
60 Time access and conversions.
69 An idealized naive date, assuming the current Gregorian calendar always was, and
70 always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and
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`,
84 A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`,
85 :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
91 A duration expressing the difference between two :class:`date`, :class:`time`,
92 or :class:`datetime` instances to microsecond resolution.
97 An abstract base class for time zone information objects. These are used by the
98 :class:`datetime` and :class:`time` classes to provide a customizable notion of
99 time adjustment (for example, to account for time zone and/or daylight saving
102 Objects of these types are immutable.
104 Objects of the :class:`date` type are always naive.
106 An object *d* of type :class:`time` or :class:`datetime` may be naive or aware.
107 *d* is aware if ``d.tzinfo`` is not ``None`` and ``d.tzinfo.utcoffset(d)`` does
108 not return ``None``. If ``d.tzinfo`` is ``None``, or if ``d.tzinfo`` is not
109 ``None`` but ``d.tzinfo.utcoffset(d)`` returns ``None``, *d* is naive.
111 The distinction between naive and aware doesn't apply to :class:`timedelta`
114 Subclass relationships::
124 .. _datetime-timedelta:
126 :class:`timedelta` Objects
127 --------------------------
129 A :class:`timedelta` object represents a duration, the difference between two
133 .. class:: timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
135 All arguments are optional and default to ``0``. Arguments may be ints, longs,
136 or floats, and may be positive or negative.
138 Only *days*, *seconds* and *microseconds* are stored internally. Arguments are
139 converted to those units:
141 * A millisecond is converted to 1000 microseconds.
142 * A minute is converted to 60 seconds.
143 * An hour is converted to 3600 seconds.
144 * A week is converted to 7 days.
146 and days, seconds and microseconds are then normalized so that the
147 representation is unique, with
149 * ``0 <= microseconds < 1000000``
150 * ``0 <= seconds < 3600*24`` (the number of seconds in one day)
151 * ``-999999999 <= days <= 999999999``
153 If any argument is a float and there are fractional microseconds, the fractional
154 microseconds left over from all arguments are combined and their sum is rounded
155 to the nearest microsecond. If no argument is a float, the conversion and
156 normalization processes are exact (no information is lost).
158 If the normalized value of days lies outside the indicated range,
159 :exc:`OverflowError` is raised.
161 Note that normalization of negative values may be surprising at first. For
164 >>> from datetime import timedelta
165 >>> d = timedelta(microseconds=-1)
166 >>> (d.days, d.seconds, d.microseconds)
169 Class attributes are:
172 .. attribute:: timedelta.min
174 The most negative :class:`timedelta` object, ``timedelta(-999999999)``.
177 .. attribute:: timedelta.max
179 The most positive :class:`timedelta` object, ``timedelta(days=999999999,
180 hours=23, minutes=59, seconds=59, microseconds=999999)``.
183 .. attribute:: timedelta.resolution
185 The smallest possible difference between non-equal :class:`timedelta` objects,
186 ``timedelta(microseconds=1)``.
188 Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``.
189 ``-timedelta.max`` is not representable as a :class:`timedelta` object.
191 Instance attributes (read-only):
193 +------------------+--------------------------------------------+
194 | Attribute | Value |
195 +==================+============================================+
196 | ``days`` | Between -999999999 and 999999999 inclusive |
197 +------------------+--------------------------------------------+
198 | ``seconds`` | Between 0 and 86399 inclusive |
199 +------------------+--------------------------------------------+
200 | ``microseconds`` | Between 0 and 999999 inclusive |
201 +------------------+--------------------------------------------+
203 Supported operations:
205 .. XXX this table is too wide!
207 +--------------------------------+-----------------------------------------------+
208 | Operation | Result |
209 +================================+===============================================+
210 | ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == |
211 | | *t3* and *t1*-*t3* == *t2* are true. (1) |
212 +--------------------------------+-----------------------------------------------+
213 | ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* |
214 | | == *t2* - *t3* and *t2* == *t1* + *t3* are |
216 +--------------------------------+-----------------------------------------------+
217 | ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer or long. |
218 | | Afterwards *t1* // i == *t2* is true, |
219 | | provided ``i != 0``. |
220 +--------------------------------+-----------------------------------------------+
221 | | In general, *t1* \* i == *t1* \* (i-1) + *t1* |
223 +--------------------------------+-----------------------------------------------+
224 | ``t1 = t2 // i`` | The floor is computed and the remainder (if |
225 | | any) is thrown away. (3) |
226 +--------------------------------+-----------------------------------------------+
227 | ``+t1`` | Returns a :class:`timedelta` object with the |
228 | | same value. (2) |
229 +--------------------------------+-----------------------------------------------+
230 | ``-t1`` | equivalent to :class:`timedelta`\ |
231 | | (-*t1.days*, -*t1.seconds*, |
232 | | -*t1.microseconds*), and to *t1*\* -1. (1)(4) |
233 +--------------------------------+-----------------------------------------------+
234 | ``abs(t)`` | equivalent to +*t* when ``t.days >= 0``, and |
235 | | to -*t* when ``t.days < 0``. (2) |
236 +--------------------------------+-----------------------------------------------+
241 This is exact, but may overflow.
244 This is exact, and cannot overflow.
247 Division by 0 raises :exc:`ZeroDivisionError`.
250 -*timedelta.max* is not representable as a :class:`timedelta` object.
252 In addition to the operations listed above :class:`timedelta` objects support
253 certain additions and subtractions with :class:`date` and :class:`datetime`
256 Comparisons of :class:`timedelta` objects are supported with the
257 :class:`timedelta` object representing the smaller duration considered to be the
258 smaller timedelta. In order to stop mixed-type comparisons from falling back to
259 the default comparison by object address, when a :class:`timedelta` object is
260 compared to an object of a different type, :exc:`TypeError` is raised unless the
261 comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
262 :const:`True`, respectively.
264 :class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
265 efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
266 considered to be true if and only if it isn't equal to ``timedelta(0)``.
270 >>> from datetime import timedelta
271 >>> year = timedelta(days=365)
272 >>> another_year = timedelta(weeks=40, days=84, hours=23,
273 ... minutes=50, seconds=600) # adds up to 365 days
274 >>> year == another_year
276 >>> ten_years = 10 * year
277 >>> ten_years, ten_years.days // 365
278 (datetime.timedelta(3650), 10)
279 >>> nine_years = ten_years - year
280 >>> nine_years, nine_years.days // 365
281 (datetime.timedelta(3285), 9)
282 >>> three_years = nine_years // 3;
283 >>> three_years, three_years.days // 365
284 (datetime.timedelta(1095), 3)
285 >>> abs(three_years - ten_years) == 2 * three_years + year
291 :class:`date` Objects
292 ---------------------
294 A :class:`date` object represents a date (year, month and day) in an idealized
295 calendar, the current Gregorian calendar indefinitely extended in both
296 directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
297 called day number 2, and so on. This matches the definition of the "proleptic
298 Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
299 where it's the base calendar for all computations. See the book for algorithms
300 for converting between proleptic Gregorian ordinals and many other calendar
304 .. class:: date(year, month, day)
306 All arguments are required. Arguments may be ints or longs, in the following
309 * ``MINYEAR <= year <= MAXYEAR``
310 * ``1 <= month <= 12``
311 * ``1 <= day <= number of days in the given month and year``
313 If an argument outside those ranges is given, :exc:`ValueError` is raised.
315 Other constructors, all class methods:
318 .. method:: date.today()
320 Return the current local date. This is equivalent to
321 ``date.fromtimestamp(time.time())``.
324 .. method:: date.fromtimestamp(timestamp)
326 Return the local date corresponding to the POSIX timestamp, such as is returned
327 by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out
328 of the range of values supported by the platform C :cfunc:`localtime` function.
329 It's common for this to be restricted to years from 1970 through 2038. Note
330 that on non-POSIX systems that include leap seconds in their notion of a
331 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
334 .. method:: date.fromordinal(ordinal)
336 Return the date corresponding to the proleptic Gregorian ordinal, where January
337 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
338 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
344 .. attribute:: date.min
346 The earliest representable date, ``date(MINYEAR, 1, 1)``.
349 .. attribute:: date.max
351 The latest representable date, ``date(MAXYEAR, 12, 31)``.
354 .. attribute:: date.resolution
356 The smallest possible difference between non-equal date objects,
357 ``timedelta(days=1)``.
359 Instance attributes (read-only):
362 .. attribute:: date.year
364 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
367 .. attribute:: date.month
369 Between 1 and 12 inclusive.
372 .. attribute:: date.day
374 Between 1 and the number of days in the given month of the given year.
376 Supported operations:
378 +-------------------------------+----------------------------------------------+
379 | Operation | Result |
380 +===============================+==============================================+
381 | ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
382 | | from *date1*. (1) |
383 +-------------------------------+----------------------------------------------+
384 | ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
385 | | timedelta == date1``. (2) |
386 +-------------------------------+----------------------------------------------+
387 | ``timedelta = date1 - date2`` | \(3) |
388 +-------------------------------+----------------------------------------------+
389 | ``date1 < date2`` | *date1* is considered less than *date2* when |
390 | | *date1* precedes *date2* in time. (4) |
391 +-------------------------------+----------------------------------------------+
396 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
397 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
398 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
399 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
400 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
403 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
404 isolation can overflow in cases where date1 - timedelta does not.
405 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
408 This is exact, and cannot overflow. timedelta.seconds and
409 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
412 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
413 date2.toordinal()``. In order to stop comparison from falling back to the
414 default scheme of comparing object addresses, date comparison normally raises
415 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
416 However, ``NotImplemented`` is returned instead if the other comparand has a
417 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
418 chance at implementing mixed-type comparison. If not, when a :class:`date`
419 object is compared to an object of a different type, :exc:`TypeError` is raised
420 unless the comparison is ``==`` or ``!=``. The latter cases return
421 :const:`False` or :const:`True`, respectively.
423 Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
424 objects are considered to be true.
429 .. method:: date.replace(year, month, day)
431 Return a date with the same value, except for those members given new values by
432 whichever keyword arguments are specified. For example, if ``d == date(2002,
433 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
436 .. method:: date.timetuple()
438 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
439 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
440 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
441 d.weekday(), d.toordinal() - date(d.year, 1, 1).toordinal() + 1, -1))``
444 .. method:: date.toordinal()
446 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
447 has ordinal 1. For any :class:`date` object *d*,
448 ``date.fromordinal(d.toordinal()) == d``.
451 .. method:: date.weekday()
453 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
454 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
458 .. method:: date.isoweekday()
460 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
461 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
462 :meth:`weekday`, :meth:`isocalendar`.
465 .. method:: date.isocalendar()
467 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
469 The ISO calendar is a widely used variant of the Gregorian calendar. See
470 http://www.phys.uu.nl/ vgent/calendar/isocalendar.htm for a good explanation.
472 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
473 Monday and ends on a Sunday. The first week of an ISO year is the first
474 (Gregorian) calendar week of a year containing a Thursday. This is called week
475 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
477 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
478 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
479 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
480 4).isocalendar() == (2004, 1, 7)``.
483 .. method:: date.isoformat()
485 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
486 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
489 .. method:: date.__str__()
491 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
494 .. method:: date.ctime()
496 Return a string representing the date, for example ``date(2002, 12,
497 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
498 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
499 :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
500 :meth:`date.ctime` does not invoke) conforms to the C standard.
503 .. method:: date.strftime(format)
505 Return a string representing the date, controlled by an explicit format string.
506 Format codes referring to hours, minutes or seconds will see 0 values. See
507 section :ref:`strftime-behavior`.
509 Example of counting days to an event::
512 >>> from datetime import date
513 >>> today = date.today()
515 datetime.date(2007, 12, 5)
516 >>> today == date.fromtimestamp(time.time())
518 >>> my_birthday = date(today.year, 6, 24)
519 >>> if my_birthday < today:
520 ... my_birthday = my_birthday.replace(year=today.year + 1)
522 datetime.date(2008, 6, 24)
523 >>> time_to_birthday = abs(my_birthday - today)
524 >>> time_to_birthday.days
527 Example of working with :class:`date`::
529 >>> from datetime import date
530 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
532 datetime.date(2002, 3, 11)
533 >>> t = d.timetuple()
542 0 # weekday (0 = Monday)
543 70 # 70th day in the year
545 >>> ic = d.isocalendar()
547 ... print i # doctest: +SKIP
550 1 # ISO day number ( 1 = Monday )
553 >>> d.strftime("%d/%m/%y")
555 >>> d.strftime("%A %d. %B %Y")
556 'Monday 11. March 2002'
559 .. _datetime-datetime:
561 :class:`datetime` Objects
562 -------------------------
564 A :class:`datetime` object is a single object containing all the information
565 from a :class:`date` object and a :class:`time` object. Like a :class:`date`
566 object, :class:`datetime` assumes the current Gregorian calendar extended in
567 both directions; like a time object, :class:`datetime` assumes there are exactly
568 3600\*24 seconds in every day.
573 .. class:: datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])
575 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
576 instance of a :class:`tzinfo` subclass. The remaining arguments may be ints or
577 longs, in the following ranges:
579 * ``MINYEAR <= year <= MAXYEAR``
580 * ``1 <= month <= 12``
581 * ``1 <= day <= number of days in the given month and year``
583 * ``0 <= minute < 60``
584 * ``0 <= second < 60``
585 * ``0 <= microsecond < 1000000``
587 If an argument outside those ranges is given, :exc:`ValueError` is raised.
589 Other constructors, all class methods:
592 .. method:: datetime.today()
594 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
595 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
596 :meth:`fromtimestamp`.
599 .. method:: datetime.now([tz])
601 Return the current local date and time. If optional argument *tz* is ``None``
602 or not specified, this is like :meth:`today`, but, if possible, supplies more
603 precision than can be gotten from going through a :func:`time.time` timestamp
604 (for example, this may be possible on platforms supplying the C
605 :cfunc:`gettimeofday` function).
607 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
608 current date and time are converted to *tz*'s time zone. In this case the
609 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
610 See also :meth:`today`, :meth:`utcnow`.
613 .. method:: datetime.utcnow()
615 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
616 :meth:`now`, but returns the current UTC date and time, as a naive
617 :class:`datetime` object. See also :meth:`now`.
620 .. method:: datetime.fromtimestamp(timestamp[, tz])
622 Return the local date and time corresponding to the POSIX timestamp, such as is
623 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
624 specified, the timestamp is converted to the platform's local date and time, and
625 the returned :class:`datetime` object is naive.
627 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
628 timestamp is converted to *tz*'s time zone. In this case the result is
630 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
632 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
633 the range of values supported by the platform C :cfunc:`localtime` or
634 :cfunc:`gmtime` functions. It's common for this to be restricted to years in
635 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
636 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
637 and then it's possible to have two timestamps differing by a second that yield
638 identical :class:`datetime` objects. See also :meth:`utcfromtimestamp`.
641 .. method:: datetime.utcfromtimestamp(timestamp)
643 Return the UTC :class:`datetime` corresponding to the POSIX timestamp, with
644 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
645 out of the range of values supported by the platform C :cfunc:`gmtime` function.
646 It's common for this to be restricted to years in 1970 through 2038. See also
647 :meth:`fromtimestamp`.
650 .. method:: datetime.fromordinal(ordinal)
652 Return the :class:`datetime` corresponding to the proleptic Gregorian ordinal,
653 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
654 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
655 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
658 .. method:: datetime.combine(date, time)
660 Return a new :class:`datetime` object whose date members are equal to the given
661 :class:`date` object's, and whose time and :attr:`tzinfo` members are equal to
662 the given :class:`time` object's. For any :class:`datetime` object *d*, ``d ==
663 datetime.combine(d.date(), d.timetz())``. If date is a :class:`datetime`
664 object, its time and :attr:`tzinfo` members are ignored.
667 .. method:: datetime.strptime(date_string, format)
669 Return a :class:`datetime` corresponding to *date_string*, parsed according to
670 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
671 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
672 can't be parsed by :func:`time.strptime` or if it returns a value which isn't a
675 .. versionadded:: 2.5
680 .. attribute:: datetime.min
682 The earliest representable :class:`datetime`, ``datetime(MINYEAR, 1, 1,
686 .. attribute:: datetime.max
688 The latest representable :class:`datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
689 59, 999999, tzinfo=None)``.
692 .. attribute:: datetime.resolution
694 The smallest possible difference between non-equal :class:`datetime` objects,
695 ``timedelta(microseconds=1)``.
697 Instance attributes (read-only):
700 .. attribute:: datetime.year
702 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
705 .. attribute:: datetime.month
707 Between 1 and 12 inclusive.
710 .. attribute:: datetime.day
712 Between 1 and the number of days in the given month of the given year.
715 .. attribute:: datetime.hour
720 .. attribute:: datetime.minute
725 .. attribute:: datetime.second
730 .. attribute:: datetime.microsecond
732 In ``range(1000000)``.
735 .. attribute:: datetime.tzinfo
737 The object passed as the *tzinfo* argument to the :class:`datetime` constructor,
738 or ``None`` if none was passed.
740 Supported operations:
742 +---------------------------------------+-------------------------------+
743 | Operation | Result |
744 +=======================================+===============================+
745 | ``datetime2 = datetime1 + timedelta`` | \(1) |
746 +---------------------------------------+-------------------------------+
747 | ``datetime2 = datetime1 - timedelta`` | \(2) |
748 +---------------------------------------+-------------------------------+
749 | ``timedelta = datetime1 - datetime2`` | \(3) |
750 +---------------------------------------+-------------------------------+
751 | ``datetime1 < datetime2`` | Compares :class:`datetime` to |
752 | | :class:`datetime`. (4) |
753 +---------------------------------------+-------------------------------+
756 datetime2 is a duration of timedelta removed from datetime1, moving forward in
757 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
758 result has the same :attr:`tzinfo` member as the input datetime, and datetime2 -
759 datetime1 == timedelta after. :exc:`OverflowError` is raised if datetime2.year
760 would be smaller than :const:`MINYEAR` or larger than :const:`MAXYEAR`. Note
761 that no time zone adjustments are done even if the input is an aware object.
764 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
765 addition, the result has the same :attr:`tzinfo` member as the input datetime,
766 and no time zone adjustments are done even if the input is aware. This isn't
767 quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation
768 can overflow in cases where datetime1 - timedelta does not.
771 Subtraction of a :class:`datetime` from a :class:`datetime` is defined only if
772 both operands are naive, or if both are aware. If one is aware and the other is
773 naive, :exc:`TypeError` is raised.
775 If both are naive, or both are aware and have the same :attr:`tzinfo` member,
776 the :attr:`tzinfo` members are ignored, and the result is a :class:`timedelta`
777 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
778 are done in this case.
780 If both are aware and have different :attr:`tzinfo` members, ``a-b`` acts as if
781 *a* and *b* were first converted to naive UTC datetimes first. The result is
782 ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) -
783 b.utcoffset())`` except that the implementation never overflows.
786 *datetime1* is considered less than *datetime2* when *datetime1* precedes
789 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
790 If both comparands are aware, and have the same :attr:`tzinfo` member, the
791 common :attr:`tzinfo` member is ignored and the base datetimes are compared. If
792 both comparands are aware and have different :attr:`tzinfo` members, the
793 comparands are first adjusted by subtracting their UTC offsets (obtained from
794 ``self.utcoffset()``).
798 In order to stop comparison from falling back to the default scheme of comparing
799 object addresses, datetime comparison normally raises :exc:`TypeError` if the
800 other comparand isn't also a :class:`datetime` object. However,
801 ``NotImplemented`` is returned instead if the other comparand has a
802 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
803 chance at implementing mixed-type comparison. If not, when a :class:`datetime`
804 object is compared to an object of a different type, :exc:`TypeError` is raised
805 unless the comparison is ``==`` or ``!=``. The latter cases return
806 :const:`False` or :const:`True`, respectively.
808 :class:`datetime` objects can be used as dictionary keys. In Boolean contexts,
809 all :class:`datetime` objects are considered to be true.
814 .. method:: datetime.date()
816 Return :class:`date` object with same year, month and day.
819 .. method:: datetime.time()
821 Return :class:`time` object with same hour, minute, second and microsecond.
822 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
825 .. method:: datetime.timetz()
827 Return :class:`time` object with same hour, minute, second, microsecond, and
828 tzinfo members. See also method :meth:`time`.
831 .. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
833 Return a datetime with the same members, except for those members given new
834 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
835 can be specified to create a naive datetime from an aware datetime with no
836 conversion of date and time members.
839 .. method:: datetime.astimezone(tz)
841 Return a :class:`datetime` object with new :attr:`tzinfo` member *tz*, adjusting
842 the date and time members so the result is the same UTC time as *self*, but in
845 *tz* must be an instance of a :class:`tzinfo` subclass, and its
846 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
847 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
848 not return ``None``).
850 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
851 adjustment of date or time members is performed. Else the result is local time
852 in time zone *tz*, representing the same UTC time as *self*: after ``astz =
853 dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have the same date
854 and time members as ``dt - dt.utcoffset()``. The discussion of class
855 :class:`tzinfo` explains the cases at Daylight Saving Time transition boundaries
856 where this cannot be achieved (an issue only if *tz* models both standard and
859 If you merely want to attach a time zone object *tz* to a datetime *dt* without
860 adjustment of date and time members, use ``dt.replace(tzinfo=tz)``. If you
861 merely want to remove the time zone object from an aware datetime *dt* without
862 conversion of date and time members, use ``dt.replace(tzinfo=None)``.
864 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
865 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
866 Ignoring error cases, :meth:`astimezone` acts like::
868 def astimezone(self, tz):
869 if self.tzinfo is tz:
871 # Convert self to UTC, and attach the new time zone object.
872 utc = (self - self.utcoffset()).replace(tzinfo=tz)
873 # Convert from UTC to tz's local time.
874 return tz.fromutc(utc)
877 .. method:: datetime.utcoffset()
879 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
880 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
881 return ``None``, or a :class:`timedelta` object representing a whole number of
882 minutes with magnitude less than one day.
885 .. method:: datetime.dst()
887 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
888 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
889 ``None``, or a :class:`timedelta` object representing a whole number of minutes
890 with magnitude less than one day.
893 .. method:: datetime.tzname()
895 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
896 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
897 ``None`` or a string object,
900 .. method:: datetime.timetuple()
902 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
903 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
904 d.hour, d.minute, d.second, d.weekday(), d.toordinal() - date(d.year, 1,
905 1).toordinal() + 1, dst))`` The :attr:`tm_isdst` flag of the result is set
906 according to the :meth:`dst` method: :attr:`tzinfo` is ``None`` or :meth:`dst`
907 returns ``None``, :attr:`tm_isdst` is set to ``-1``; else if :meth:`dst`
908 returns a non-zero value, :attr:`tm_isdst` is set to ``1``; else ``tm_isdst`` is
912 .. method:: datetime.utctimetuple()
914 If :class:`datetime` instance *d* is naive, this is the same as
915 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
916 ``d.dst()`` returns. DST is never in effect for a UTC time.
918 If *d* is aware, *d* is normalized to UTC time, by subtracting
919 ``d.utcoffset()``, and a :class:`time.struct_time` for the normalized time is
920 returned. :attr:`tm_isdst` is forced to 0. Note that the result's
921 :attr:`tm_year` member may be :const:`MINYEAR`\ -1 or :const:`MAXYEAR`\ +1, if
922 *d*.year was ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
926 .. method:: datetime.toordinal()
928 Return the proleptic Gregorian ordinal of the date. The same as
929 ``self.date().toordinal()``.
932 .. method:: datetime.weekday()
934 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
935 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
938 .. method:: datetime.isoweekday()
940 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
941 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
945 .. method:: datetime.isocalendar()
947 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
948 ``self.date().isocalendar()``.
951 .. method:: datetime.isoformat([sep])
953 Return a string representing the date and time in ISO 8601 format,
954 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
957 If :meth:`utcoffset` does not return ``None``, a 6-character string is
958 appended, giving the UTC offset in (signed) hours and minutes:
959 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
960 YYYY-MM-DDTHH:MM:SS+HH:MM
962 The optional argument *sep* (default ``'T'``) is a one-character separator,
963 placed between the date and time portions of the result. For example, ::
965 >>> from datetime import tzinfo, timedelta, datetime
966 >>> class TZ(tzinfo):
967 ... def utcoffset(self, dt): return timedelta(minutes=-399)
969 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
970 '2002-12-25 00:00:00-06:39'
973 .. method:: datetime.__str__()
975 For a :class:`datetime` instance *d*, ``str(d)`` is equivalent to
976 ``d.isoformat(' ')``.
979 .. method:: datetime.ctime()
981 Return a string representing the date and time, for example ``datetime(2002, 12,
982 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
983 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
984 native C :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
985 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
988 .. method:: datetime.strftime(format)
990 Return a string representing the date and time, controlled by an explicit format
991 string. See section :ref:`strftime-behavior`.
993 Examples of working with datetime objects::
995 >>> from datetime import datetime, date, time
996 >>> # Using datetime.combine()
997 >>> d = date(2005, 7, 14)
999 >>> datetime.combine(d, t)
1000 datetime.datetime(2005, 7, 14, 12, 30)
1001 >>> # Using datetime.now() or datetime.utcnow()
1003 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
1004 >>> datetime.utcnow()
1005 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1006 >>> # Using datetime.strptime()
1007 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1009 datetime.datetime(2006, 11, 21, 16, 30)
1010 >>> # Using datetime.timetuple() to get tuple of all attributes
1011 >>> tt = dt.timetuple()
1021 1 # weekday (0 = Monday)
1022 325 # number of days since 1st January
1023 -1 # dst - method tzinfo.dst() returned None
1024 >>> # Date in ISO format
1025 >>> ic = dt.isocalendar()
1032 >>> # Formatting datetime
1033 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1034 'Tuesday, 21. November 2006 04:30PM'
1036 Using datetime with tzinfo::
1038 >>> from datetime import timedelta, datetime, tzinfo
1039 >>> class GMT1(tzinfo):
1040 ... def __init__(self): # DST starts last Sunday in March
1041 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1042 ... self.dston = d - timedelta(days=d.weekday() + 1)
1043 ... d = datetime(dt.year, 11, 1)
1044 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1045 ... def utcoffset(self, dt):
1046 ... return timedelta(hours=1) + self.dst(dt)
1047 ... def dst(self, dt):
1048 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1049 ... return timedelta(hours=1)
1051 ... return timedelta(0)
1052 ... def tzname(self,dt):
1055 >>> class GMT2(tzinfo):
1056 ... def __init__(self):
1057 ... d = datetime(dt.year, 4, 1)
1058 ... self.dston = d - timedelta(days=d.weekday() + 1)
1059 ... d = datetime(dt.year, 11, 1)
1060 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
1061 ... def utcoffset(self, dt):
1062 ... return timedelta(hours=1) + self.dst(dt)
1063 ... def dst(self, dt):
1064 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1065 ... return timedelta(hours=2)
1067 ... return timedelta(0)
1068 ... def tzname(self,dt):
1072 >>> # Daylight Saving Time
1073 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1075 datetime.timedelta(0)
1077 datetime.timedelta(0, 3600)
1078 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1080 datetime.timedelta(0, 3600)
1082 datetime.timedelta(0, 7200)
1083 >>> # Convert datetime to another time zone
1084 >>> dt3 = dt2.astimezone(GMT2())
1085 >>> dt3 # doctest: +ELLIPSIS
1086 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1087 >>> dt2 # doctest: +ELLIPSIS
1088 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1089 >>> dt2.utctimetuple() == dt3.utctimetuple()
1096 :class:`time` Objects
1097 ---------------------
1099 A time object represents a (local) time of day, independent of any particular
1100 day, and subject to adjustment via a :class:`tzinfo` object.
1103 .. class:: time(hour[, minute[, second[, microsecond[, tzinfo]]]])
1105 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
1106 :class:`tzinfo` subclass. The remaining arguments may be ints or longs, in the
1109 * ``0 <= hour < 24``
1110 * ``0 <= minute < 60``
1111 * ``0 <= second < 60``
1112 * ``0 <= microsecond < 1000000``.
1114 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1115 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1120 .. attribute:: time.min
1122 The earliest representable :class:`time`, ``time(0, 0, 0, 0)``.
1125 .. attribute:: time.max
1127 The latest representable :class:`time`, ``time(23, 59, 59, 999999)``.
1130 .. attribute:: time.resolution
1132 The smallest possible difference between non-equal :class:`time` objects,
1133 ``timedelta(microseconds=1)``, although note that arithmetic on :class:`time`
1134 objects is not supported.
1136 Instance attributes (read-only):
1139 .. attribute:: time.hour
1144 .. attribute:: time.minute
1149 .. attribute:: time.second
1154 .. attribute:: time.microsecond
1156 In ``range(1000000)``.
1159 .. attribute:: time.tzinfo
1161 The object passed as the tzinfo argument to the :class:`time` constructor, or
1162 ``None`` if none was passed.
1164 Supported operations:
1166 * comparison of :class:`time` to :class:`time`, where *a* is considered less
1167 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1168 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
1169 the same :attr:`tzinfo` member, the common :attr:`tzinfo` member is ignored and
1170 the base times are compared. If both comparands are aware and have different
1171 :attr:`tzinfo` members, the comparands are first adjusted by subtracting their
1172 UTC offsets (obtained from ``self.utcoffset()``). In order to stop mixed-type
1173 comparisons from falling back to the default comparison by object address, when
1174 a :class:`time` object is compared to an object of a different type,
1175 :exc:`TypeError` is raised unless the comparison is ``==`` or ``!=``. The
1176 latter cases return :const:`False` or :const:`True`, respectively.
1178 * hash, use as dict key
1180 * efficient pickling
1182 * in Boolean contexts, a :class:`time` object is considered to be true if and
1183 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1184 ``0`` if that's ``None``), the result is non-zero.
1189 .. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1191 Return a :class:`time` with the same value, except for those members given new
1192 values by whichever keyword arguments are specified. Note that ``tzinfo=None``
1193 can be specified to create a naive :class:`time` from an aware :class:`time`,
1194 without conversion of the time members.
1197 .. method:: time.isoformat()
1199 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1200 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1201 6-character string is appended, giving the UTC offset in (signed) hours and
1202 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1205 .. method:: time.__str__()
1207 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1210 .. method:: time.strftime(format)
1212 Return a string representing the time, controlled by an explicit format string.
1213 See section :ref:`strftime-behavior`.
1216 .. method:: time.utcoffset()
1218 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1219 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1220 return ``None`` or a :class:`timedelta` object representing a whole number of
1221 minutes with magnitude less than one day.
1224 .. method:: time.dst()
1226 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1227 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1228 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1229 with magnitude less than one day.
1232 .. method:: time.tzname()
1234 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1235 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1236 return ``None`` or a string object.
1240 >>> from datetime import time, tzinfo
1241 >>> class GMT1(tzinfo):
1242 ... def utcoffset(self, dt):
1243 ... return timedelta(hours=1)
1244 ... def dst(self, dt):
1245 ... return timedelta(0)
1246 ... def tzname(self,dt):
1247 ... return "Europe/Prague"
1249 >>> t = time(12, 10, 30, tzinfo=GMT1())
1250 >>> t # doctest: +ELLIPSIS
1251 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1256 datetime.timedelta(0)
1259 >>> t.strftime("%H:%M:%S %Z")
1260 '12:10:30 Europe/Prague'
1263 .. _datetime-tzinfo:
1265 :class:`tzinfo` Objects
1266 -----------------------
1268 :class:`tzinfo` is an abstract base clase, meaning that this class should not be
1269 instantiated directly. You need to derive a concrete subclass, and (at least)
1270 supply implementations of the standard :class:`tzinfo` methods needed by the
1271 :class:`datetime` methods you use. The :mod:`datetime` module does not supply
1272 any concrete subclasses of :class:`tzinfo`.
1274 An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1275 constructors for :class:`datetime` and :class:`time` objects. The latter objects
1276 view their members as being in local time, and the :class:`tzinfo` object
1277 supports methods revealing offset of local time from UTC, the name of the time
1278 zone, and DST offset, all relative to a date or time object passed to them.
1280 Special requirement for pickling: A :class:`tzinfo` subclass must have an
1281 :meth:`__init__` method that can be called with no arguments, else it can be
1282 pickled but possibly not unpickled again. This is a technical requirement that
1283 may be relaxed in the future.
1285 A concrete subclass of :class:`tzinfo` may need to implement the following
1286 methods. Exactly which methods are needed depends on the uses made of aware
1287 :mod:`datetime` objects. If in doubt, simply implement all of them.
1290 .. method:: tzinfo.utcoffset(self, dt)
1292 Return offset of local time from UTC, in minutes east of UTC. If local time is
1293 west of UTC, this should be negative. Note that this is intended to be the
1294 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1295 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1296 the UTC offset isn't known, return ``None``. Else the value returned must be a
1297 :class:`timedelta` object specifying a whole number of minutes in the range
1298 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1299 than one day). Most implementations of :meth:`utcoffset` will probably look
1300 like one of these two::
1302 return CONSTANT # fixed-offset class
1303 return CONSTANT + self.dst(dt) # daylight-aware class
1305 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1308 The default implementation of :meth:`utcoffset` raises
1309 :exc:`NotImplementedError`.
1312 .. method:: tzinfo.dst(self, dt)
1314 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1315 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1316 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1317 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1318 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1319 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1320 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
1321 member's :meth:`dst` method to determine how the :attr:`tm_isdst` flag should be
1322 set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for DST changes
1323 when crossing time zones.
1325 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1326 daylight times must be consistent in this sense:
1328 ``tz.utcoffset(dt) - tz.dst(dt)``
1330 must return the same result for every :class:`datetime` *dt* with ``dt.tzinfo ==
1331 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1332 zone's "standard offset", which should not depend on the date or the time, but
1333 only on geographic location. The implementation of :meth:`datetime.astimezone`
1334 relies on this, but cannot detect violations; it's the programmer's
1335 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1336 this, it may be able to override the default implementation of
1337 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1339 Most implementations of :meth:`dst` will probably look like one of these two::
1342 # a fixed-offset class: doesn't account for DST
1348 # Code to set dston and dstoff to the time zone's DST
1349 # transition times based on the input dt.year, and expressed
1350 # in standard local time. Then
1352 if dston <= dt.replace(tzinfo=None) < dstoff:
1353 return timedelta(hours=1)
1357 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1360 .. method:: tzinfo.tzname(self, dt)
1362 Return the time zone name corresponding to the :class:`datetime` object *dt*, as
1363 a string. Nothing about string names is defined by the :mod:`datetime` module,
1364 and there's no requirement that it mean anything in particular. For example,
1365 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1366 valid replies. Return ``None`` if a string name isn't known. Note that this is
1367 a method rather than a fixed string primarily because some :class:`tzinfo`
1368 subclasses will wish to return different names depending on the specific value
1369 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1372 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1374 These methods are called by a :class:`datetime` or :class:`time` object, in
1375 response to their methods of the same names. A :class:`datetime` object passes
1376 itself as the argument, and a :class:`time` object passes ``None`` as the
1377 argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
1378 accept a *dt* argument of ``None``, or of class :class:`datetime`.
1380 When ``None`` is passed, it's up to the class designer to decide the best
1381 response. For example, returning ``None`` is appropriate if the class wishes to
1382 say that time objects don't participate in the :class:`tzinfo` protocols. It
1383 may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1384 there is no other convention for discovering the standard offset.
1386 When a :class:`datetime` object is passed in response to a :class:`datetime`
1387 method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1388 rely on this, unless user code calls :class:`tzinfo` methods directly. The
1389 intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1390 time, and not need worry about objects in other timezones.
1392 There is one more :class:`tzinfo` method that a subclass may wish to override:
1395 .. method:: tzinfo.fromutc(self, dt)
1397 This is called from the default :class:`datetime.astimezone()` implementation.
1398 When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members
1399 are to be viewed as expressing a UTC time. The purpose of :meth:`fromutc` is to
1400 adjust the date and time members, returning an equivalent datetime in *self*'s
1403 Most :class:`tzinfo` subclasses should be able to inherit the default
1404 :meth:`fromutc` implementation without problems. It's strong enough to handle
1405 fixed-offset time zones, and time zones accounting for both standard and
1406 daylight time, and the latter even if the DST transition times differ in
1407 different years. An example of a time zone the default :meth:`fromutc`
1408 implementation may not handle correctly in all cases is one where the standard
1409 offset (from UTC) depends on the specific date and time passed, which can happen
1410 for political reasons. The default implementations of :meth:`astimezone` and
1411 :meth:`fromutc` may not produce the result you want if the result is one of the
1412 hours straddling the moment the standard offset changes.
1414 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1417 def fromutc(self, dt):
1418 # raise ValueError error if dt.tzinfo is not self
1419 dtoff = dt.utcoffset()
1421 # raise ValueError if dtoff is None or dtdst is None
1422 delta = dtoff - dtdst # this is self's standard offset
1424 dt += delta # convert to standard local time
1426 # raise ValueError if dtdst is None
1432 Example :class:`tzinfo` classes:
1434 .. literalinclude:: ../includes/tzinfo-examples.py
1437 Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1438 subclass accounting for both standard and daylight time, at the DST transition
1439 points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
1440 minute after 1:59 (EST) on the first Sunday in April, and ends the minute after
1441 1:59 (EDT) on the last Sunday in October::
1443 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1444 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1445 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1447 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1449 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1451 When DST starts (the "start" line), the local wall clock leaps from 1:59 to
1452 3:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1453 ``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1454 begins. In order for :meth:`astimezone` to make this guarantee, the
1455 :meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1456 Eastern) to be in daylight time.
1458 When DST ends (the "end" line), there's a potentially worse problem: there's an
1459 hour that can't be spelled unambiguously in local wall time: the last hour of
1460 daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1461 daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1462 to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1463 :meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1464 hours into the same local hour then. In the Eastern example, UTC times of the
1465 form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1466 :meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1467 consider times in the "repeated hour" to be in standard time. This is easily
1468 arranged, as in the example, by expressing DST switch times in the time zone's
1469 standard local time.
1471 Applications that can't bear such ambiguities should avoid using hybrid
1472 :class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any
1473 other fixed-offset :class:`tzinfo` subclass (such as a class representing only
1474 EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
1477 .. _strftime-behavior:
1479 :meth:`strftime` Behavior
1480 -------------------------
1482 :class:`date`, :class:`datetime`, and :class:`time` objects all support a
1483 ``strftime(format)`` method, to create a string representing the time under the
1484 control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1485 acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1486 although not all objects support a :meth:`timetuple` method.
1488 For :class:`time` objects, the format codes for year, month, and day should not
1489 be used, as time objects have no such values. If they're used anyway, ``1900``
1490 is substituted for the year, and ``0`` for the month and day.
1492 For :class:`date` objects, the format codes for hours, minutes, and seconds
1493 should not be used, as :class:`date` objects have no such values. If they're
1494 used anyway, ``0`` is substituted for them.
1496 The full set of format codes supported varies across platforms, because Python
1497 calls the platform C library's :func:`strftime` function, and platform
1498 variations are common.
1500 The following is a list of all the format codes that the C standard (1989
1501 version) requires, and these work on all platforms with a standard C
1502 implementation. Note that the 1999 version of the C standard added additional
1505 The exact range of years for which :meth:`strftime` works also varies across
1506 platforms. Regardless of platform, years before 1900 cannot be used.
1508 +-----------+--------------------------------+-------+
1509 | Directive | Meaning | Notes |
1510 +===========+================================+=======+
1511 | ``%a`` | Locale's abbreviated weekday | |
1513 +-----------+--------------------------------+-------+
1514 | ``%A`` | Locale's full weekday name. | |
1515 +-----------+--------------------------------+-------+
1516 | ``%b`` | Locale's abbreviated month | |
1518 +-----------+--------------------------------+-------+
1519 | ``%B`` | Locale's full month name. | |
1520 +-----------+--------------------------------+-------+
1521 | ``%c`` | Locale's appropriate date and | |
1522 | | time representation. | |
1523 +-----------+--------------------------------+-------+
1524 | ``%d`` | Day of the month as a decimal | |
1525 | | number [01,31]. | |
1526 +-----------+--------------------------------+-------+
1527 | ``%H`` | Hour (24-hour clock) as a | |
1528 | | decimal number [00,23]. | |
1529 +-----------+--------------------------------+-------+
1530 | ``%I`` | Hour (12-hour clock) as a | |
1531 | | decimal number [01,12]. | |
1532 +-----------+--------------------------------+-------+
1533 | ``%j`` | Day of the year as a decimal | |
1534 | | number [001,366]. | |
1535 +-----------+--------------------------------+-------+
1536 | ``%m`` | Month as a decimal number | |
1538 +-----------+--------------------------------+-------+
1539 | ``%M`` | Minute as a decimal number | |
1541 +-----------+--------------------------------+-------+
1542 | ``%p`` | Locale's equivalent of either | \(1) |
1544 +-----------+--------------------------------+-------+
1545 | ``%S`` | Second as a decimal number | \(2) |
1547 +-----------+--------------------------------+-------+
1548 | ``%U`` | Week number of the year | \(3) |
1549 | | (Sunday as the first day of | |
1550 | | the week) as a decimal number | |
1551 | | [00,53]. All days in a new | |
1552 | | year preceding the first | |
1553 | | Sunday are considered to be in | |
1555 +-----------+--------------------------------+-------+
1556 | ``%w`` | Weekday as a decimal number | |
1557 | | [0(Sunday),6]. | |
1558 +-----------+--------------------------------+-------+
1559 | ``%W`` | Week number of the year | \(3) |
1560 | | (Monday as the first day of | |
1561 | | the week) as a decimal number | |
1562 | | [00,53]. All days in a new | |
1563 | | year preceding the first | |
1564 | | Monday are considered to be in | |
1566 +-----------+--------------------------------+-------+
1567 | ``%x`` | Locale's appropriate date | |
1568 | | representation. | |
1569 +-----------+--------------------------------+-------+
1570 | ``%X`` | Locale's appropriate time | |
1571 | | representation. | |
1572 +-----------+--------------------------------+-------+
1573 | ``%y`` | Year without century as a | |
1574 | | decimal number [00,99]. | |
1575 +-----------+--------------------------------+-------+
1576 | ``%Y`` | Year with century as a decimal | |
1578 +-----------+--------------------------------+-------+
1579 | ``%z`` | UTC offset in the form +HHMM | \(4) |
1580 | | or -HHMM (empty string if the | |
1581 | | the object is naive). | |
1582 +-----------+--------------------------------+-------+
1583 | ``%Z`` | Time zone name (empty string | |
1584 | | if the object is naive). | |
1585 +-----------+--------------------------------+-------+
1586 | ``%%`` | A literal ``'%'`` character. | |
1587 +-----------+--------------------------------+-------+
1592 When used with the :func:`strptime` function, the ``%p`` directive only affects
1593 the output hour field if the ``%I`` directive is used to parse the hour.
1596 The range really is ``0`` to ``61``; this accounts for leap seconds and the
1597 (very rare) double leap seconds.
1600 When used with the :func:`strptime` function, ``%U`` and ``%W`` are only used in
1601 calculations when the day of the week and the year are specified.
1604 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1605 ``%z`` is replaced with the string ``'-0330'``.