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