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