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