diff options
Diffstat (limited to 'Doc/library/datetime.rst')
| -rw-r--r-- | Doc/library/datetime.rst | 209 |
1 files changed, 166 insertions, 43 deletions
diff --git a/Doc/library/datetime.rst b/Doc/library/datetime.rst index 26d9946..de9ad44 100644 --- a/Doc/library/datetime.rst +++ b/Doc/library/datetime.rst @@ -28,11 +28,14 @@ For applications requiring more, :class:`datetime` and :class:`time` objects have an optional time zone information member, :attr:`tzinfo`, that can contain an instance of a subclass of the abstract :class:`tzinfo` class. These :class:`tzinfo` objects capture information about the offset from UTC time, the -time zone name, and whether Daylight Saving Time is in effect. Note that no -concrete :class:`tzinfo` classes are supplied by the :mod:`datetime` module. -Supporting timezones at whatever level of detail is required is up to the -application. The rules for time adjustment across the world are more political -than rational, and there is no standard suitable for every application. +time zone name, and whether Daylight Saving Time is in effect. Note that only +one concrete :class:`tzinfo` class, the :class:`timezone` class, is supplied by the +:mod:`datetime` module. The :class:`timezone` class can reprsent simple +timezones with fixed offset from UTC such as UTC itself or North American EST and +EDT timezones. Supporting timezones at whatever level of detail is +required is up to the application. The rules for time adjustment across the +world are more political than rational, change frequently, and there is no +standard suitable for every application aside from UTC. The :mod:`datetime` module exports the following constants: @@ -99,6 +102,14 @@ Available Types time adjustment (for example, to account for time zone and/or daylight saving time). +.. class:: timezone + + A class that implements the :class:`tzinfo` abstract base class as a + fixed offset from the UTC. + + .. versionadded:: 3.2 + + Objects of these types are immutable. Objects of the :class:`date` type are always naive. @@ -116,6 +127,7 @@ Subclass relationships:: object timedelta tzinfo + timezone time date datetime @@ -220,8 +232,28 @@ Supported operations: | | In general, *t1* \* i == *t1* \* (i-1) + *t1* | | | is true. (1) | +--------------------------------+-----------------------------------------------+ -| ``t1 = t2 // i`` | The floor is computed and the remainder (if | -| | any) is thrown away. (3) | +| ``t1 = t2 * f or t1 = f * t2`` | Delta multiplied by a float. The result is | +| | rounded to the nearest multiple of | +| | timedelta.resolution using round-half-to-even.| ++--------------------------------+-----------------------------------------------+ +| ``f = t2 / t3`` | Division (3) of *t2* by *t3*. Returns a | +| | :class:`float` object. | ++--------------------------------+-----------------------------------------------+ +| ``t1 = t2 / f or t1 = t2 / i`` | Delta divided by a float or an int. The result| +| | is rounded to the nearest multiple of | +| | timedelta.resolution using round-half-to-even.| ++--------------------------------+-----------------------------------------------+ +| ``t1 = t2 // i`` or | The floor is computed and the remainder (if | +| ``t1 = t2 // t3`` | any) is thrown away. In the second case, an | +| | integer is returned. (3) | ++--------------------------------+-----------------------------------------------+ +| ``t1 = t2 % t3`` | The remainder is computed as a | +| | :class:`timedelta` object. (3) | ++--------------------------------+-----------------------------------------------+ +| ``q, r = divmod(t1, t2)`` | Computes the quotient and the remainder: | +| | ``q = t1 // t2`` (3) and ``r = t1 % t2``. | +| | q is an integer and r is a :class:`timedelta` | +| | object. | +--------------------------------+-----------------------------------------------+ | ``+t1`` | Returns a :class:`timedelta` object with the | | | same value. (2) | @@ -270,6 +302,13 @@ In addition to the operations listed above :class:`timedelta` objects support certain additions and subtractions with :class:`date` and :class:`datetime` objects (see below). +.. versionchanged:: 3.2 + Floor division and true division of a :class:`timedelta` object by another + :class:`timedelta` object are now supported, as are remainder operations and + the :func:`divmod` function. True division and multiplication of a + :class:`timedelta` object by a :class:`float` object are now supported. + + Comparisons of :class:`timedelta` objects are supported with the :class:`timedelta` object representing the smaller duration considered to be the smaller timedelta. In order to stop mixed-type comparisons from falling back to @@ -282,12 +321,27 @@ comparison is ``==`` or ``!=``. The latter cases return :const:`False` or efficient pickling, and in Boolean contexts, a :class:`timedelta` object is considered to be true if and only if it isn't equal to ``timedelta(0)``. +Instance methods: + +.. method:: timedelta.total_seconds() + + Return the total number of seconds contained in the duration. Equivalent to + ``td / timedelta(seconds=1)``. + + Note that for very large time intervals (greater than 270 years on + most platforms) this method will lose microsecond accuracy. + + .. versionadded:: 3.2 + + Example usage: >>> from datetime import timedelta >>> year = timedelta(days=365) >>> another_year = timedelta(weeks=40, days=84, hours=23, ... minutes=50, seconds=600) # adds up to 365 days + >>> year.total_seconds() + 31536000.0 >>> year == another_year True >>> ten_years = 10 * year @@ -342,7 +396,7 @@ Other constructors, all class methods: Return the local date corresponding to the POSIX timestamp, such as is returned by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out - of the range of values supported by the platform C :cfunc:`localtime` function. + of the range of values supported by the platform C :c:func:`localtime` function. It's common for this to be restricted to years from 1970 through 2038. Note that on non-POSIX systems that include leap seconds in their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`. @@ -516,7 +570,7 @@ Instance methods: Return a string representing the date, for example ``date(2002, 12, 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C - :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which + :c:func:`ctime` function (which :func:`time.ctime` invokes, but which :meth:`date.ctime` does not invoke) conforms to the C standard. @@ -623,7 +677,7 @@ Other constructors, all class methods: or not specified, this is like :meth:`today`, but, if possible, supplies more precision than can be gotten from going through a :func:`time.time` timestamp (for example, this may be possible on platforms supplying the C - :cfunc:`gettimeofday` function). + :c:func:`gettimeofday` function). Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the current date and time are converted to *tz*'s time zone. In this case the @@ -635,8 +689,8 @@ Other constructors, all class methods: Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like :meth:`now`, but returns the current UTC date and time, as a naive - :class:`datetime` object. See also :meth:`now`. - + :class:`datetime` object. An aware current UTC datetime can be obtained by + calling ``datetime.now(timezone.utc)``. See also :meth:`now`. .. classmethod:: datetime.fromtimestamp(timestamp, tz=None) @@ -651,8 +705,8 @@ Other constructors, all class methods: ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``. :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of - the range of values supported by the platform C :cfunc:`localtime` or - :cfunc:`gmtime` functions. It's common for this to be restricted to years in + the range of values supported by the platform C :c:func:`localtime` or + :c:func:`gmtime` functions. It's common for this to be restricted to years in 1970 through 2038. Note that on non-POSIX systems that include leap seconds in their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`, and then it's possible to have two timestamps differing by a second that yield @@ -663,7 +717,7 @@ Other constructors, all class methods: Return the UTC :class:`datetime` corresponding to the POSIX timestamp, with :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is - out of the range of values supported by the platform C :cfunc:`gmtime` function. + out of the range of values supported by the platform C :c:func:`gmtime` function. It's common for this to be restricted to years in 1970 through 2038. See also :meth:`fromtimestamp`. @@ -927,7 +981,7 @@ Instance methods: of the result is set according to the :meth:`dst` method: :attr:`tzinfo` is ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``; else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``; - else ``tm_isdst`` is set to ``0``. + else :attr:`tm_isdst` is set to ``0``. .. method:: datetime.utctimetuple() @@ -937,10 +991,10 @@ Instance methods: ``d.dst()`` returns. DST is never in effect for a UTC time. If *d* is aware, *d* is normalized to UTC time, by subtracting - ``d.utcoffset()``, and a :class:`time.struct_time` for the normalized time is - returned. :attr:`tm_isdst` is forced to 0. Note that the result's - :attr:`tm_year` member may be :const:`MINYEAR`\ -1 or :const:`MAXYEAR`\ +1, if - *d*.year was ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year + ``d.utcoffset()``, and a :class:`time.struct_time` for the + normalized time is returned. :attr:`tm_isdst` is forced to 0. Note + that an :exc:`OverflowError` may be raised if *d*.year was + ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year boundary. @@ -1002,7 +1056,7 @@ Instance methods: Return a string representing the date and time, for example ``datetime(2002, 12, 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the - native C :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which + native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which :meth:`datetime.ctime` does not invoke) conforms to the C standard. @@ -1293,8 +1347,10 @@ Example: :class:`tzinfo` is an abstract base class, meaning that this class should not be instantiated directly. You need to derive a concrete subclass, and (at least) supply implementations of the standard :class:`tzinfo` methods needed by the -:class:`datetime` methods you use. The :mod:`datetime` module does not supply -any concrete subclasses of :class:`tzinfo`. +:class:`datetime` methods you use. The :mod:`datetime` module supplies +a simple concrete subclass of :class:`tzinfo` :class:`timezone` which can reprsent +timezones with fixed offset from UTC such as UTC itself or North American EST and +EDT. An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the constructors for :class:`datetime` and :class:`time` objects. The latter objects @@ -1312,7 +1368,7 @@ methods. Exactly which methods are needed depends on the uses made of aware :mod:`datetime` objects. If in doubt, simply implement all of them. -.. method:: tzinfo.utcoffset(self, dt) +.. method:: tzinfo.utcoffset(dt) Return offset of local time from UTC, in minutes east of UTC. If local time is west of UTC, this should be negative. Note that this is intended to be the @@ -1334,7 +1390,7 @@ methods. Exactly which methods are needed depends on the uses made of aware :exc:`NotImplementedError`. -.. method:: tzinfo.dst(self, dt) +.. method:: tzinfo.dst(dt) Return the daylight saving time (DST) adjustment, in minutes east of UTC, or ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not @@ -1382,7 +1438,7 @@ methods. Exactly which methods are needed depends on the uses made of aware The default implementation of :meth:`dst` raises :exc:`NotImplementedError`. -.. method:: tzinfo.tzname(self, dt) +.. method:: tzinfo.tzname(dt) Return the time zone name corresponding to the :class:`datetime` object *dt*, as a string. Nothing about string names is defined by the :mod:`datetime` module, @@ -1418,7 +1474,7 @@ time, and not need worry about objects in other timezones. There is one more :class:`tzinfo` method that a subclass may wish to override: -.. method:: tzinfo.fromutc(self, dt) +.. method:: tzinfo.fromutc(dt) This is called from the default :class:`datetime.astimezone()` implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members @@ -1495,9 +1551,65 @@ arranged, as in the example, by expressing DST switch times in the time zone's standard local time. Applications that can't bear such ambiguities should avoid using hybrid -:class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any -other fixed-offset :class:`tzinfo` subclass (such as a class representing only -EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)). +:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`, +or any other fixed-offset :class:`tzinfo` subclass (such as a class representing +only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)). + + +.. _datetime-timezone: + +:class:`timezone` Objects +-------------------------- + +A :class:`timezone` object represents a timezone that is defined by a +fixed offset from UTC. Note that objects of this class cannot be used +to represent timezone information in the locations where different +offsets are used in different days of the year or where historical +changes have been made to civil time. + + +.. class:: timezone(offset[, name]) + + The *offset* argument must be specified as a :class:`timedelta` + object representing the difference between the local time and UTC. It must + be strictly between ``-timedelta(hours=24)`` and + ``timedelta(hours=24)`` and represent a whole number of minutes, + otherwise :exc:`ValueError` is raised. + + The *name* argument is optional. If specified it must be a string that + is used as the value returned by the ``tzname(dt)`` method. Otherwise, + ``tzname(dt)`` returns a string 'UTCsHH:MM', where s is the sign of + *offset*, HH and MM are two digits of ``offset.hours`` and + ``offset.minutes`` respectively. + +.. method:: timezone.utcoffset(dt) + + Return the fixed value specified when the :class:`timezone` instance is + constructed. The *dt* argument is ignored. The return value is a + :class:`timedelta` instance equal to the difference between the + local time and UTC. + +.. method:: timezone.tzname(dt) + + Return the fixed value specified when the :class:`timezone` instance is + constructed or a string 'UTCsHH:MM', where s is the sign of + *offset*, HH and MM are two digits of ``offset.hours`` and + ``offset.minutes`` respectively. + +.. method:: timezone.dst(dt) + + Always returns ``None``. + +.. method:: timezone.fromutc(dt) + + Return ``dt + offset``. The *dt* argument must be an aware + :class:`datetime` instance, with ``tzinfo`` set to ``self``. + +Class attributes: + +.. attribute:: timezone.utc + + The UTC timezone, ``timezone(timedelta(0))``. .. _strftime-strptime-behavior: @@ -1549,9 +1661,6 @@ version) requires, and these work on all platforms with a standard C implementation. Note that the 1999 version of the C standard added additional format codes. -The exact range of years for which :meth:`strftime` works also varies across -platforms. Regardless of platform, years before 1900 cannot be used. - +-----------+--------------------------------+-------+ | Directive | Meaning | Notes | +===========+================================+=======+ @@ -1594,7 +1703,7 @@ platforms. Regardless of platform, years before 1900 cannot be used. | | AM or PM. | | +-----------+--------------------------------+-------+ | ``%S`` | Second as a decimal number | \(3) | -| | [00,61]. | | +| | [00,59]. | | +-----------+--------------------------------+-------+ | ``%U`` | Week number of the year | \(4) | | | (Sunday as the first day of | | @@ -1624,10 +1733,11 @@ platforms. Regardless of platform, years before 1900 cannot be used. | ``%y`` | Year without century as a | | | | decimal number [00,99]. | | +-----------+--------------------------------+-------+ -| ``%Y`` | Year with century as a decimal | | -| | number. | | +| ``%Y`` | Year with century as a decimal | \(5) | +| | number [0001,9999] (strptime), | | +| | [1000,9999] (strftime). | | +-----------+--------------------------------+-------+ -| ``%z`` | UTC offset in the form +HHMM | \(5) | +| ``%z`` | UTC offset in the form +HHMM | \(6) | | | or -HHMM (empty string if the | | | | the object is naive). | | +-----------+--------------------------------+-------+ @@ -1651,17 +1761,30 @@ Notes: the output hour field if the ``%I`` directive is used to parse the hour. (3) - The range really is ``0`` to ``61``; according to the Posix standard this - accounts for leap seconds and the (very rare) double leap seconds. - The :mod:`time` module may produce and does accept leap seconds since - it is based on the Posix standard, but the :mod:`datetime` module - does not accept leap seconds in :meth:`strptime` input nor will it - produce them in :func:`strftime` output. + Unlike :mod:`time` module, :mod:`datetime` module does not support + leap seconds. (4) When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in calculations when the day of the week and the year are specified. (5) + For technical reasons, :meth:`strftime` method does not support + dates before year 1000: ``t.strftime(format)`` will raise a + :exc:`ValueError` when ``t.year < 1000`` even if ``format`` does + not contain ``%Y`` directive. The :meth:`strptime` method can + parse years in the full [1, 9999] range, but years < 1000 must be + zero-filled to 4-digit width. + + .. versionchanged:: 3.2 + In previous versions, :meth:`strftime` method was restricted to + years >= 1900. + +(6) For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is replaced with the string ``'-0330'``. + +.. versionchanged:: 3.2 + When the ``%z`` directive is provided to the :meth:`strptime` method, an + aware :class:`datetime` object will be produced. The ``tzinfo`` of the + result will be set to a :class:`timezone` instance. |
