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