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