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