Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1 | :mod:`datetime` --- Basic date and time types |
| 2 | ============================================= |
| 3 | |
| 4 | .. module:: datetime |
| 5 | :synopsis: Basic date and time types. |
| 6 | .. moduleauthor:: Tim Peters <tim@zope.com> |
| 7 | .. sectionauthor:: Tim Peters <tim@zope.com> |
| 8 | .. sectionauthor:: A.M. Kuchling <amk@amk.ca> |
| 9 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 10 | .. XXX what order should the types be discussed in? |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 11 | |
| 12 | .. versionadded:: 2.3 |
| 13 | |
| 14 | The :mod:`datetime` module supplies classes for manipulating dates and times in |
| 15 | both simple and complex ways. While date and time arithmetic is supported, the |
| 16 | focus of the implementation is on efficient member extraction for output |
| 17 | formatting and manipulation. For related |
| 18 | functionality, see also the :mod:`time` and :mod:`calendar` modules. |
| 19 | |
| 20 | There are two kinds of date and time objects: "naive" and "aware". This |
| 21 | distinction refers to whether the object has any notion of time zone, daylight |
| 22 | saving time, or other kind of algorithmic or political time adjustment. Whether |
| 23 | a naive :class:`datetime` object represents Coordinated Universal Time (UTC), |
| 24 | local time, or time in some other timezone is purely up to the program, just |
| 25 | like it's up to the program whether a particular number represents metres, |
| 26 | miles, or mass. Naive :class:`datetime` objects are easy to understand and to |
| 27 | work with, at the cost of ignoring some aspects of reality. |
| 28 | |
| 29 | For applications requiring more, :class:`datetime` and :class:`time` objects |
| 30 | have an optional time zone information member, :attr:`tzinfo`, that can contain |
| 31 | an instance of a subclass of the abstract :class:`tzinfo` class. These |
| 32 | :class:`tzinfo` objects capture information about the offset from UTC time, the |
| 33 | time zone name, and whether Daylight Saving Time is in effect. Note that no |
| 34 | concrete :class:`tzinfo` classes are supplied by the :mod:`datetime` module. |
| 35 | Supporting timezones at whatever level of detail is required is up to the |
| 36 | application. The rules for time adjustment across the world are more political |
| 37 | than rational, and there is no standard suitable for every application. |
| 38 | |
| 39 | The :mod:`datetime` module exports the following constants: |
| 40 | |
| 41 | |
| 42 | .. data:: MINYEAR |
| 43 | |
| 44 | The smallest year number allowed in a :class:`date` or :class:`datetime` object. |
| 45 | :const:`MINYEAR` is ``1``. |
| 46 | |
| 47 | |
| 48 | .. data:: MAXYEAR |
| 49 | |
| 50 | The largest year number allowed in a :class:`date` or :class:`datetime` object. |
| 51 | :const:`MAXYEAR` is ``9999``. |
| 52 | |
| 53 | |
| 54 | .. seealso:: |
| 55 | |
| 56 | Module :mod:`calendar` |
| 57 | General calendar related functions. |
| 58 | |
| 59 | Module :mod:`time` |
| 60 | Time access and conversions. |
| 61 | |
| 62 | |
| 63 | Available Types |
| 64 | --------------- |
| 65 | |
| 66 | |
| 67 | .. class:: date |
Georg Brandl | 592c58d | 2009-09-19 10:42:34 +0000 | [diff] [blame^] | 68 | :noindex: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 69 | |
| 70 | An idealized naive date, assuming the current Gregorian calendar always was, and |
| 71 | always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and |
| 72 | :attr:`day`. |
| 73 | |
| 74 | |
| 75 | .. class:: time |
Georg Brandl | 592c58d | 2009-09-19 10:42:34 +0000 | [diff] [blame^] | 76 | :noindex: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 77 | |
| 78 | An idealized time, independent of any particular day, assuming that every day |
| 79 | has exactly 24\*60\*60 seconds (there is no notion of "leap seconds" here). |
| 80 | Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`, |
| 81 | and :attr:`tzinfo`. |
| 82 | |
| 83 | |
| 84 | .. class:: datetime |
Georg Brandl | 592c58d | 2009-09-19 10:42:34 +0000 | [diff] [blame^] | 85 | :noindex: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 86 | |
| 87 | A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`, |
| 88 | :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`, |
| 89 | and :attr:`tzinfo`. |
| 90 | |
| 91 | |
| 92 | .. class:: timedelta |
Georg Brandl | 592c58d | 2009-09-19 10:42:34 +0000 | [diff] [blame^] | 93 | :noindex: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 94 | |
| 95 | A duration expressing the difference between two :class:`date`, :class:`time`, |
| 96 | or :class:`datetime` instances to microsecond resolution. |
| 97 | |
| 98 | |
| 99 | .. class:: tzinfo |
| 100 | |
| 101 | An abstract base class for time zone information objects. These are used by the |
| 102 | :class:`datetime` and :class:`time` classes to provide a customizable notion of |
| 103 | time adjustment (for example, to account for time zone and/or daylight saving |
| 104 | time). |
| 105 | |
| 106 | Objects of these types are immutable. |
| 107 | |
| 108 | Objects of the :class:`date` type are always naive. |
| 109 | |
| 110 | An object *d* of type :class:`time` or :class:`datetime` may be naive or aware. |
| 111 | *d* is aware if ``d.tzinfo`` is not ``None`` and ``d.tzinfo.utcoffset(d)`` does |
| 112 | not return ``None``. If ``d.tzinfo`` is ``None``, or if ``d.tzinfo`` is not |
| 113 | ``None`` but ``d.tzinfo.utcoffset(d)`` returns ``None``, *d* is naive. |
| 114 | |
| 115 | The distinction between naive and aware doesn't apply to :class:`timedelta` |
| 116 | objects. |
| 117 | |
| 118 | Subclass relationships:: |
| 119 | |
| 120 | object |
| 121 | timedelta |
| 122 | tzinfo |
| 123 | time |
| 124 | date |
| 125 | datetime |
| 126 | |
| 127 | |
| 128 | .. _datetime-timedelta: |
| 129 | |
| 130 | :class:`timedelta` Objects |
| 131 | -------------------------- |
| 132 | |
| 133 | A :class:`timedelta` object represents a duration, the difference between two |
| 134 | dates or times. |
| 135 | |
| 136 | |
| 137 | .. class:: timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]) |
| 138 | |
| 139 | All arguments are optional and default to ``0``. Arguments may be ints, longs, |
| 140 | or floats, and may be positive or negative. |
| 141 | |
| 142 | Only *days*, *seconds* and *microseconds* are stored internally. Arguments are |
| 143 | converted to those units: |
| 144 | |
| 145 | * A millisecond is converted to 1000 microseconds. |
| 146 | * A minute is converted to 60 seconds. |
| 147 | * An hour is converted to 3600 seconds. |
| 148 | * A week is converted to 7 days. |
| 149 | |
| 150 | and days, seconds and microseconds are then normalized so that the |
| 151 | representation is unique, with |
| 152 | |
| 153 | * ``0 <= microseconds < 1000000`` |
| 154 | * ``0 <= seconds < 3600*24`` (the number of seconds in one day) |
| 155 | * ``-999999999 <= days <= 999999999`` |
| 156 | |
| 157 | If any argument is a float and there are fractional microseconds, the fractional |
| 158 | microseconds left over from all arguments are combined and their sum is rounded |
| 159 | to the nearest microsecond. If no argument is a float, the conversion and |
| 160 | normalization processes are exact (no information is lost). |
| 161 | |
| 162 | If the normalized value of days lies outside the indicated range, |
| 163 | :exc:`OverflowError` is raised. |
| 164 | |
| 165 | Note that normalization of negative values may be surprising at first. For |
Georg Brandl | 3f04303 | 2008-03-22 21:21:57 +0000 | [diff] [blame] | 166 | example, |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 167 | |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 168 | >>> from datetime import timedelta |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 169 | >>> d = timedelta(microseconds=-1) |
| 170 | >>> (d.days, d.seconds, d.microseconds) |
| 171 | (-1, 86399, 999999) |
| 172 | |
| 173 | Class attributes are: |
| 174 | |
| 175 | |
| 176 | .. attribute:: timedelta.min |
| 177 | |
| 178 | The most negative :class:`timedelta` object, ``timedelta(-999999999)``. |
| 179 | |
| 180 | |
| 181 | .. attribute:: timedelta.max |
| 182 | |
| 183 | The most positive :class:`timedelta` object, ``timedelta(days=999999999, |
| 184 | hours=23, minutes=59, seconds=59, microseconds=999999)``. |
| 185 | |
| 186 | |
| 187 | .. attribute:: timedelta.resolution |
| 188 | |
| 189 | The smallest possible difference between non-equal :class:`timedelta` objects, |
| 190 | ``timedelta(microseconds=1)``. |
| 191 | |
| 192 | Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``. |
| 193 | ``-timedelta.max`` is not representable as a :class:`timedelta` object. |
| 194 | |
| 195 | Instance attributes (read-only): |
| 196 | |
| 197 | +------------------+--------------------------------------------+ |
| 198 | | Attribute | Value | |
| 199 | +==================+============================================+ |
| 200 | | ``days`` | Between -999999999 and 999999999 inclusive | |
| 201 | +------------------+--------------------------------------------+ |
| 202 | | ``seconds`` | Between 0 and 86399 inclusive | |
| 203 | +------------------+--------------------------------------------+ |
| 204 | | ``microseconds`` | Between 0 and 999999 inclusive | |
| 205 | +------------------+--------------------------------------------+ |
| 206 | |
| 207 | Supported operations: |
| 208 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 209 | .. XXX this table is too wide! |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 210 | |
| 211 | +--------------------------------+-----------------------------------------------+ |
| 212 | | Operation | Result | |
| 213 | +================================+===============================================+ |
| 214 | | ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == | |
| 215 | | | *t3* and *t1*-*t3* == *t2* are true. (1) | |
| 216 | +--------------------------------+-----------------------------------------------+ |
| 217 | | ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* | |
| 218 | | | == *t2* - *t3* and *t2* == *t1* + *t3* are | |
| 219 | | | true. (1) | |
| 220 | +--------------------------------+-----------------------------------------------+ |
| 221 | | ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer or long. | |
| 222 | | | Afterwards *t1* // i == *t2* is true, | |
| 223 | | | provided ``i != 0``. | |
| 224 | +--------------------------------+-----------------------------------------------+ |
| 225 | | | In general, *t1* \* i == *t1* \* (i-1) + *t1* | |
| 226 | | | is true. (1) | |
| 227 | +--------------------------------+-----------------------------------------------+ |
| 228 | | ``t1 = t2 // i`` | The floor is computed and the remainder (if | |
| 229 | | | any) is thrown away. (3) | |
| 230 | +--------------------------------+-----------------------------------------------+ |
| 231 | | ``+t1`` | Returns a :class:`timedelta` object with the | |
| 232 | | | same value. (2) | |
| 233 | +--------------------------------+-----------------------------------------------+ |
| 234 | | ``-t1`` | equivalent to :class:`timedelta`\ | |
| 235 | | | (-*t1.days*, -*t1.seconds*, | |
| 236 | | | -*t1.microseconds*), and to *t1*\* -1. (1)(4) | |
| 237 | +--------------------------------+-----------------------------------------------+ |
| 238 | | ``abs(t)`` | equivalent to +*t* when ``t.days >= 0``, and | |
| 239 | | | to -*t* when ``t.days < 0``. (2) | |
| 240 | +--------------------------------+-----------------------------------------------+ |
| 241 | |
| 242 | Notes: |
| 243 | |
| 244 | (1) |
| 245 | This is exact, but may overflow. |
| 246 | |
| 247 | (2) |
| 248 | This is exact, and cannot overflow. |
| 249 | |
| 250 | (3) |
| 251 | Division by 0 raises :exc:`ZeroDivisionError`. |
| 252 | |
| 253 | (4) |
| 254 | -*timedelta.max* is not representable as a :class:`timedelta` object. |
| 255 | |
| 256 | In addition to the operations listed above :class:`timedelta` objects support |
| 257 | certain additions and subtractions with :class:`date` and :class:`datetime` |
| 258 | objects (see below). |
| 259 | |
| 260 | Comparisons of :class:`timedelta` objects are supported with the |
| 261 | :class:`timedelta` object representing the smaller duration considered to be the |
| 262 | smaller timedelta. In order to stop mixed-type comparisons from falling back to |
| 263 | the default comparison by object address, when a :class:`timedelta` object is |
| 264 | compared to an object of a different type, :exc:`TypeError` is raised unless the |
| 265 | comparison is ``==`` or ``!=``. The latter cases return :const:`False` or |
| 266 | :const:`True`, respectively. |
| 267 | |
Georg Brandl | 7c3e79f | 2007-11-02 20:06:17 +0000 | [diff] [blame] | 268 | :class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 269 | efficient pickling, and in Boolean contexts, a :class:`timedelta` object is |
| 270 | considered to be true if and only if it isn't equal to ``timedelta(0)``. |
| 271 | |
Georg Brandl | 3f04303 | 2008-03-22 21:21:57 +0000 | [diff] [blame] | 272 | Example usage: |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 273 | |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 274 | >>> from datetime import timedelta |
| 275 | >>> year = timedelta(days=365) |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 276 | >>> another_year = timedelta(weeks=40, days=84, hours=23, |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 277 | ... minutes=50, seconds=600) # adds up to 365 days |
| 278 | >>> year == another_year |
| 279 | True |
| 280 | >>> ten_years = 10 * year |
| 281 | >>> ten_years, ten_years.days // 365 |
| 282 | (datetime.timedelta(3650), 10) |
| 283 | >>> nine_years = ten_years - year |
| 284 | >>> nine_years, nine_years.days // 365 |
| 285 | (datetime.timedelta(3285), 9) |
| 286 | >>> three_years = nine_years // 3; |
| 287 | >>> three_years, three_years.days // 365 |
| 288 | (datetime.timedelta(1095), 3) |
| 289 | >>> abs(three_years - ten_years) == 2 * three_years + year |
| 290 | True |
| 291 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 292 | |
| 293 | .. _datetime-date: |
| 294 | |
| 295 | :class:`date` Objects |
| 296 | --------------------- |
| 297 | |
| 298 | A :class:`date` object represents a date (year, month and day) in an idealized |
| 299 | calendar, the current Gregorian calendar indefinitely extended in both |
| 300 | directions. January 1 of year 1 is called day number 1, January 2 of year 1 is |
| 301 | called day number 2, and so on. This matches the definition of the "proleptic |
| 302 | Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations, |
| 303 | where it's the base calendar for all computations. See the book for algorithms |
| 304 | for converting between proleptic Gregorian ordinals and many other calendar |
| 305 | systems. |
| 306 | |
| 307 | |
| 308 | .. class:: date(year, month, day) |
| 309 | |
| 310 | All arguments are required. Arguments may be ints or longs, in the following |
| 311 | ranges: |
| 312 | |
| 313 | * ``MINYEAR <= year <= MAXYEAR`` |
| 314 | * ``1 <= month <= 12`` |
| 315 | * ``1 <= day <= number of days in the given month and year`` |
| 316 | |
| 317 | If an argument outside those ranges is given, :exc:`ValueError` is raised. |
| 318 | |
| 319 | Other constructors, all class methods: |
| 320 | |
| 321 | |
| 322 | .. method:: date.today() |
| 323 | |
| 324 | Return the current local date. This is equivalent to |
| 325 | ``date.fromtimestamp(time.time())``. |
| 326 | |
| 327 | |
| 328 | .. method:: date.fromtimestamp(timestamp) |
| 329 | |
| 330 | Return the local date corresponding to the POSIX timestamp, such as is returned |
| 331 | by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out |
| 332 | of the range of values supported by the platform C :cfunc:`localtime` function. |
| 333 | It's common for this to be restricted to years from 1970 through 2038. Note |
| 334 | that on non-POSIX systems that include leap seconds in their notion of a |
| 335 | timestamp, leap seconds are ignored by :meth:`fromtimestamp`. |
| 336 | |
| 337 | |
| 338 | .. method:: date.fromordinal(ordinal) |
| 339 | |
| 340 | Return the date corresponding to the proleptic Gregorian ordinal, where January |
| 341 | 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <= |
| 342 | date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) == |
| 343 | d``. |
| 344 | |
| 345 | Class attributes: |
| 346 | |
| 347 | |
| 348 | .. attribute:: date.min |
| 349 | |
| 350 | The earliest representable date, ``date(MINYEAR, 1, 1)``. |
| 351 | |
| 352 | |
| 353 | .. attribute:: date.max |
| 354 | |
| 355 | The latest representable date, ``date(MAXYEAR, 12, 31)``. |
| 356 | |
| 357 | |
| 358 | .. attribute:: date.resolution |
| 359 | |
| 360 | The smallest possible difference between non-equal date objects, |
| 361 | ``timedelta(days=1)``. |
| 362 | |
| 363 | Instance attributes (read-only): |
| 364 | |
| 365 | |
| 366 | .. attribute:: date.year |
| 367 | |
| 368 | Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive. |
| 369 | |
| 370 | |
| 371 | .. attribute:: date.month |
| 372 | |
| 373 | Between 1 and 12 inclusive. |
| 374 | |
| 375 | |
| 376 | .. attribute:: date.day |
| 377 | |
| 378 | Between 1 and the number of days in the given month of the given year. |
| 379 | |
| 380 | Supported operations: |
| 381 | |
| 382 | +-------------------------------+----------------------------------------------+ |
| 383 | | Operation | Result | |
| 384 | +===============================+==============================================+ |
| 385 | | ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed | |
| 386 | | | from *date1*. (1) | |
| 387 | +-------------------------------+----------------------------------------------+ |
| 388 | | ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + | |
| 389 | | | timedelta == date1``. (2) | |
| 390 | +-------------------------------+----------------------------------------------+ |
| 391 | | ``timedelta = date1 - date2`` | \(3) | |
| 392 | +-------------------------------+----------------------------------------------+ |
| 393 | | ``date1 < date2`` | *date1* is considered less than *date2* when | |
| 394 | | | *date1* precedes *date2* in time. (4) | |
| 395 | +-------------------------------+----------------------------------------------+ |
| 396 | |
| 397 | Notes: |
| 398 | |
| 399 | (1) |
| 400 | *date2* is moved forward in time if ``timedelta.days > 0``, or backward if |
| 401 | ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``. |
| 402 | ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored. |
| 403 | :exc:`OverflowError` is raised if ``date2.year`` would be smaller than |
| 404 | :const:`MINYEAR` or larger than :const:`MAXYEAR`. |
| 405 | |
| 406 | (2) |
| 407 | This isn't quite equivalent to date1 + (-timedelta), because -timedelta in |
| 408 | isolation can overflow in cases where date1 - timedelta does not. |
| 409 | ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored. |
| 410 | |
| 411 | (3) |
| 412 | This is exact, and cannot overflow. timedelta.seconds and |
| 413 | timedelta.microseconds are 0, and date2 + timedelta == date1 after. |
| 414 | |
| 415 | (4) |
| 416 | In other words, ``date1 < date2`` if and only if ``date1.toordinal() < |
| 417 | date2.toordinal()``. In order to stop comparison from falling back to the |
| 418 | default scheme of comparing object addresses, date comparison normally raises |
| 419 | :exc:`TypeError` if the other comparand isn't also a :class:`date` object. |
| 420 | However, ``NotImplemented`` is returned instead if the other comparand has a |
| 421 | :meth:`timetuple` attribute. This hook gives other kinds of date objects a |
| 422 | chance at implementing mixed-type comparison. If not, when a :class:`date` |
| 423 | object is compared to an object of a different type, :exc:`TypeError` is raised |
| 424 | unless the comparison is ``==`` or ``!=``. The latter cases return |
| 425 | :const:`False` or :const:`True`, respectively. |
| 426 | |
| 427 | Dates can be used as dictionary keys. In Boolean contexts, all :class:`date` |
| 428 | objects are considered to be true. |
| 429 | |
| 430 | Instance methods: |
| 431 | |
| 432 | |
| 433 | .. method:: date.replace(year, month, day) |
| 434 | |
| 435 | Return a date with the same value, except for those members given new values by |
| 436 | whichever keyword arguments are specified. For example, if ``d == date(2002, |
| 437 | 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``. |
| 438 | |
| 439 | |
| 440 | .. method:: date.timetuple() |
| 441 | |
| 442 | Return a :class:`time.struct_time` such as returned by :func:`time.localtime`. |
| 443 | The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()`` |
| 444 | is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0, |
| 445 | d.weekday(), d.toordinal() - date(d.year, 1, 1).toordinal() + 1, -1))`` |
| 446 | |
| 447 | |
| 448 | .. method:: date.toordinal() |
| 449 | |
| 450 | Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 |
| 451 | has ordinal 1. For any :class:`date` object *d*, |
| 452 | ``date.fromordinal(d.toordinal()) == d``. |
| 453 | |
| 454 | |
| 455 | .. method:: date.weekday() |
| 456 | |
| 457 | Return the day of the week as an integer, where Monday is 0 and Sunday is 6. |
| 458 | For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also |
| 459 | :meth:`isoweekday`. |
| 460 | |
| 461 | |
| 462 | .. method:: date.isoweekday() |
| 463 | |
| 464 | Return the day of the week as an integer, where Monday is 1 and Sunday is 7. |
| 465 | For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also |
| 466 | :meth:`weekday`, :meth:`isocalendar`. |
| 467 | |
| 468 | |
| 469 | .. method:: date.isocalendar() |
| 470 | |
| 471 | Return a 3-tuple, (ISO year, ISO week number, ISO weekday). |
| 472 | |
| 473 | The ISO calendar is a widely used variant of the Gregorian calendar. See |
| 474 | http://www.phys.uu.nl/ vgent/calendar/isocalendar.htm for a good explanation. |
| 475 | |
| 476 | The ISO year consists of 52 or 53 full weeks, and where a week starts on a |
| 477 | Monday and ends on a Sunday. The first week of an ISO year is the first |
| 478 | (Gregorian) calendar week of a year containing a Thursday. This is called week |
| 479 | number 1, and the ISO year of that Thursday is the same as its Gregorian year. |
| 480 | |
| 481 | For example, 2004 begins on a Thursday, so the first week of ISO year 2004 |
| 482 | begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that |
| 483 | ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1, |
| 484 | 4).isocalendar() == (2004, 1, 7)``. |
| 485 | |
| 486 | |
| 487 | .. method:: date.isoformat() |
| 488 | |
| 489 | Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For |
| 490 | example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``. |
| 491 | |
| 492 | |
| 493 | .. method:: date.__str__() |
| 494 | |
| 495 | For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``. |
| 496 | |
| 497 | |
| 498 | .. method:: date.ctime() |
| 499 | |
| 500 | Return a string representing the date, for example ``date(2002, 12, |
| 501 | 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to |
| 502 | ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C |
| 503 | :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which |
| 504 | :meth:`date.ctime` does not invoke) conforms to the C standard. |
| 505 | |
| 506 | |
| 507 | .. method:: date.strftime(format) |
| 508 | |
| 509 | Return a string representing the date, controlled by an explicit format string. |
| 510 | Format codes referring to hours, minutes or seconds will see 0 values. See |
| 511 | section :ref:`strftime-behavior`. |
| 512 | |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 513 | Example of counting days to an event:: |
| 514 | |
| 515 | >>> import time |
| 516 | >>> from datetime import date |
| 517 | >>> today = date.today() |
| 518 | >>> today |
| 519 | datetime.date(2007, 12, 5) |
| 520 | >>> today == date.fromtimestamp(time.time()) |
| 521 | True |
| 522 | >>> my_birthday = date(today.year, 6, 24) |
| 523 | >>> if my_birthday < today: |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 524 | ... my_birthday = my_birthday.replace(year=today.year + 1) |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 525 | >>> my_birthday |
| 526 | datetime.date(2008, 6, 24) |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 527 | >>> time_to_birthday = abs(my_birthday - today) |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 528 | >>> time_to_birthday.days |
| 529 | 202 |
| 530 | |
Georg Brandl | 3f04303 | 2008-03-22 21:21:57 +0000 | [diff] [blame] | 531 | Example of working with :class:`date`: |
| 532 | |
| 533 | .. doctest:: |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 534 | |
| 535 | >>> from datetime import date |
| 536 | >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001 |
| 537 | >>> d |
| 538 | datetime.date(2002, 3, 11) |
| 539 | >>> t = d.timetuple() |
Georg Brandl | 3f04303 | 2008-03-22 21:21:57 +0000 | [diff] [blame] | 540 | >>> for i in t: # doctest: +SKIP |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 541 | ... print i |
| 542 | 2002 # year |
| 543 | 3 # month |
| 544 | 11 # day |
| 545 | 0 |
| 546 | 0 |
| 547 | 0 |
| 548 | 0 # weekday (0 = Monday) |
| 549 | 70 # 70th day in the year |
| 550 | -1 |
| 551 | >>> ic = d.isocalendar() |
Georg Brandl | 3f04303 | 2008-03-22 21:21:57 +0000 | [diff] [blame] | 552 | >>> for i in ic: # doctest: +SKIP |
| 553 | ... print i |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 554 | 2002 # ISO year |
| 555 | 11 # ISO week number |
| 556 | 1 # ISO day number ( 1 = Monday ) |
| 557 | >>> d.isoformat() |
| 558 | '2002-03-11' |
| 559 | >>> d.strftime("%d/%m/%y") |
| 560 | '11/03/02' |
| 561 | >>> d.strftime("%A %d. %B %Y") |
| 562 | 'Monday 11. March 2002' |
| 563 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 564 | |
| 565 | .. _datetime-datetime: |
| 566 | |
| 567 | :class:`datetime` Objects |
| 568 | ------------------------- |
| 569 | |
| 570 | A :class:`datetime` object is a single object containing all the information |
| 571 | from a :class:`date` object and a :class:`time` object. Like a :class:`date` |
| 572 | object, :class:`datetime` assumes the current Gregorian calendar extended in |
| 573 | both directions; like a time object, :class:`datetime` assumes there are exactly |
| 574 | 3600\*24 seconds in every day. |
| 575 | |
| 576 | Constructor: |
| 577 | |
| 578 | |
| 579 | .. class:: datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]) |
| 580 | |
| 581 | The year, month and day arguments are required. *tzinfo* may be ``None``, or an |
| 582 | instance of a :class:`tzinfo` subclass. The remaining arguments may be ints or |
| 583 | longs, in the following ranges: |
| 584 | |
| 585 | * ``MINYEAR <= year <= MAXYEAR`` |
| 586 | * ``1 <= month <= 12`` |
| 587 | * ``1 <= day <= number of days in the given month and year`` |
| 588 | * ``0 <= hour < 24`` |
| 589 | * ``0 <= minute < 60`` |
| 590 | * ``0 <= second < 60`` |
| 591 | * ``0 <= microsecond < 1000000`` |
| 592 | |
| 593 | If an argument outside those ranges is given, :exc:`ValueError` is raised. |
| 594 | |
| 595 | Other constructors, all class methods: |
| 596 | |
| 597 | |
| 598 | .. method:: datetime.today() |
| 599 | |
| 600 | Return the current local datetime, with :attr:`tzinfo` ``None``. This is |
| 601 | equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`, |
| 602 | :meth:`fromtimestamp`. |
| 603 | |
| 604 | |
| 605 | .. method:: datetime.now([tz]) |
| 606 | |
| 607 | Return the current local date and time. If optional argument *tz* is ``None`` |
| 608 | or not specified, this is like :meth:`today`, but, if possible, supplies more |
| 609 | precision than can be gotten from going through a :func:`time.time` timestamp |
| 610 | (for example, this may be possible on platforms supplying the C |
| 611 | :cfunc:`gettimeofday` function). |
| 612 | |
| 613 | Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the |
| 614 | current date and time are converted to *tz*'s time zone. In this case the |
| 615 | result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``. |
| 616 | See also :meth:`today`, :meth:`utcnow`. |
| 617 | |
| 618 | |
| 619 | .. method:: datetime.utcnow() |
| 620 | |
| 621 | Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like |
| 622 | :meth:`now`, but returns the current UTC date and time, as a naive |
| 623 | :class:`datetime` object. See also :meth:`now`. |
| 624 | |
| 625 | |
| 626 | .. method:: datetime.fromtimestamp(timestamp[, tz]) |
| 627 | |
| 628 | Return the local date and time corresponding to the POSIX timestamp, such as is |
| 629 | returned by :func:`time.time`. If optional argument *tz* is ``None`` or not |
| 630 | specified, the timestamp is converted to the platform's local date and time, and |
| 631 | the returned :class:`datetime` object is naive. |
| 632 | |
| 633 | Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the |
| 634 | timestamp is converted to *tz*'s time zone. In this case the result is |
| 635 | equivalent to |
| 636 | ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``. |
| 637 | |
| 638 | :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of |
| 639 | the range of values supported by the platform C :cfunc:`localtime` or |
| 640 | :cfunc:`gmtime` functions. It's common for this to be restricted to years in |
| 641 | 1970 through 2038. Note that on non-POSIX systems that include leap seconds in |
| 642 | their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`, |
| 643 | and then it's possible to have two timestamps differing by a second that yield |
| 644 | identical :class:`datetime` objects. See also :meth:`utcfromtimestamp`. |
| 645 | |
| 646 | |
| 647 | .. method:: datetime.utcfromtimestamp(timestamp) |
| 648 | |
| 649 | Return the UTC :class:`datetime` corresponding to the POSIX timestamp, with |
| 650 | :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is |
| 651 | out of the range of values supported by the platform C :cfunc:`gmtime` function. |
| 652 | It's common for this to be restricted to years in 1970 through 2038. See also |
| 653 | :meth:`fromtimestamp`. |
| 654 | |
| 655 | |
| 656 | .. method:: datetime.fromordinal(ordinal) |
| 657 | |
| 658 | Return the :class:`datetime` corresponding to the proleptic Gregorian ordinal, |
| 659 | where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 |
| 660 | <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and |
| 661 | microsecond of the result are all 0, and :attr:`tzinfo` is ``None``. |
| 662 | |
| 663 | |
| 664 | .. method:: datetime.combine(date, time) |
| 665 | |
| 666 | Return a new :class:`datetime` object whose date members are equal to the given |
| 667 | :class:`date` object's, and whose time and :attr:`tzinfo` members are equal to |
| 668 | the given :class:`time` object's. For any :class:`datetime` object *d*, ``d == |
| 669 | datetime.combine(d.date(), d.timetz())``. If date is a :class:`datetime` |
| 670 | object, its time and :attr:`tzinfo` members are ignored. |
| 671 | |
| 672 | |
| 673 | .. method:: datetime.strptime(date_string, format) |
| 674 | |
| 675 | Return a :class:`datetime` corresponding to *date_string*, parsed according to |
| 676 | *format*. This is equivalent to ``datetime(*(time.strptime(date_string, |
| 677 | format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format |
| 678 | can't be parsed by :func:`time.strptime` or if it returns a value which isn't a |
| 679 | time tuple. |
| 680 | |
| 681 | .. versionadded:: 2.5 |
| 682 | |
| 683 | Class attributes: |
| 684 | |
| 685 | |
| 686 | .. attribute:: datetime.min |
| 687 | |
| 688 | The earliest representable :class:`datetime`, ``datetime(MINYEAR, 1, 1, |
| 689 | tzinfo=None)``. |
| 690 | |
| 691 | |
| 692 | .. attribute:: datetime.max |
| 693 | |
| 694 | The latest representable :class:`datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59, |
| 695 | 59, 999999, tzinfo=None)``. |
| 696 | |
| 697 | |
| 698 | .. attribute:: datetime.resolution |
| 699 | |
| 700 | The smallest possible difference between non-equal :class:`datetime` objects, |
| 701 | ``timedelta(microseconds=1)``. |
| 702 | |
| 703 | Instance attributes (read-only): |
| 704 | |
| 705 | |
| 706 | .. attribute:: datetime.year |
| 707 | |
| 708 | Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive. |
| 709 | |
| 710 | |
| 711 | .. attribute:: datetime.month |
| 712 | |
| 713 | Between 1 and 12 inclusive. |
| 714 | |
| 715 | |
| 716 | .. attribute:: datetime.day |
| 717 | |
| 718 | Between 1 and the number of days in the given month of the given year. |
| 719 | |
| 720 | |
| 721 | .. attribute:: datetime.hour |
| 722 | |
| 723 | In ``range(24)``. |
| 724 | |
| 725 | |
| 726 | .. attribute:: datetime.minute |
| 727 | |
| 728 | In ``range(60)``. |
| 729 | |
| 730 | |
| 731 | .. attribute:: datetime.second |
| 732 | |
| 733 | In ``range(60)``. |
| 734 | |
| 735 | |
| 736 | .. attribute:: datetime.microsecond |
| 737 | |
| 738 | In ``range(1000000)``. |
| 739 | |
| 740 | |
| 741 | .. attribute:: datetime.tzinfo |
| 742 | |
| 743 | The object passed as the *tzinfo* argument to the :class:`datetime` constructor, |
| 744 | or ``None`` if none was passed. |
| 745 | |
| 746 | Supported operations: |
| 747 | |
| 748 | +---------------------------------------+-------------------------------+ |
| 749 | | Operation | Result | |
| 750 | +=======================================+===============================+ |
| 751 | | ``datetime2 = datetime1 + timedelta`` | \(1) | |
| 752 | +---------------------------------------+-------------------------------+ |
| 753 | | ``datetime2 = datetime1 - timedelta`` | \(2) | |
| 754 | +---------------------------------------+-------------------------------+ |
| 755 | | ``timedelta = datetime1 - datetime2`` | \(3) | |
| 756 | +---------------------------------------+-------------------------------+ |
| 757 | | ``datetime1 < datetime2`` | Compares :class:`datetime` to | |
| 758 | | | :class:`datetime`. (4) | |
| 759 | +---------------------------------------+-------------------------------+ |
| 760 | |
| 761 | (1) |
| 762 | datetime2 is a duration of timedelta removed from datetime1, moving forward in |
| 763 | time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The |
| 764 | result has the same :attr:`tzinfo` member as the input datetime, and datetime2 - |
| 765 | datetime1 == timedelta after. :exc:`OverflowError` is raised if datetime2.year |
| 766 | would be smaller than :const:`MINYEAR` or larger than :const:`MAXYEAR`. Note |
| 767 | that no time zone adjustments are done even if the input is an aware object. |
| 768 | |
| 769 | (2) |
| 770 | Computes the datetime2 such that datetime2 + timedelta == datetime1. As for |
| 771 | addition, the result has the same :attr:`tzinfo` member as the input datetime, |
| 772 | and no time zone adjustments are done even if the input is aware. This isn't |
| 773 | quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation |
| 774 | can overflow in cases where datetime1 - timedelta does not. |
| 775 | |
| 776 | (3) |
| 777 | Subtraction of a :class:`datetime` from a :class:`datetime` is defined only if |
| 778 | both operands are naive, or if both are aware. If one is aware and the other is |
| 779 | naive, :exc:`TypeError` is raised. |
| 780 | |
| 781 | If both are naive, or both are aware and have the same :attr:`tzinfo` member, |
| 782 | the :attr:`tzinfo` members are ignored, and the result is a :class:`timedelta` |
| 783 | object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments |
| 784 | are done in this case. |
| 785 | |
| 786 | If both are aware and have different :attr:`tzinfo` members, ``a-b`` acts as if |
| 787 | *a* and *b* were first converted to naive UTC datetimes first. The result is |
| 788 | ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) - |
| 789 | b.utcoffset())`` except that the implementation never overflows. |
| 790 | |
| 791 | (4) |
| 792 | *datetime1* is considered less than *datetime2* when *datetime1* precedes |
| 793 | *datetime2* in time. |
| 794 | |
| 795 | If one comparand is naive and the other is aware, :exc:`TypeError` is raised. |
| 796 | If both comparands are aware, and have the same :attr:`tzinfo` member, the |
| 797 | common :attr:`tzinfo` member is ignored and the base datetimes are compared. If |
| 798 | both comparands are aware and have different :attr:`tzinfo` members, the |
| 799 | comparands are first adjusted by subtracting their UTC offsets (obtained from |
| 800 | ``self.utcoffset()``). |
| 801 | |
| 802 | .. note:: |
| 803 | |
| 804 | In order to stop comparison from falling back to the default scheme of comparing |
| 805 | object addresses, datetime comparison normally raises :exc:`TypeError` if the |
| 806 | other comparand isn't also a :class:`datetime` object. However, |
| 807 | ``NotImplemented`` is returned instead if the other comparand has a |
| 808 | :meth:`timetuple` attribute. This hook gives other kinds of date objects a |
| 809 | chance at implementing mixed-type comparison. If not, when a :class:`datetime` |
| 810 | object is compared to an object of a different type, :exc:`TypeError` is raised |
| 811 | unless the comparison is ``==`` or ``!=``. The latter cases return |
| 812 | :const:`False` or :const:`True`, respectively. |
| 813 | |
| 814 | :class:`datetime` objects can be used as dictionary keys. In Boolean contexts, |
| 815 | all :class:`datetime` objects are considered to be true. |
| 816 | |
| 817 | Instance methods: |
| 818 | |
| 819 | |
| 820 | .. method:: datetime.date() |
| 821 | |
| 822 | Return :class:`date` object with same year, month and day. |
| 823 | |
| 824 | |
| 825 | .. method:: datetime.time() |
| 826 | |
| 827 | Return :class:`time` object with same hour, minute, second and microsecond. |
| 828 | :attr:`tzinfo` is ``None``. See also method :meth:`timetz`. |
| 829 | |
| 830 | |
| 831 | .. method:: datetime.timetz() |
| 832 | |
| 833 | Return :class:`time` object with same hour, minute, second, microsecond, and |
| 834 | tzinfo members. See also method :meth:`time`. |
| 835 | |
| 836 | |
| 837 | .. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]]) |
| 838 | |
| 839 | Return a datetime with the same members, except for those members given new |
| 840 | values by whichever keyword arguments are specified. Note that ``tzinfo=None`` |
| 841 | can be specified to create a naive datetime from an aware datetime with no |
| 842 | conversion of date and time members. |
| 843 | |
| 844 | |
| 845 | .. method:: datetime.astimezone(tz) |
| 846 | |
| 847 | Return a :class:`datetime` object with new :attr:`tzinfo` member *tz*, adjusting |
| 848 | the date and time members so the result is the same UTC time as *self*, but in |
| 849 | *tz*'s local time. |
| 850 | |
| 851 | *tz* must be an instance of a :class:`tzinfo` subclass, and its |
| 852 | :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must |
| 853 | be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must |
| 854 | not return ``None``). |
| 855 | |
| 856 | If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no |
| 857 | adjustment of date or time members is performed. Else the result is local time |
| 858 | in time zone *tz*, representing the same UTC time as *self*: after ``astz = |
| 859 | dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have the same date |
| 860 | and time members as ``dt - dt.utcoffset()``. The discussion of class |
| 861 | :class:`tzinfo` explains the cases at Daylight Saving Time transition boundaries |
| 862 | where this cannot be achieved (an issue only if *tz* models both standard and |
| 863 | daylight time). |
| 864 | |
| 865 | If you merely want to attach a time zone object *tz* to a datetime *dt* without |
| 866 | adjustment of date and time members, use ``dt.replace(tzinfo=tz)``. If you |
| 867 | merely want to remove the time zone object from an aware datetime *dt* without |
| 868 | conversion of date and time members, use ``dt.replace(tzinfo=None)``. |
| 869 | |
| 870 | Note that the default :meth:`tzinfo.fromutc` method can be overridden in a |
| 871 | :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`. |
| 872 | Ignoring error cases, :meth:`astimezone` acts like:: |
| 873 | |
| 874 | def astimezone(self, tz): |
| 875 | if self.tzinfo is tz: |
| 876 | return self |
| 877 | # Convert self to UTC, and attach the new time zone object. |
| 878 | utc = (self - self.utcoffset()).replace(tzinfo=tz) |
| 879 | # Convert from UTC to tz's local time. |
| 880 | return tz.fromutc(utc) |
| 881 | |
| 882 | |
| 883 | .. method:: datetime.utcoffset() |
| 884 | |
| 885 | If :attr:`tzinfo` is ``None``, returns ``None``, else returns |
| 886 | ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't |
| 887 | return ``None``, or a :class:`timedelta` object representing a whole number of |
| 888 | minutes with magnitude less than one day. |
| 889 | |
| 890 | |
| 891 | .. method:: datetime.dst() |
| 892 | |
| 893 | If :attr:`tzinfo` is ``None``, returns ``None``, else returns |
| 894 | ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return |
| 895 | ``None``, or a :class:`timedelta` object representing a whole number of minutes |
| 896 | with magnitude less than one day. |
| 897 | |
| 898 | |
| 899 | .. method:: datetime.tzname() |
| 900 | |
| 901 | If :attr:`tzinfo` is ``None``, returns ``None``, else returns |
| 902 | ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return |
| 903 | ``None`` or a string object, |
| 904 | |
| 905 | |
| 906 | .. method:: datetime.timetuple() |
| 907 | |
| 908 | Return a :class:`time.struct_time` such as returned by :func:`time.localtime`. |
| 909 | ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day, |
| 910 | d.hour, d.minute, d.second, d.weekday(), d.toordinal() - date(d.year, 1, |
| 911 | 1).toordinal() + 1, dst))`` The :attr:`tm_isdst` flag of the result is set |
| 912 | according to the :meth:`dst` method: :attr:`tzinfo` is ``None`` or :meth:`dst` |
| 913 | returns ``None``, :attr:`tm_isdst` is set to ``-1``; else if :meth:`dst` |
| 914 | returns a non-zero value, :attr:`tm_isdst` is set to ``1``; else ``tm_isdst`` is |
| 915 | set to ``0``. |
| 916 | |
| 917 | |
| 918 | .. method:: datetime.utctimetuple() |
| 919 | |
| 920 | If :class:`datetime` instance *d* is naive, this is the same as |
| 921 | ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what |
| 922 | ``d.dst()`` returns. DST is never in effect for a UTC time. |
| 923 | |
| 924 | If *d* is aware, *d* is normalized to UTC time, by subtracting |
| 925 | ``d.utcoffset()``, and a :class:`time.struct_time` for the normalized time is |
| 926 | returned. :attr:`tm_isdst` is forced to 0. Note that the result's |
| 927 | :attr:`tm_year` member may be :const:`MINYEAR`\ -1 or :const:`MAXYEAR`\ +1, if |
| 928 | *d*.year was ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year |
| 929 | boundary. |
| 930 | |
| 931 | |
| 932 | .. method:: datetime.toordinal() |
| 933 | |
| 934 | Return the proleptic Gregorian ordinal of the date. The same as |
| 935 | ``self.date().toordinal()``. |
| 936 | |
| 937 | |
| 938 | .. method:: datetime.weekday() |
| 939 | |
| 940 | Return the day of the week as an integer, where Monday is 0 and Sunday is 6. |
| 941 | The same as ``self.date().weekday()``. See also :meth:`isoweekday`. |
| 942 | |
| 943 | |
| 944 | .. method:: datetime.isoweekday() |
| 945 | |
| 946 | Return the day of the week as an integer, where Monday is 1 and Sunday is 7. |
| 947 | The same as ``self.date().isoweekday()``. See also :meth:`weekday`, |
| 948 | :meth:`isocalendar`. |
| 949 | |
| 950 | |
| 951 | .. method:: datetime.isocalendar() |
| 952 | |
| 953 | Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as |
| 954 | ``self.date().isocalendar()``. |
| 955 | |
| 956 | |
| 957 | .. method:: datetime.isoformat([sep]) |
| 958 | |
| 959 | Return a string representing the date and time in ISO 8601 format, |
| 960 | YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0, |
| 961 | YYYY-MM-DDTHH:MM:SS |
| 962 | |
| 963 | If :meth:`utcoffset` does not return ``None``, a 6-character string is |
| 964 | appended, giving the UTC offset in (signed) hours and minutes: |
| 965 | YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0 |
| 966 | YYYY-MM-DDTHH:MM:SS+HH:MM |
| 967 | |
| 968 | The optional argument *sep* (default ``'T'``) is a one-character separator, |
Georg Brandl | 3f04303 | 2008-03-22 21:21:57 +0000 | [diff] [blame] | 969 | placed between the date and time portions of the result. For example, |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 970 | |
| 971 | >>> from datetime import tzinfo, timedelta, datetime |
| 972 | >>> class TZ(tzinfo): |
| 973 | ... def utcoffset(self, dt): return timedelta(minutes=-399) |
| 974 | ... |
| 975 | >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ') |
| 976 | '2002-12-25 00:00:00-06:39' |
| 977 | |
| 978 | |
| 979 | .. method:: datetime.__str__() |
| 980 | |
| 981 | For a :class:`datetime` instance *d*, ``str(d)`` is equivalent to |
| 982 | ``d.isoformat(' ')``. |
| 983 | |
| 984 | |
| 985 | .. method:: datetime.ctime() |
| 986 | |
| 987 | Return a string representing the date and time, for example ``datetime(2002, 12, |
| 988 | 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is |
| 989 | equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the |
| 990 | native C :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which |
| 991 | :meth:`datetime.ctime` does not invoke) conforms to the C standard. |
| 992 | |
| 993 | |
| 994 | .. method:: datetime.strftime(format) |
| 995 | |
| 996 | Return a string representing the date and time, controlled by an explicit format |
| 997 | string. See section :ref:`strftime-behavior`. |
| 998 | |
Georg Brandl | 3f04303 | 2008-03-22 21:21:57 +0000 | [diff] [blame] | 999 | Examples of working with datetime objects: |
| 1000 | |
| 1001 | .. doctest:: |
| 1002 | |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1003 | >>> from datetime import datetime, date, time |
| 1004 | >>> # Using datetime.combine() |
| 1005 | >>> d = date(2005, 7, 14) |
| 1006 | >>> t = time(12, 30) |
| 1007 | >>> datetime.combine(d, t) |
| 1008 | datetime.datetime(2005, 7, 14, 12, 30) |
| 1009 | >>> # Using datetime.now() or datetime.utcnow() |
Georg Brandl | 3f04303 | 2008-03-22 21:21:57 +0000 | [diff] [blame] | 1010 | >>> datetime.now() # doctest: +SKIP |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1011 | datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1 |
Georg Brandl | 3f04303 | 2008-03-22 21:21:57 +0000 | [diff] [blame] | 1012 | >>> datetime.utcnow() # doctest: +SKIP |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1013 | datetime.datetime(2007, 12, 6, 15, 29, 43, 79060) |
| 1014 | >>> # Using datetime.strptime() |
| 1015 | >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") |
| 1016 | >>> dt |
| 1017 | datetime.datetime(2006, 11, 21, 16, 30) |
| 1018 | >>> # Using datetime.timetuple() to get tuple of all attributes |
| 1019 | >>> tt = dt.timetuple() |
Georg Brandl | 3f04303 | 2008-03-22 21:21:57 +0000 | [diff] [blame] | 1020 | >>> for it in tt: # doctest: +SKIP |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1021 | ... print it |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1022 | ... |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1023 | 2006 # year |
| 1024 | 11 # month |
| 1025 | 21 # day |
| 1026 | 16 # hour |
| 1027 | 30 # minute |
| 1028 | 0 # second |
| 1029 | 1 # weekday (0 = Monday) |
| 1030 | 325 # number of days since 1st January |
| 1031 | -1 # dst - method tzinfo.dst() returned None |
| 1032 | >>> # Date in ISO format |
| 1033 | >>> ic = dt.isocalendar() |
Georg Brandl | 3f04303 | 2008-03-22 21:21:57 +0000 | [diff] [blame] | 1034 | >>> for it in ic: # doctest: +SKIP |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1035 | ... print it |
| 1036 | ... |
| 1037 | 2006 # ISO year |
| 1038 | 47 # ISO week |
| 1039 | 2 # ISO weekday |
| 1040 | >>> # Formatting datetime |
| 1041 | >>> dt.strftime("%A, %d. %B %Y %I:%M%p") |
| 1042 | 'Tuesday, 21. November 2006 04:30PM' |
| 1043 | |
Georg Brandl | 3f04303 | 2008-03-22 21:21:57 +0000 | [diff] [blame] | 1044 | Using datetime with tzinfo: |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1045 | |
| 1046 | >>> from datetime import timedelta, datetime, tzinfo |
| 1047 | >>> class GMT1(tzinfo): |
| 1048 | ... def __init__(self): # DST starts last Sunday in March |
| 1049 | ... d = datetime(dt.year, 4, 1) # ends last Sunday in October |
| 1050 | ... self.dston = d - timedelta(days=d.weekday() + 1) |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1051 | ... d = datetime(dt.year, 11, 1) |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1052 | ... self.dstoff = d - timedelta(days=d.weekday() + 1) |
| 1053 | ... def utcoffset(self, dt): |
| 1054 | ... return timedelta(hours=1) + self.dst(dt) |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1055 | ... def dst(self, dt): |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1056 | ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff: |
| 1057 | ... return timedelta(hours=1) |
| 1058 | ... else: |
| 1059 | ... return timedelta(0) |
| 1060 | ... def tzname(self,dt): |
| 1061 | ... return "GMT +1" |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1062 | ... |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1063 | >>> class GMT2(tzinfo): |
| 1064 | ... def __init__(self): |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1065 | ... d = datetime(dt.year, 4, 1) |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1066 | ... self.dston = d - timedelta(days=d.weekday() + 1) |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1067 | ... d = datetime(dt.year, 11, 1) |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1068 | ... self.dstoff = d - timedelta(days=d.weekday() + 1) |
| 1069 | ... def utcoffset(self, dt): |
| 1070 | ... return timedelta(hours=1) + self.dst(dt) |
| 1071 | ... def dst(self, dt): |
| 1072 | ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff: |
| 1073 | ... return timedelta(hours=2) |
| 1074 | ... else: |
| 1075 | ... return timedelta(0) |
| 1076 | ... def tzname(self,dt): |
| 1077 | ... return "GMT +2" |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1078 | ... |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1079 | >>> gmt1 = GMT1() |
| 1080 | >>> # Daylight Saving Time |
| 1081 | >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1) |
| 1082 | >>> dt1.dst() |
| 1083 | datetime.timedelta(0) |
| 1084 | >>> dt1.utcoffset() |
| 1085 | datetime.timedelta(0, 3600) |
| 1086 | >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1) |
| 1087 | >>> dt2.dst() |
| 1088 | datetime.timedelta(0, 3600) |
| 1089 | >>> dt2.utcoffset() |
| 1090 | datetime.timedelta(0, 7200) |
| 1091 | >>> # Convert datetime to another time zone |
| 1092 | >>> dt3 = dt2.astimezone(GMT2()) |
| 1093 | >>> dt3 # doctest: +ELLIPSIS |
| 1094 | datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>) |
| 1095 | >>> dt2 # doctest: +ELLIPSIS |
| 1096 | datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>) |
| 1097 | >>> dt2.utctimetuple() == dt3.utctimetuple() |
| 1098 | True |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1099 | |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1100 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1101 | |
| 1102 | .. _datetime-time: |
| 1103 | |
| 1104 | :class:`time` Objects |
| 1105 | --------------------- |
| 1106 | |
| 1107 | A time object represents a (local) time of day, independent of any particular |
| 1108 | day, and subject to adjustment via a :class:`tzinfo` object. |
| 1109 | |
| 1110 | |
| 1111 | .. class:: time(hour[, minute[, second[, microsecond[, tzinfo]]]]) |
| 1112 | |
| 1113 | All arguments are optional. *tzinfo* may be ``None``, or an instance of a |
| 1114 | :class:`tzinfo` subclass. The remaining arguments may be ints or longs, in the |
| 1115 | following ranges: |
| 1116 | |
| 1117 | * ``0 <= hour < 24`` |
| 1118 | * ``0 <= minute < 60`` |
| 1119 | * ``0 <= second < 60`` |
| 1120 | * ``0 <= microsecond < 1000000``. |
| 1121 | |
| 1122 | If an argument outside those ranges is given, :exc:`ValueError` is raised. All |
| 1123 | default to ``0`` except *tzinfo*, which defaults to :const:`None`. |
| 1124 | |
| 1125 | Class attributes: |
| 1126 | |
| 1127 | |
| 1128 | .. attribute:: time.min |
| 1129 | |
| 1130 | The earliest representable :class:`time`, ``time(0, 0, 0, 0)``. |
| 1131 | |
| 1132 | |
| 1133 | .. attribute:: time.max |
| 1134 | |
| 1135 | The latest representable :class:`time`, ``time(23, 59, 59, 999999)``. |
| 1136 | |
| 1137 | |
| 1138 | .. attribute:: time.resolution |
| 1139 | |
| 1140 | The smallest possible difference between non-equal :class:`time` objects, |
| 1141 | ``timedelta(microseconds=1)``, although note that arithmetic on :class:`time` |
| 1142 | objects is not supported. |
| 1143 | |
| 1144 | Instance attributes (read-only): |
| 1145 | |
| 1146 | |
| 1147 | .. attribute:: time.hour |
| 1148 | |
| 1149 | In ``range(24)``. |
| 1150 | |
| 1151 | |
| 1152 | .. attribute:: time.minute |
| 1153 | |
| 1154 | In ``range(60)``. |
| 1155 | |
| 1156 | |
| 1157 | .. attribute:: time.second |
| 1158 | |
| 1159 | In ``range(60)``. |
| 1160 | |
| 1161 | |
| 1162 | .. attribute:: time.microsecond |
| 1163 | |
| 1164 | In ``range(1000000)``. |
| 1165 | |
| 1166 | |
| 1167 | .. attribute:: time.tzinfo |
| 1168 | |
| 1169 | The object passed as the tzinfo argument to the :class:`time` constructor, or |
| 1170 | ``None`` if none was passed. |
| 1171 | |
| 1172 | Supported operations: |
| 1173 | |
| 1174 | * comparison of :class:`time` to :class:`time`, where *a* is considered less |
| 1175 | than *b* when *a* precedes *b* in time. If one comparand is naive and the other |
| 1176 | is aware, :exc:`TypeError` is raised. If both comparands are aware, and have |
| 1177 | the same :attr:`tzinfo` member, the common :attr:`tzinfo` member is ignored and |
| 1178 | the base times are compared. If both comparands are aware and have different |
| 1179 | :attr:`tzinfo` members, the comparands are first adjusted by subtracting their |
| 1180 | UTC offsets (obtained from ``self.utcoffset()``). In order to stop mixed-type |
| 1181 | comparisons from falling back to the default comparison by object address, when |
| 1182 | a :class:`time` object is compared to an object of a different type, |
| 1183 | :exc:`TypeError` is raised unless the comparison is ``==`` or ``!=``. The |
| 1184 | latter cases return :const:`False` or :const:`True`, respectively. |
| 1185 | |
| 1186 | * hash, use as dict key |
| 1187 | |
| 1188 | * efficient pickling |
| 1189 | |
| 1190 | * in Boolean contexts, a :class:`time` object is considered to be true if and |
| 1191 | only if, after converting it to minutes and subtracting :meth:`utcoffset` (or |
| 1192 | ``0`` if that's ``None``), the result is non-zero. |
| 1193 | |
| 1194 | Instance methods: |
| 1195 | |
| 1196 | |
| 1197 | .. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]]) |
| 1198 | |
| 1199 | Return a :class:`time` with the same value, except for those members given new |
| 1200 | values by whichever keyword arguments are specified. Note that ``tzinfo=None`` |
| 1201 | can be specified to create a naive :class:`time` from an aware :class:`time`, |
| 1202 | without conversion of the time members. |
| 1203 | |
| 1204 | |
| 1205 | .. method:: time.isoformat() |
| 1206 | |
| 1207 | Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if |
| 1208 | self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a |
| 1209 | 6-character string is appended, giving the UTC offset in (signed) hours and |
| 1210 | minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM |
| 1211 | |
| 1212 | |
| 1213 | .. method:: time.__str__() |
| 1214 | |
| 1215 | For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``. |
| 1216 | |
| 1217 | |
| 1218 | .. method:: time.strftime(format) |
| 1219 | |
| 1220 | Return a string representing the time, controlled by an explicit format string. |
| 1221 | See section :ref:`strftime-behavior`. |
| 1222 | |
| 1223 | |
| 1224 | .. method:: time.utcoffset() |
| 1225 | |
| 1226 | If :attr:`tzinfo` is ``None``, returns ``None``, else returns |
| 1227 | ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't |
| 1228 | return ``None`` or a :class:`timedelta` object representing a whole number of |
| 1229 | minutes with magnitude less than one day. |
| 1230 | |
| 1231 | |
| 1232 | .. method:: time.dst() |
| 1233 | |
| 1234 | If :attr:`tzinfo` is ``None``, returns ``None``, else returns |
| 1235 | ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return |
| 1236 | ``None``, or a :class:`timedelta` object representing a whole number of minutes |
| 1237 | with magnitude less than one day. |
| 1238 | |
| 1239 | |
| 1240 | .. method:: time.tzname() |
| 1241 | |
| 1242 | If :attr:`tzinfo` is ``None``, returns ``None``, else returns |
| 1243 | ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't |
| 1244 | return ``None`` or a string object. |
| 1245 | |
Georg Brandl | 3f04303 | 2008-03-22 21:21:57 +0000 | [diff] [blame] | 1246 | Example: |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1247 | |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1248 | >>> from datetime import time, tzinfo |
| 1249 | >>> class GMT1(tzinfo): |
| 1250 | ... def utcoffset(self, dt): |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1251 | ... return timedelta(hours=1) |
| 1252 | ... def dst(self, dt): |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1253 | ... return timedelta(0) |
| 1254 | ... def tzname(self,dt): |
| 1255 | ... return "Europe/Prague" |
| 1256 | ... |
| 1257 | >>> t = time(12, 10, 30, tzinfo=GMT1()) |
| 1258 | >>> t # doctest: +ELLIPSIS |
| 1259 | datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>) |
| 1260 | >>> gmt = GMT1() |
| 1261 | >>> t.isoformat() |
| 1262 | '12:10:30+01:00' |
| 1263 | >>> t.dst() |
| 1264 | datetime.timedelta(0) |
| 1265 | >>> t.tzname() |
| 1266 | 'Europe/Prague' |
| 1267 | >>> t.strftime("%H:%M:%S %Z") |
| 1268 | '12:10:30 Europe/Prague' |
| 1269 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1270 | |
| 1271 | .. _datetime-tzinfo: |
| 1272 | |
| 1273 | :class:`tzinfo` Objects |
| 1274 | ----------------------- |
| 1275 | |
Brett Cannon | 8aa2c6c | 2009-01-29 00:54:32 +0000 | [diff] [blame] | 1276 | :class:`tzinfo` is an abstract base class, meaning that this class should not be |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1277 | instantiated directly. You need to derive a concrete subclass, and (at least) |
| 1278 | supply implementations of the standard :class:`tzinfo` methods needed by the |
| 1279 | :class:`datetime` methods you use. The :mod:`datetime` module does not supply |
| 1280 | any concrete subclasses of :class:`tzinfo`. |
| 1281 | |
| 1282 | An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the |
| 1283 | constructors for :class:`datetime` and :class:`time` objects. The latter objects |
| 1284 | view their members as being in local time, and the :class:`tzinfo` object |
| 1285 | supports methods revealing offset of local time from UTC, the name of the time |
| 1286 | zone, and DST offset, all relative to a date or time object passed to them. |
| 1287 | |
| 1288 | Special requirement for pickling: A :class:`tzinfo` subclass must have an |
| 1289 | :meth:`__init__` method that can be called with no arguments, else it can be |
| 1290 | pickled but possibly not unpickled again. This is a technical requirement that |
| 1291 | may be relaxed in the future. |
| 1292 | |
| 1293 | A concrete subclass of :class:`tzinfo` may need to implement the following |
| 1294 | methods. Exactly which methods are needed depends on the uses made of aware |
| 1295 | :mod:`datetime` objects. If in doubt, simply implement all of them. |
| 1296 | |
| 1297 | |
| 1298 | .. method:: tzinfo.utcoffset(self, dt) |
| 1299 | |
| 1300 | Return offset of local time from UTC, in minutes east of UTC. If local time is |
| 1301 | west of UTC, this should be negative. Note that this is intended to be the |
| 1302 | total offset from UTC; for example, if a :class:`tzinfo` object represents both |
| 1303 | time zone and DST adjustments, :meth:`utcoffset` should return their sum. If |
| 1304 | the UTC offset isn't known, return ``None``. Else the value returned must be a |
| 1305 | :class:`timedelta` object specifying a whole number of minutes in the range |
| 1306 | -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less |
| 1307 | than one day). Most implementations of :meth:`utcoffset` will probably look |
| 1308 | like one of these two:: |
| 1309 | |
| 1310 | return CONSTANT # fixed-offset class |
| 1311 | return CONSTANT + self.dst(dt) # daylight-aware class |
| 1312 | |
| 1313 | If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return |
| 1314 | ``None`` either. |
| 1315 | |
| 1316 | The default implementation of :meth:`utcoffset` raises |
| 1317 | :exc:`NotImplementedError`. |
| 1318 | |
| 1319 | |
| 1320 | .. method:: tzinfo.dst(self, dt) |
| 1321 | |
| 1322 | Return the daylight saving time (DST) adjustment, in minutes east of UTC, or |
| 1323 | ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not |
| 1324 | in effect. If DST is in effect, return the offset as a :class:`timedelta` object |
| 1325 | (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has |
| 1326 | already been added to the UTC offset returned by :meth:`utcoffset`, so there's |
| 1327 | no need to consult :meth:`dst` unless you're interested in obtaining DST info |
| 1328 | separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo` |
| 1329 | member's :meth:`dst` method to determine how the :attr:`tm_isdst` flag should be |
| 1330 | set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for DST changes |
| 1331 | when crossing time zones. |
| 1332 | |
| 1333 | An instance *tz* of a :class:`tzinfo` subclass that models both standard and |
| 1334 | daylight times must be consistent in this sense: |
| 1335 | |
| 1336 | ``tz.utcoffset(dt) - tz.dst(dt)`` |
| 1337 | |
| 1338 | must return the same result for every :class:`datetime` *dt* with ``dt.tzinfo == |
| 1339 | tz`` For sane :class:`tzinfo` subclasses, this expression yields the time |
| 1340 | zone's "standard offset", which should not depend on the date or the time, but |
| 1341 | only on geographic location. The implementation of :meth:`datetime.astimezone` |
| 1342 | relies on this, but cannot detect violations; it's the programmer's |
| 1343 | responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee |
| 1344 | this, it may be able to override the default implementation of |
| 1345 | :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless. |
| 1346 | |
| 1347 | Most implementations of :meth:`dst` will probably look like one of these two:: |
| 1348 | |
| 1349 | def dst(self): |
| 1350 | # a fixed-offset class: doesn't account for DST |
| 1351 | return timedelta(0) |
| 1352 | |
| 1353 | or :: |
| 1354 | |
| 1355 | def dst(self): |
| 1356 | # Code to set dston and dstoff to the time zone's DST |
| 1357 | # transition times based on the input dt.year, and expressed |
| 1358 | # in standard local time. Then |
| 1359 | |
| 1360 | if dston <= dt.replace(tzinfo=None) < dstoff: |
| 1361 | return timedelta(hours=1) |
| 1362 | else: |
| 1363 | return timedelta(0) |
| 1364 | |
| 1365 | The default implementation of :meth:`dst` raises :exc:`NotImplementedError`. |
| 1366 | |
| 1367 | |
| 1368 | .. method:: tzinfo.tzname(self, dt) |
| 1369 | |
| 1370 | Return the time zone name corresponding to the :class:`datetime` object *dt*, as |
| 1371 | a string. Nothing about string names is defined by the :mod:`datetime` module, |
| 1372 | and there's no requirement that it mean anything in particular. For example, |
| 1373 | "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all |
| 1374 | valid replies. Return ``None`` if a string name isn't known. Note that this is |
| 1375 | a method rather than a fixed string primarily because some :class:`tzinfo` |
| 1376 | subclasses will wish to return different names depending on the specific value |
| 1377 | of *dt* passed, especially if the :class:`tzinfo` class is accounting for |
| 1378 | daylight time. |
| 1379 | |
| 1380 | The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`. |
| 1381 | |
| 1382 | These methods are called by a :class:`datetime` or :class:`time` object, in |
| 1383 | response to their methods of the same names. A :class:`datetime` object passes |
| 1384 | itself as the argument, and a :class:`time` object passes ``None`` as the |
| 1385 | argument. A :class:`tzinfo` subclass's methods should therefore be prepared to |
| 1386 | accept a *dt* argument of ``None``, or of class :class:`datetime`. |
| 1387 | |
| 1388 | When ``None`` is passed, it's up to the class designer to decide the best |
| 1389 | response. For example, returning ``None`` is appropriate if the class wishes to |
| 1390 | say that time objects don't participate in the :class:`tzinfo` protocols. It |
| 1391 | may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as |
| 1392 | there is no other convention for discovering the standard offset. |
| 1393 | |
| 1394 | When a :class:`datetime` object is passed in response to a :class:`datetime` |
| 1395 | method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can |
| 1396 | rely on this, unless user code calls :class:`tzinfo` methods directly. The |
| 1397 | intent is that the :class:`tzinfo` methods interpret *dt* as being in local |
| 1398 | time, and not need worry about objects in other timezones. |
| 1399 | |
| 1400 | There is one more :class:`tzinfo` method that a subclass may wish to override: |
| 1401 | |
| 1402 | |
| 1403 | .. method:: tzinfo.fromutc(self, dt) |
| 1404 | |
| 1405 | This is called from the default :class:`datetime.astimezone()` implementation. |
| 1406 | When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members |
| 1407 | are to be viewed as expressing a UTC time. The purpose of :meth:`fromutc` is to |
| 1408 | adjust the date and time members, returning an equivalent datetime in *self*'s |
| 1409 | local time. |
| 1410 | |
| 1411 | Most :class:`tzinfo` subclasses should be able to inherit the default |
| 1412 | :meth:`fromutc` implementation without problems. It's strong enough to handle |
| 1413 | fixed-offset time zones, and time zones accounting for both standard and |
| 1414 | daylight time, and the latter even if the DST transition times differ in |
| 1415 | different years. An example of a time zone the default :meth:`fromutc` |
| 1416 | implementation may not handle correctly in all cases is one where the standard |
| 1417 | offset (from UTC) depends on the specific date and time passed, which can happen |
| 1418 | for political reasons. The default implementations of :meth:`astimezone` and |
| 1419 | :meth:`fromutc` may not produce the result you want if the result is one of the |
| 1420 | hours straddling the moment the standard offset changes. |
| 1421 | |
| 1422 | Skipping code for error cases, the default :meth:`fromutc` implementation acts |
| 1423 | like:: |
| 1424 | |
| 1425 | def fromutc(self, dt): |
| 1426 | # raise ValueError error if dt.tzinfo is not self |
| 1427 | dtoff = dt.utcoffset() |
| 1428 | dtdst = dt.dst() |
| 1429 | # raise ValueError if dtoff is None or dtdst is None |
| 1430 | delta = dtoff - dtdst # this is self's standard offset |
| 1431 | if delta: |
| 1432 | dt += delta # convert to standard local time |
| 1433 | dtdst = dt.dst() |
| 1434 | # raise ValueError if dtdst is None |
| 1435 | if dtdst: |
| 1436 | return dt + dtdst |
| 1437 | else: |
| 1438 | return dt |
| 1439 | |
| 1440 | Example :class:`tzinfo` classes: |
| 1441 | |
| 1442 | .. literalinclude:: ../includes/tzinfo-examples.py |
| 1443 | |
| 1444 | |
| 1445 | Note that there are unavoidable subtleties twice per year in a :class:`tzinfo` |
| 1446 | subclass accounting for both standard and daylight time, at the DST transition |
| 1447 | points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the |
| 1448 | minute after 1:59 (EST) on the first Sunday in April, and ends the minute after |
| 1449 | 1:59 (EDT) on the last Sunday in October:: |
| 1450 | |
| 1451 | UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM |
| 1452 | EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM |
| 1453 | EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM |
| 1454 | |
| 1455 | start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM |
| 1456 | |
| 1457 | end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM |
| 1458 | |
| 1459 | When DST starts (the "start" line), the local wall clock leaps from 1:59 to |
| 1460 | 3:00. A wall time of the form 2:MM doesn't really make sense on that day, so |
| 1461 | ``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST |
| 1462 | begins. In order for :meth:`astimezone` to make this guarantee, the |
| 1463 | :meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for |
| 1464 | Eastern) to be in daylight time. |
| 1465 | |
| 1466 | When DST ends (the "end" line), there's a potentially worse problem: there's an |
| 1467 | hour that can't be spelled unambiguously in local wall time: the last hour of |
| 1468 | daylight time. In Eastern, that's times of the form 5:MM UTC on the day |
| 1469 | daylight time ends. The local wall clock leaps from 1:59 (daylight time) back |
| 1470 | to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous. |
| 1471 | :meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC |
| 1472 | hours into the same local hour then. In the Eastern example, UTC times of the |
| 1473 | form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for |
| 1474 | :meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must |
| 1475 | consider times in the "repeated hour" to be in standard time. This is easily |
| 1476 | arranged, as in the example, by expressing DST switch times in the time zone's |
| 1477 | standard local time. |
| 1478 | |
| 1479 | Applications that can't bear such ambiguities should avoid using hybrid |
| 1480 | :class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any |
| 1481 | other fixed-offset :class:`tzinfo` subclass (such as a class representing only |
| 1482 | EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)). |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1483 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1484 | |
| 1485 | .. _strftime-behavior: |
| 1486 | |
| 1487 | :meth:`strftime` Behavior |
| 1488 | ------------------------- |
| 1489 | |
| 1490 | :class:`date`, :class:`datetime`, and :class:`time` objects all support a |
| 1491 | ``strftime(format)`` method, to create a string representing the time under the |
| 1492 | control of an explicit format string. Broadly speaking, ``d.strftime(fmt)`` |
| 1493 | acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())`` |
| 1494 | although not all objects support a :meth:`timetuple` method. |
| 1495 | |
| 1496 | For :class:`time` objects, the format codes for year, month, and day should not |
| 1497 | be used, as time objects have no such values. If they're used anyway, ``1900`` |
| 1498 | is substituted for the year, and ``0`` for the month and day. |
| 1499 | |
Skip Montanaro | fc070d2 | 2008-03-15 16:04:45 +0000 | [diff] [blame] | 1500 | For :class:`date` objects, the format codes for hours, minutes, seconds, and |
| 1501 | microseconds should not be used, as :class:`date` objects have no such |
| 1502 | values. If they're used anyway, ``0`` is substituted for them. |
| 1503 | |
Skip Montanaro | fc070d2 | 2008-03-15 16:04:45 +0000 | [diff] [blame] | 1504 | .. versionadded:: 2.6 |
Georg Brandl | af9a97b | 2009-01-18 14:41:52 +0000 | [diff] [blame] | 1505 | :class:`time` and :class:`datetime` objects support a ``%f`` format code |
| 1506 | which expands to the number of microseconds in the object, zero-padded on |
| 1507 | the left to six places. |
Skip Montanaro | fc070d2 | 2008-03-15 16:04:45 +0000 | [diff] [blame] | 1508 | |
| 1509 | For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty |
| 1510 | strings. |
| 1511 | |
| 1512 | For an aware object: |
| 1513 | |
| 1514 | ``%z`` |
| 1515 | :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or |
| 1516 | -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and |
| 1517 | MM is a 2-digit string giving the number of UTC offset minutes. For example, if |
| 1518 | :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is |
| 1519 | replaced with the string ``'-0330'``. |
| 1520 | |
| 1521 | ``%Z`` |
| 1522 | If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string. |
| 1523 | Otherwise ``%Z`` is replaced by the returned value, which must be a string. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1524 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1525 | The full set of format codes supported varies across platforms, because Python |
| 1526 | calls the platform C library's :func:`strftime` function, and platform |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1527 | variations are common. |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1528 | |
| 1529 | The following is a list of all the format codes that the C standard (1989 |
| 1530 | version) requires, and these work on all platforms with a standard C |
| 1531 | implementation. Note that the 1999 version of the C standard added additional |
| 1532 | format codes. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1533 | |
| 1534 | The exact range of years for which :meth:`strftime` works also varies across |
| 1535 | platforms. Regardless of platform, years before 1900 cannot be used. |
| 1536 | |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1537 | +-----------+--------------------------------+-------+ |
| 1538 | | Directive | Meaning | Notes | |
| 1539 | +===========+================================+=======+ |
| 1540 | | ``%a`` | Locale's abbreviated weekday | | |
| 1541 | | | name. | | |
| 1542 | +-----------+--------------------------------+-------+ |
| 1543 | | ``%A`` | Locale's full weekday name. | | |
| 1544 | +-----------+--------------------------------+-------+ |
| 1545 | | ``%b`` | Locale's abbreviated month | | |
| 1546 | | | name. | | |
| 1547 | +-----------+--------------------------------+-------+ |
| 1548 | | ``%B`` | Locale's full month name. | | |
| 1549 | +-----------+--------------------------------+-------+ |
| 1550 | | ``%c`` | Locale's appropriate date and | | |
| 1551 | | | time representation. | | |
| 1552 | +-----------+--------------------------------+-------+ |
| 1553 | | ``%d`` | Day of the month as a decimal | | |
| 1554 | | | number [01,31]. | | |
| 1555 | +-----------+--------------------------------+-------+ |
Skip Montanaro | fc070d2 | 2008-03-15 16:04:45 +0000 | [diff] [blame] | 1556 | | ``%f`` | Microsecond as a decimal | \(1) | |
| 1557 | | | number [0,999999], zero-padded | | |
| 1558 | | | on the left | | |
| 1559 | +-----------+--------------------------------+-------+ |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1560 | | ``%H`` | Hour (24-hour clock) as a | | |
| 1561 | | | decimal number [00,23]. | | |
| 1562 | +-----------+--------------------------------+-------+ |
| 1563 | | ``%I`` | Hour (12-hour clock) as a | | |
| 1564 | | | decimal number [01,12]. | | |
| 1565 | +-----------+--------------------------------+-------+ |
| 1566 | | ``%j`` | Day of the year as a decimal | | |
| 1567 | | | number [001,366]. | | |
| 1568 | +-----------+--------------------------------+-------+ |
| 1569 | | ``%m`` | Month as a decimal number | | |
| 1570 | | | [01,12]. | | |
| 1571 | +-----------+--------------------------------+-------+ |
| 1572 | | ``%M`` | Minute as a decimal number | | |
| 1573 | | | [00,59]. | | |
| 1574 | +-----------+--------------------------------+-------+ |
Skip Montanaro | fc070d2 | 2008-03-15 16:04:45 +0000 | [diff] [blame] | 1575 | | ``%p`` | Locale's equivalent of either | \(2) | |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1576 | | | AM or PM. | | |
| 1577 | +-----------+--------------------------------+-------+ |
Skip Montanaro | fc070d2 | 2008-03-15 16:04:45 +0000 | [diff] [blame] | 1578 | | ``%S`` | Second as a decimal number | \(3) | |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1579 | | | [00,61]. | | |
| 1580 | +-----------+--------------------------------+-------+ |
Skip Montanaro | fc070d2 | 2008-03-15 16:04:45 +0000 | [diff] [blame] | 1581 | | ``%U`` | Week number of the year | \(4) | |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1582 | | | (Sunday as the first day of | | |
| 1583 | | | the week) as a decimal number | | |
| 1584 | | | [00,53]. All days in a new | | |
| 1585 | | | year preceding the first | | |
| 1586 | | | Sunday are considered to be in | | |
| 1587 | | | week 0. | | |
| 1588 | +-----------+--------------------------------+-------+ |
| 1589 | | ``%w`` | Weekday as a decimal number | | |
| 1590 | | | [0(Sunday),6]. | | |
| 1591 | +-----------+--------------------------------+-------+ |
Skip Montanaro | fc070d2 | 2008-03-15 16:04:45 +0000 | [diff] [blame] | 1592 | | ``%W`` | Week number of the year | \(4) | |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1593 | | | (Monday as the first day of | | |
| 1594 | | | the week) as a decimal number | | |
| 1595 | | | [00,53]. All days in a new | | |
| 1596 | | | year preceding the first | | |
| 1597 | | | Monday are considered to be in | | |
| 1598 | | | week 0. | | |
| 1599 | +-----------+--------------------------------+-------+ |
| 1600 | | ``%x`` | Locale's appropriate date | | |
| 1601 | | | representation. | | |
| 1602 | +-----------+--------------------------------+-------+ |
| 1603 | | ``%X`` | Locale's appropriate time | | |
| 1604 | | | representation. | | |
| 1605 | +-----------+--------------------------------+-------+ |
| 1606 | | ``%y`` | Year without century as a | | |
| 1607 | | | decimal number [00,99]. | | |
| 1608 | +-----------+--------------------------------+-------+ |
| 1609 | | ``%Y`` | Year with century as a decimal | | |
| 1610 | | | number. | | |
| 1611 | +-----------+--------------------------------+-------+ |
Skip Montanaro | fc070d2 | 2008-03-15 16:04:45 +0000 | [diff] [blame] | 1612 | | ``%z`` | UTC offset in the form +HHMM | \(5) | |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1613 | | | or -HHMM (empty string if the | | |
| 1614 | | | the object is naive). | | |
| 1615 | +-----------+--------------------------------+-------+ |
| 1616 | | ``%Z`` | Time zone name (empty string | | |
| 1617 | | | if the object is naive). | | |
| 1618 | +-----------+--------------------------------+-------+ |
| 1619 | | ``%%`` | A literal ``'%'`` character. | | |
| 1620 | +-----------+--------------------------------+-------+ |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1621 | |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1622 | Notes: |
| 1623 | |
| 1624 | (1) |
Skip Montanaro | fc070d2 | 2008-03-15 16:04:45 +0000 | [diff] [blame] | 1625 | When used with the :func:`strptime` function, the ``%f`` directive |
| 1626 | accepts from one to six digits and zero pads on the right. ``%f`` is |
Georg Brandl | af9a97b | 2009-01-18 14:41:52 +0000 | [diff] [blame] | 1627 | an extension to the set of format characters in the C standard (but |
| 1628 | implemented separately in datetime objects, and therefore always |
| 1629 | available). |
Skip Montanaro | fc070d2 | 2008-03-15 16:04:45 +0000 | [diff] [blame] | 1630 | |
| 1631 | (2) |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1632 | When used with the :func:`strptime` function, the ``%p`` directive only affects |
| 1633 | the output hour field if the ``%I`` directive is used to parse the hour. |
| 1634 | |
Skip Montanaro | fc070d2 | 2008-03-15 16:04:45 +0000 | [diff] [blame] | 1635 | (3) |
R. David Murray | d56bab4 | 2009-04-02 04:34:04 +0000 | [diff] [blame] | 1636 | The range really is ``0`` to ``61``; according to the Posix standard this |
| 1637 | accounts for leap seconds and the (very rare) double leap seconds. |
| 1638 | The :mod:`time` module may produce and does accept leap seconds since |
| 1639 | it is based on the Posix standard, but the :mod:`datetime` module |
| 1640 | does not accept leap seconds in :func:`strptime` input nor will it |
| 1641 | produce them in :func:`strftime` output. |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1642 | |
Skip Montanaro | fc070d2 | 2008-03-15 16:04:45 +0000 | [diff] [blame] | 1643 | (4) |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1644 | When used with the :func:`strptime` function, ``%U`` and ``%W`` are only used in |
| 1645 | calculations when the day of the week and the year are specified. |
| 1646 | |
Skip Montanaro | fc070d2 | 2008-03-15 16:04:45 +0000 | [diff] [blame] | 1647 | (5) |
Georg Brandl | e40a6a8 | 2007-12-08 11:23:13 +0000 | [diff] [blame] | 1648 | For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, |
| 1649 | ``%z`` is replaced with the string ``'-0330'``. |