n | .. % XXX what order should the types be discussed in? |
| |
| |
| :mod:`datetime` --- Basic date and time types |
| ============================================= |
| |
| .. module:: datetime |
| :synopsis: Basic date and time types. |
| .. moduleauthor:: Tim Peters <tim@zope.com> |
| .. sectionauthor:: Tim Peters <tim@zope.com> |
| .. sectionauthor:: A.M. Kuchling <amk@amk.ca> |
| |
n | .. XXX what order should the types be discussed in? |
| |
| .. versionadded:: 2.3 |
| |
| The :mod:`datetime` module supplies classes for manipulating dates and times in |
| both simple and complex ways. While date and time arithmetic is supported, the |
| focus of the implementation is on efficient member extraction for output |
n | formatting and manipulation. |
n | formatting and manipulation. For related |
| functionality, see also the :mod:`time` and :mod:`calendar` modules. |
| |
| There are two kinds of date and time objects: "naive" and "aware". This |
| distinction refers to whether the object has any notion of time zone, daylight |
| saving time, or other kind of algorithmic or political time adjustment. Whether |
| a naive :class:`datetime` object represents Coordinated Universal Time (UTC), |
| local time, or time in some other timezone is purely up to the program, just |
| like it's up to the program whether a particular number represents metres, |
| miles, or mass. Naive :class:`datetime` objects are easy to understand and to |
| .. class:: timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]) |
| |
| All arguments are optional and default to ``0``. Arguments may be ints, longs, |
| or floats, and may be positive or negative. |
| |
| Only *days*, *seconds* and *microseconds* are stored internally. Arguments are |
| converted to those units: |
| |
n | * A millisecond is converted to 1000 microseconds. |
n | * A millisecond is converted to 1000 microseconds. |
| |
| * A minute is converted to 60 seconds. |
| * A minute is converted to 60 seconds. |
| |
| * An hour is converted to 3600 seconds. |
| * An hour is converted to 3600 seconds. |
| |
| * A week is converted to 7 days. |
| * A week is converted to 7 days. |
| |
| and days, seconds and microseconds are then normalized so that the |
| representation is unique, with |
| |
n | * ``0 <= microseconds < 1000000`` |
n | * ``0 <= microseconds < 1000000`` |
| |
| * ``0 <= seconds < 3600*24`` (the number of seconds in one day) |
| * ``0 <= seconds < 3600*24`` (the number of seconds in one day) |
| |
| * ``-999999999 <= days <= 999999999`` |
| * ``-999999999 <= days <= 999999999`` |
| |
| If any argument is a float and there are fractional microseconds, the fractional |
| microseconds left over from all arguments are combined and their sum is rounded |
| to the nearest microsecond. If no argument is a float, the conversion and |
| normalization processes are exact (no information is lost). |
| |
| If the normalized value of days lies outside the indicated range, |
| :exc:`OverflowError` is raised. |
| |
| Note that normalization of negative values may be surprising at first. For |
n | example, :: |
n | example, |
| |
n | >>> from datetime import timedelta |
| >>> d = timedelta(microseconds=-1) |
| >>> (d.days, d.seconds, d.microseconds) |
| (-1, 86399, 999999) |
| |
| Class attributes are: |
| |
| |
| .. attribute:: timedelta.min |
| 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 |
| the default comparison by object address, when a :class:`timedelta` object is |
| compared to an object of a different type, :exc:`TypeError` is raised unless the |
| comparison is ``==`` or ``!=``. The latter cases return :const:`False` or |
| :const:`True`, respectively. |
| |
n | :class:`timedelta` objects are hashable (usable as dictionary keys), support |
n | :class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support |
| 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)``. |
n | |
| 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 == another_year |
| True |
| >>> ten_years = 10 * year |
| >>> ten_years, ten_years.days // 365 |
| (datetime.timedelta(3650), 10) |
| >>> nine_years = ten_years - year |
| >>> nine_years, nine_years.days // 365 |
| (datetime.timedelta(3285), 9) |
| >>> three_years = nine_years // 3; |
| >>> three_years, three_years.days // 365 |
| (datetime.timedelta(1095), 3) |
| >>> abs(three_years - ten_years) == 2 * three_years + year |
| True |
| |
| |
| .. _datetime-date: |
| |
| :class:`date` Objects |
| --------------------- |
| |
| A :class:`date` object represents a date (year, month and day) in an idealized |
| |
| .. method:: date.__str__() |
| |
| For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``. |
| |
| |
| .. method:: date.ctime() |
| |
n | Return a string representing the date, for example date(2002, 12, 4).ctime() == |
n | Return a string representing the date, for example ``date(2002, 12, |
| 'Wed Dec 4 00:00:00 2002'. ``d.ctime()`` is equivalent to |
| 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 |
| :meth:`date.ctime` does not invoke) conforms to the C standard. |
| |
| |
| .. method:: date.strftime(format) |
| |
| Return a string representing the date, controlled by an explicit format string. |
| Format codes referring to hours, minutes or seconds will see 0 values. See |
n | section :ref:`strftime-behavior` -- :meth:`strftime` behavior. |
n | section :ref:`strftime-behavior`. |
| |
| Example of counting days to an event:: |
| |
| >>> import time |
| >>> from datetime import date |
| >>> today = date.today() |
| >>> today |
| datetime.date(2007, 12, 5) |
| >>> today == date.fromtimestamp(time.time()) |
| True |
| >>> my_birthday = date(today.year, 6, 24) |
| >>> if my_birthday < today: |
| ... my_birthday = my_birthday.replace(year=today.year + 1) |
| >>> my_birthday |
| datetime.date(2008, 6, 24) |
| >>> time_to_birthday = abs(my_birthday - today) |
| >>> time_to_birthday.days |
| 202 |
| |
| Example of working with :class:`date`: |
| |
| .. doctest:: |
| |
| >>> from datetime import date |
| >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001 |
| >>> d |
| datetime.date(2002, 3, 11) |
| >>> t = d.timetuple() |
| >>> for i in t: # doctest: +SKIP |
| ... print i |
| 2002 # year |
| 3 # month |
| 11 # day |
| 0 |
| 0 |
| 0 |
| 0 # weekday (0 = Monday) |
| 70 # 70th day in the year |
| -1 |
| >>> ic = d.isocalendar() |
| >>> for i in ic: # doctest: +SKIP |
| ... print i |
| 2002 # ISO year |
| 11 # ISO week number |
| 1 # ISO day number ( 1 = Monday ) |
| >>> d.isoformat() |
| '2002-03-11' |
| >>> d.strftime("%d/%m/%y") |
| '11/03/02' |
| >>> d.strftime("%A %d. %B %Y") |
| 'Monday 11. March 2002' |
| |
| |
| .. _datetime-datetime: |
| |
| :class:`datetime` Objects |
| ------------------------- |
| |
| A :class:`datetime` object is a single object containing all the information |
| .. method:: datetime.isocalendar() |
| |
| Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as |
| ``self.date().isocalendar()``. |
| |
| |
| .. method:: datetime.isoformat([sep]) |
| |
n | Return a string representing the date and time in ISO 8601 format, YYYY-MM- |
n | Return a string representing the date and time in ISO 8601 format, |
| DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0, YYYY-MM-DDTHH:MM:SS |
| YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0, |
| YYYY-MM-DDTHH:MM:SS |
| |
n | If :meth:`utcoffset` does not return ``None``, a 6-character string is appended, |
n | If :meth:`utcoffset` does not return ``None``, a 6-character string is |
| giving the UTC offset in (signed) hours and minutes: YYYY-MM- |
| appended, giving the UTC offset in (signed) hours and minutes: |
| DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0 YYYY-MM- |
| YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0 |
| DDTHH:MM:SS+HH:MM |
| YYYY-MM-DDTHH:MM:SS+HH:MM |
| |
| The optional argument *sep* (default ``'T'``) is a one-character separator, |
n | placed between the date and time portions of the result. For example, :: |
n | placed between the date and time portions of the result. For example, |
| |
| >>> from datetime import tzinfo, timedelta, datetime |
| >>> class TZ(tzinfo): |
| ... def utcoffset(self, dt): return timedelta(minutes=-399) |
| ... |
| >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ') |
| '2002-12-25 00:00:00-06:39' |
| |
| equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the |
| native C :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which |
| :meth:`datetime.ctime` does not invoke) conforms to the C standard. |
| |
| |
| .. method:: datetime.strftime(format) |
| |
| Return a string representing the date and time, controlled by an explicit format |
n | string. See section :ref:`strftime-behavior` -- :meth:`strftime` behavior. |
n | string. See section :ref:`strftime-behavior`. |
| |
| Examples of working with datetime objects: |
| |
| .. doctest:: |
| |
| >>> from datetime import datetime, date, time |
| >>> # Using datetime.combine() |
| >>> d = date(2005, 7, 14) |
| >>> t = time(12, 30) |
| >>> datetime.combine(d, t) |
| datetime.datetime(2005, 7, 14, 12, 30) |
| >>> # Using datetime.now() or datetime.utcnow() |
| >>> datetime.now() # doctest: +SKIP |
| datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1 |
| >>> datetime.utcnow() # doctest: +SKIP |
| datetime.datetime(2007, 12, 6, 15, 29, 43, 79060) |
| >>> # Using datetime.strptime() |
| >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") |
| >>> dt |
| datetime.datetime(2006, 11, 21, 16, 30) |
| >>> # Using datetime.timetuple() to get tuple of all attributes |
| >>> tt = dt.timetuple() |
| >>> for it in tt: # doctest: +SKIP |
| ... print it |
| ... |
| 2006 # year |
| 11 # month |
| 21 # day |
| 16 # hour |
| 30 # minute |
| 0 # second |
| 1 # weekday (0 = Monday) |
| 325 # number of days since 1st January |
| -1 # dst - method tzinfo.dst() returned None |
| >>> # Date in ISO format |
| >>> ic = dt.isocalendar() |
| >>> for it in ic: # doctest: +SKIP |
| ... print it |
| ... |
| 2006 # ISO year |
| 47 # ISO week |
| 2 # ISO weekday |
| >>> # Formatting datetime |
| >>> dt.strftime("%A, %d. %B %Y %I:%M%p") |
| 'Tuesday, 21. November 2006 04:30PM' |
| |
| Using datetime with tzinfo: |
| |
| >>> from datetime import timedelta, datetime, tzinfo |
| >>> class GMT1(tzinfo): |
| ... def __init__(self): # DST starts last Sunday in March |
| ... d = datetime(dt.year, 4, 1) # ends last Sunday in October |
| ... self.dston = d - timedelta(days=d.weekday() + 1) |
| ... d = datetime(dt.year, 11, 1) |
| ... self.dstoff = d - timedelta(days=d.weekday() + 1) |
| ... def utcoffset(self, dt): |
| ... return timedelta(hours=1) + self.dst(dt) |
| ... def dst(self, dt): |
| ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff: |
| ... return timedelta(hours=1) |
| ... else: |
| ... return timedelta(0) |
| ... def tzname(self,dt): |
| ... return "GMT +1" |
| ... |
| >>> class GMT2(tzinfo): |
| ... def __init__(self): |
| ... d = datetime(dt.year, 4, 1) |
| ... self.dston = d - timedelta(days=d.weekday() + 1) |
| ... d = datetime(dt.year, 11, 1) |
| ... self.dstoff = d - timedelta(days=d.weekday() + 1) |
| ... def utcoffset(self, dt): |
| ... return timedelta(hours=1) + self.dst(dt) |
| ... def dst(self, dt): |
| ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff: |
| ... return timedelta(hours=2) |
| ... else: |
| ... return timedelta(0) |
| ... def tzname(self,dt): |
| ... return "GMT +2" |
| ... |
| >>> gmt1 = GMT1() |
| >>> # Daylight Saving Time |
| >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1) |
| >>> dt1.dst() |
| datetime.timedelta(0) |
| >>> dt1.utcoffset() |
| datetime.timedelta(0, 3600) |
| >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1) |
| >>> dt2.dst() |
| datetime.timedelta(0, 3600) |
| >>> dt2.utcoffset() |
| datetime.timedelta(0, 7200) |
| >>> # Convert datetime to another time zone |
| >>> dt3 = dt2.astimezone(GMT2()) |
| >>> dt3 # doctest: +ELLIPSIS |
| datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>) |
| >>> dt2 # doctest: +ELLIPSIS |
| datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>) |
| >>> dt2.utctimetuple() == dt3.utctimetuple() |
| True |
| |
| |
| |
| .. _datetime-time: |
| |
| :class:`time` Objects |
| --------------------- |
| |
| A time object represents a (local) time of day, independent of any particular |
| |
| |
| .. method:: time.tzname() |
| |
| If :attr:`tzinfo` is ``None``, returns ``None``, else returns |
| ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't |
| return ``None`` or a string object. |
| |
n | Example: |
| |
| >>> from datetime import time, tzinfo |
| >>> class GMT1(tzinfo): |
| ... def utcoffset(self, dt): |
| ... return timedelta(hours=1) |
| ... def dst(self, dt): |
| ... return timedelta(0) |
| ... def tzname(self,dt): |
| ... return "Europe/Prague" |
| ... |
| >>> t = time(12, 10, 30, tzinfo=GMT1()) |
| >>> t # doctest: +ELLIPSIS |
| datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>) |
| >>> gmt = GMT1() |
| >>> t.isoformat() |
| '12:10:30+01:00' |
| >>> t.dst() |
| datetime.timedelta(0) |
| >>> t.tzname() |
| 'Europe/Prague' |
| >>> t.strftime("%H:%M:%S %Z") |
| '12:10:30 Europe/Prague' |
| |
| |
| .. _datetime-tzinfo: |
| |
| :class:`tzinfo` Objects |
| ----------------------- |
| |
n | :class:`tzinfo` is an abstract base clase, meaning that this class should not be |
n | :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`. |
| |
| 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 |
| view their members as being in local time, and the :class:`tzinfo` object |
| control of an explicit format string. Broadly speaking, ``d.strftime(fmt)`` |
| acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())`` |
| although not all objects support a :meth:`timetuple` method. |
| |
| For :class:`time` objects, the format codes for year, month, and day should not |
| be used, as time objects have no such values. If they're used anyway, ``1900`` |
| is substituted for the year, and ``0`` for the month and day. |
| |
n | For :class:`date` objects, the format codes for hours, minutes, and seconds |
n | For :class:`date` objects, the format codes for hours, minutes, seconds, and |
| should not be used, as :class:`date` objects have no such values. If they're |
| microseconds should not be used, as :class:`date` objects have no such |
| used anyway, ``0`` is substituted for them. |
| values. If they're used anyway, ``0`` is substituted for them. |
| |
| .. versionadded:: 2.6 |
| :class:`time` and :class:`datetime` objects support a ``%f`` format code |
| which expands to the number of microseconds in the object, zero-padded on |
| the left to six places. |
| |
| For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty |
| strings. |
| |
| For an aware object: |
| |
| ``%z`` |
| :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or |
| replaced with the string ``'-0330'``. |
| |
| ``%Z`` |
| If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string. |
| Otherwise ``%Z`` is replaced by the returned value, which must be a string. |
| |
| The full set of format codes supported varies across platforms, because Python |
| calls the platform C library's :func:`strftime` function, and platform |
n | variations are common. The documentation for Python's :mod:`time` module lists |
n | variations are common. |
| the format codes that the C standard (1989 version) requires, and those work on |
| |
| all platforms with a standard C implementation. Note that the 1999 version of |
| The following is a list of all the format codes that the C standard (1989 |
| the C standard added additional format codes. |
| 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. |
| |
n | +-----------+--------------------------------+-------+ |
| | Directive | Meaning | Notes | |
| +===========+================================+=======+ |
| | ``%a`` | Locale's abbreviated weekday | | |
| | | name. | | |
| +-----------+--------------------------------+-------+ |
| | ``%A`` | Locale's full weekday name. | | |
| +-----------+--------------------------------+-------+ |
| | ``%b`` | Locale's abbreviated month | | |
| | | name. | | |
| +-----------+--------------------------------+-------+ |
| | ``%B`` | Locale's full month name. | | |
| +-----------+--------------------------------+-------+ |
| | ``%c`` | Locale's appropriate date and | | |
| | | time representation. | | |
| +-----------+--------------------------------+-------+ |
| | ``%d`` | Day of the month as a decimal | | |
| | | number [01,31]. | | |
| +-----------+--------------------------------+-------+ |
| | ``%f`` | Microsecond as a decimal | \(1) | |
| | | number [0,999999], zero-padded | | |
| | | on the left | | |
| +-----------+--------------------------------+-------+ |
| | ``%H`` | Hour (24-hour clock) as a | | |
| | | decimal number [00,23]. | | |
| +-----------+--------------------------------+-------+ |
| | ``%I`` | Hour (12-hour clock) as a | | |
| | | decimal number [01,12]. | | |
| +-----------+--------------------------------+-------+ |
| | ``%j`` | Day of the year as a decimal | | |
| | | number [001,366]. | | |
| +-----------+--------------------------------+-------+ |
| | ``%m`` | Month as a decimal number | | |
| | | [01,12]. | | |
| +-----------+--------------------------------+-------+ |
| | ``%M`` | Minute as a decimal number | | |
| | | [00,59]. | | |
| +-----------+--------------------------------+-------+ |
| | ``%p`` | Locale's equivalent of either | \(2) | |
| | | AM or PM. | | |
| +-----------+--------------------------------+-------+ |
| | ``%S`` | Second as a decimal number | \(3) | |
| | | [00,61]. | | |
| +-----------+--------------------------------+-------+ |
| | ``%U`` | Week number of the year | \(4) | |
| | | (Sunday as the first day of | | |
| | | the week) as a decimal number | | |
| | | [00,53]. All days in a new | | |
| | | year preceding the first | | |
| | | Sunday are considered to be in | | |
| | | week 0. | | |
| +-----------+--------------------------------+-------+ |
| | ``%w`` | Weekday as a decimal number | | |
| | | [0(Sunday),6]. | | |
| +-----------+--------------------------------+-------+ |
| | ``%W`` | Week number of the year | \(4) | |
| | | (Monday as the first day of | | |
| | | the week) as a decimal number | | |
| | | [00,53]. All days in a new | | |
| | | year preceding the first | | |
| | | Monday are considered to be in | | |
| | | week 0. | | |
| +-----------+--------------------------------+-------+ |
| | ``%x`` | Locale's appropriate date | | |
| | | representation. | | |
| +-----------+--------------------------------+-------+ |
| | ``%X`` | Locale's appropriate time | | |
| | | representation. | | |
| +-----------+--------------------------------+-------+ |
| | ``%y`` | Year without century as a | | |
| | | decimal number [00,99]. | | |
| +-----------+--------------------------------+-------+ |
| | ``%Y`` | Year with century as a decimal | | |
| | | number. | | |
| +-----------+--------------------------------+-------+ |
| | ``%z`` | UTC offset in the form +HHMM | \(5) | |
| | | or -HHMM (empty string if the | | |
| | | the object is naive). | | |
| +-----------+--------------------------------+-------+ |
| | ``%Z`` | Time zone name (empty string | | |
| | | if the object is naive). | | |
| +-----------+--------------------------------+-------+ |
| | ``%%`` | A literal ``'%'`` character. | | |
| +-----------+--------------------------------+-------+ |
| |
n | Examples |
n | Notes: |
| -------- |
| |
n | (1) |
| When used with the :func:`strptime` function, the ``%f`` directive |
| accepts from one to six digits and zero pads on the right. ``%f`` is |
| an extension to the set of format characters in the C standard (but |
| implemented separately in datetime objects, and therefore always |
| available). |
| |
n | Creating Datetime Objects from Formatted Strings |
n | (2) |
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| When used with the :func:`strptime` function, the ``%p`` directive only affects |
| the output hour field if the ``%I`` directive is used to parse the hour. |
| |
n | The :class:`datetime` class does not directly support parsing formatted time |
n | (3) |
| strings. You can use :func:`time.strptime` to do the parsing and create a |
| The range really is ``0`` to ``61``; according to the Posix standard this |
| :class:`datetime` object from the tuple it returns:: |
| 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 :func:`strptime` input nor will it |
| produce them in :func:`strftime` output. |
| |
n | >>> s = "2005-12-06T12:13:14" |
n | (4) |
| >>> from datetime import datetime |
| When used with the :func:`strptime` function, ``%U`` and ``%W`` are only used in |
| >>> from time import strptime |
| calculations when the day of the week and the year are specified. |
| >>> datetime(*strptime(s, "%Y-%m-%dT%H:%M:%S")[0:6]) |
| datetime.datetime(2005, 12, 6, 12, 13, 14) |
| |
t | (5) |
| For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, |
| ``%z`` is replaced with the string ``'-0330'``. |