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