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