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