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