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