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