blob: 0cc36e9ffdb79dcb20e73e80b11c0eaefc7efa18 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001: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 Brandlb19be572007-12-29 10:57:00 +000010.. XXX what order should the types be discussed in?
Georg Brandl8ec7f652007-08-15 14:28:01 +000011
12.. versionadded:: 2.3
13
14The :mod:`datetime` module supplies classes for manipulating dates and times in
15both simple and complex ways. While date and time arithmetic is supported, the
Senthil Kumaran6f18b982011-07-04 12:50:02 -070016focus of the implementation is on efficient attribute extraction for output
R David Murray8349bc22012-05-14 22:33:36 -040017formatting and manipulation. For related functionality, see also the
18:mod:`time` and :mod:`calendar` modules.
Georg Brandl8ec7f652007-08-15 14:28:01 +000019
R David Murray089d4d42012-05-14 22:32:44 -040020There are two kinds of date and time objects: "naive" and "aware".
21
22An aware object has sufficient knowledge of applicable algorithmic and
23political time adjustments, such as time zone and daylight saving time
24information, to locate itself relative to other aware objects. An aware object
25is used to represent a specific moment in time that is not open to
26interpretation [#]_.
27
Georg Brandle565cf82012-08-21 19:44:00 +020028A naive object does not contain enough information to unambiguously locate
29itself relative to other date/time objects. Whether a naive object represents
R David Murray8349bc22012-05-14 22:33:36 -040030Coordinated Universal Time (UTC), local time, or time in some other timezone is
31purely up to the program, just like it's up to the program whether a particular
32number represents metres, miles, or mass. Naive objects are easy to understand
33and to work with, at the cost of ignoring some aspects of reality.
Georg Brandl8ec7f652007-08-15 14:28:01 +000034
R David Murray8349bc22012-05-14 22:33:36 -040035For applications requiring aware objects, :class:`.datetime` and :class:`.time`
36objects have an optional time zone information attribute, :attr:`tzinfo`, that
37can be set to an instance of a subclass of the abstract :class:`tzinfo` class.
38These :class:`tzinfo` objects capture information about the offset from UTC
39time, the time zone name, and whether Daylight Saving Time is in effect. Note
40that no concrete :class:`tzinfo` classes are supplied by the :mod:`datetime`
41module. Supporting timezones at whatever level of detail is required is up to
42the application. The rules for time adjustment across the world are more
43political than rational, and there is no standard suitable for every
44application.
Georg Brandl8ec7f652007-08-15 14:28:01 +000045
46The :mod:`datetime` module exports the following constants:
47
Georg Brandl8ec7f652007-08-15 14:28:01 +000048.. data:: MINYEAR
49
Sandro Tosi8d38fcf2012-02-18 20:28:35 +010050 The smallest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl8ec7f652007-08-15 14:28:01 +000051 :const:`MINYEAR` is ``1``.
52
53
54.. data:: MAXYEAR
55
Sandro Tosi8d38fcf2012-02-18 20:28:35 +010056 The largest year number allowed in a :class:`date` or :class:`.datetime` object.
Georg Brandl8ec7f652007-08-15 14:28:01 +000057 :const:`MAXYEAR` is ``9999``.
58
59
60.. seealso::
61
62 Module :mod:`calendar`
63 General calendar related functions.
64
65 Module :mod:`time`
66 Time access and conversions.
67
68
69Available Types
70---------------
71
Georg Brandl8ec7f652007-08-15 14:28:01 +000072.. class:: date
Georg Brandl592c58d2009-09-19 10:42:34 +000073 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +000074
75 An idealized naive date, assuming the current Gregorian calendar always was, and
76 always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and
77 :attr:`day`.
78
79
80.. class:: time
Georg Brandl592c58d2009-09-19 10:42:34 +000081 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +000082
83 An idealized time, independent of any particular day, assuming that every day
84 has exactly 24\*60\*60 seconds (there is no notion of "leap seconds" here).
85 Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
86 and :attr:`tzinfo`.
87
88
89.. class:: datetime
Georg Brandl592c58d2009-09-19 10:42:34 +000090 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +000091
92 A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`,
93 :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
94 and :attr:`tzinfo`.
95
96
97.. class:: timedelta
Georg Brandl592c58d2009-09-19 10:42:34 +000098 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +000099
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100100 A duration expressing the difference between two :class:`date`, :class:`.time`,
101 or :class:`.datetime` instances to microsecond resolution.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000102
103
104.. class:: tzinfo
105
106 An abstract base class for time zone information objects. These are used by the
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100107 :class:`.datetime` and :class:`.time` classes to provide a customizable notion of
Georg Brandl8ec7f652007-08-15 14:28:01 +0000108 time adjustment (for example, to account for time zone and/or daylight saving
109 time).
110
111Objects of these types are immutable.
112
113Objects of the :class:`date` type are always naive.
114
R David Murray089d4d42012-05-14 22:32:44 -0400115An object of type :class:`.time` or :class:`.datetime` may be naive or aware.
116A :class:`.datetime` object *d* is aware if ``d.tzinfo`` is not ``None`` and
117``d.tzinfo.utcoffset(d)`` does not return ``None``. If ``d.tzinfo`` is
118``None``, or if ``d.tzinfo`` is not ``None`` but ``d.tzinfo.utcoffset(d)``
119returns ``None``, *d* is naive. A :class:`.time` object *t* is aware
120if ``t.tzinfo`` is not ``None`` and ``t.tzinfo.utcoffset(None)`` does not return
121``None``. Otherwise, *t* is naive.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000122
123The distinction between naive and aware doesn't apply to :class:`timedelta`
124objects.
125
126Subclass relationships::
127
128 object
129 timedelta
130 tzinfo
131 time
132 date
133 datetime
134
135
136.. _datetime-timedelta:
137
138:class:`timedelta` Objects
139--------------------------
140
141A :class:`timedelta` object represents a duration, the difference between two
142dates or times.
143
Georg Brandl8ec7f652007-08-15 14:28:01 +0000144.. class:: timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
145
146 All arguments are optional and default to ``0``. Arguments may be ints, longs,
147 or floats, and may be positive or negative.
148
149 Only *days*, *seconds* and *microseconds* are stored internally. Arguments are
150 converted to those units:
151
152 * A millisecond is converted to 1000 microseconds.
153 * A minute is converted to 60 seconds.
154 * An hour is converted to 3600 seconds.
155 * A week is converted to 7 days.
156
157 and days, seconds and microseconds are then normalized so that the
158 representation is unique, with
159
160 * ``0 <= microseconds < 1000000``
161 * ``0 <= seconds < 3600*24`` (the number of seconds in one day)
162 * ``-999999999 <= days <= 999999999``
163
164 If any argument is a float and there are fractional microseconds, the fractional
165 microseconds left over from all arguments are combined and their sum is rounded
166 to the nearest microsecond. If no argument is a float, the conversion and
167 normalization processes are exact (no information is lost).
168
169 If the normalized value of days lies outside the indicated range,
170 :exc:`OverflowError` is raised.
171
172 Note that normalization of negative values may be surprising at first. For
Georg Brandl3f043032008-03-22 21:21:57 +0000173 example,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000174
Georg Brandle40a6a82007-12-08 11:23:13 +0000175 >>> from datetime import timedelta
Georg Brandl8ec7f652007-08-15 14:28:01 +0000176 >>> d = timedelta(microseconds=-1)
177 >>> (d.days, d.seconds, d.microseconds)
178 (-1, 86399, 999999)
179
Georg Brandl8ec7f652007-08-15 14:28:01 +0000180
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000181Class attributes are:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000182
183.. attribute:: timedelta.min
184
185 The most negative :class:`timedelta` object, ``timedelta(-999999999)``.
186
187
188.. attribute:: timedelta.max
189
190 The most positive :class:`timedelta` object, ``timedelta(days=999999999,
191 hours=23, minutes=59, seconds=59, microseconds=999999)``.
192
193
194.. attribute:: timedelta.resolution
195
196 The smallest possible difference between non-equal :class:`timedelta` objects,
197 ``timedelta(microseconds=1)``.
198
199Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``.
200``-timedelta.max`` is not representable as a :class:`timedelta` object.
201
202Instance attributes (read-only):
203
204+------------------+--------------------------------------------+
205| Attribute | Value |
206+==================+============================================+
207| ``days`` | Between -999999999 and 999999999 inclusive |
208+------------------+--------------------------------------------+
209| ``seconds`` | Between 0 and 86399 inclusive |
210+------------------+--------------------------------------------+
211| ``microseconds`` | Between 0 and 999999 inclusive |
212+------------------+--------------------------------------------+
213
214Supported operations:
215
Georg Brandlb19be572007-12-29 10:57:00 +0000216.. XXX this table is too wide!
Georg Brandl8ec7f652007-08-15 14:28:01 +0000217
218+--------------------------------+-----------------------------------------------+
219| Operation | Result |
220+================================+===============================================+
221| ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == |
222| | *t3* and *t1*-*t3* == *t2* are true. (1) |
223+--------------------------------+-----------------------------------------------+
224| ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* |
225| | == *t2* - *t3* and *t2* == *t1* + *t3* are |
226| | true. (1) |
227+--------------------------------+-----------------------------------------------+
228| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer or long. |
229| | Afterwards *t1* // i == *t2* is true, |
230| | provided ``i != 0``. |
231+--------------------------------+-----------------------------------------------+
232| | In general, *t1* \* i == *t1* \* (i-1) + *t1* |
233| | is true. (1) |
234+--------------------------------+-----------------------------------------------+
235| ``t1 = t2 // i`` | The floor is computed and the remainder (if |
236| | any) is thrown away. (3) |
237+--------------------------------+-----------------------------------------------+
238| ``+t1`` | Returns a :class:`timedelta` object with the |
239| | same value. (2) |
240+--------------------------------+-----------------------------------------------+
241| ``-t1`` | equivalent to :class:`timedelta`\ |
242| | (-*t1.days*, -*t1.seconds*, |
243| | -*t1.microseconds*), and to *t1*\* -1. (1)(4) |
244+--------------------------------+-----------------------------------------------+
Georg Brandl5ffa1462009-10-13 18:10:59 +0000245| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, and|
Georg Brandl8ec7f652007-08-15 14:28:01 +0000246| | to -*t* when ``t.days < 0``. (2) |
247+--------------------------------+-----------------------------------------------+
Georg Brandlad8ac862010-08-01 19:21:26 +0000248| ``str(t)`` | Returns a string in the form |
249| | ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D |
250| | is negative for negative ``t``. (5) |
251+--------------------------------+-----------------------------------------------+
252| ``repr(t)`` | Returns a string in the form |
253| | ``datetime.timedelta(D[, S[, U]])``, where D |
254| | is negative for negative ``t``. (5) |
255+--------------------------------+-----------------------------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000256
257Notes:
258
259(1)
260 This is exact, but may overflow.
261
262(2)
263 This is exact, and cannot overflow.
264
265(3)
266 Division by 0 raises :exc:`ZeroDivisionError`.
267
268(4)
269 -*timedelta.max* is not representable as a :class:`timedelta` object.
270
Georg Brandlad8ac862010-08-01 19:21:26 +0000271(5)
272 String representations of :class:`timedelta` objects are normalized
273 similarly to their internal representation. This leads to somewhat
274 unusual results for negative timedeltas. For example:
275
276 >>> timedelta(hours=-5)
277 datetime.timedelta(-1, 68400)
278 >>> print(_)
279 -1 day, 19:00:00
280
Georg Brandl8ec7f652007-08-15 14:28:01 +0000281In addition to the operations listed above :class:`timedelta` objects support
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100282certain additions and subtractions with :class:`date` and :class:`.datetime`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000283objects (see below).
284
285Comparisons of :class:`timedelta` objects are supported with the
286:class:`timedelta` object representing the smaller duration considered to be the
287smaller timedelta. In order to stop mixed-type comparisons from falling back to
288the default comparison by object address, when a :class:`timedelta` object is
289compared to an object of a different type, :exc:`TypeError` is raised unless the
290comparison is ``==`` or ``!=``. The latter cases return :const:`False` or
291:const:`True`, respectively.
292
Georg Brandl7c3e79f2007-11-02 20:06:17 +0000293:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
Georg Brandl8ec7f652007-08-15 14:28:01 +0000294efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
295considered to be true if and only if it isn't equal to ``timedelta(0)``.
296
Antoine Pitroubcfaf802009-11-25 22:59:36 +0000297Instance methods:
298
299.. method:: timedelta.total_seconds()
300
Mark Dickinson7000e9e2010-05-09 09:30:06 +0000301 Return the total number of seconds contained in the duration.
302 Equivalent to ``(td.microseconds + (td.seconds + td.days * 24 *
303 3600) * 10**6) / 10**6`` computed with true division enabled.
304
305 Note that for very large time intervals (greater than 270 years on
306 most platforms) this method will lose microsecond accuracy.
Antoine Pitroubcfaf802009-11-25 22:59:36 +0000307
Antoine Pitroue236c3c2009-11-25 23:03:22 +0000308 .. versionadded:: 2.7
309
Antoine Pitroubcfaf802009-11-25 22:59:36 +0000310
Georg Brandl3f043032008-03-22 21:21:57 +0000311Example usage:
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000312
Georg Brandle40a6a82007-12-08 11:23:13 +0000313 >>> from datetime import timedelta
314 >>> year = timedelta(days=365)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000315 >>> another_year = timedelta(weeks=40, days=84, hours=23,
Georg Brandle40a6a82007-12-08 11:23:13 +0000316 ... minutes=50, seconds=600) # adds up to 365 days
Antoine Pitroubcfaf802009-11-25 22:59:36 +0000317 >>> year.total_seconds()
318 31536000.0
Georg Brandle40a6a82007-12-08 11:23:13 +0000319 >>> year == another_year
320 True
321 >>> ten_years = 10 * year
322 >>> ten_years, ten_years.days // 365
323 (datetime.timedelta(3650), 10)
324 >>> nine_years = ten_years - year
325 >>> nine_years, nine_years.days // 365
326 (datetime.timedelta(3285), 9)
327 >>> three_years = nine_years // 3;
328 >>> three_years, three_years.days // 365
329 (datetime.timedelta(1095), 3)
330 >>> abs(three_years - ten_years) == 2 * three_years + year
331 True
332
Georg Brandl8ec7f652007-08-15 14:28:01 +0000333
334.. _datetime-date:
335
336:class:`date` Objects
337---------------------
338
339A :class:`date` object represents a date (year, month and day) in an idealized
340calendar, the current Gregorian calendar indefinitely extended in both
341directions. January 1 of year 1 is called day number 1, January 2 of year 1 is
342called day number 2, and so on. This matches the definition of the "proleptic
343Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
344where it's the base calendar for all computations. See the book for algorithms
345for converting between proleptic Gregorian ordinals and many other calendar
346systems.
347
348
349.. class:: date(year, month, day)
350
351 All arguments are required. Arguments may be ints or longs, in the following
352 ranges:
353
354 * ``MINYEAR <= year <= MAXYEAR``
355 * ``1 <= month <= 12``
356 * ``1 <= day <= number of days in the given month and year``
357
358 If an argument outside those ranges is given, :exc:`ValueError` is raised.
359
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000360
Georg Brandl8ec7f652007-08-15 14:28:01 +0000361Other constructors, all class methods:
362
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000363.. classmethod:: date.today()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000364
365 Return the current local date. This is equivalent to
366 ``date.fromtimestamp(time.time())``.
367
368
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000369.. classmethod:: date.fromtimestamp(timestamp)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000370
371 Return the local date corresponding to the POSIX timestamp, such as is returned
372 by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100373 of the range of values supported by the platform C :c:func:`localtime` function.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000374 It's common for this to be restricted to years from 1970 through 2038. Note
375 that on non-POSIX systems that include leap seconds in their notion of a
376 timestamp, leap seconds are ignored by :meth:`fromtimestamp`.
377
378
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000379.. classmethod:: date.fromordinal(ordinal)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000380
381 Return the date corresponding to the proleptic Gregorian ordinal, where January
382 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 <= ordinal <=
383 date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
384 d``.
385
Georg Brandl8ec7f652007-08-15 14:28:01 +0000386
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000387Class attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000388
389.. attribute:: date.min
390
391 The earliest representable date, ``date(MINYEAR, 1, 1)``.
392
393
394.. attribute:: date.max
395
396 The latest representable date, ``date(MAXYEAR, 12, 31)``.
397
398
399.. attribute:: date.resolution
400
401 The smallest possible difference between non-equal date objects,
402 ``timedelta(days=1)``.
403
Georg Brandl8ec7f652007-08-15 14:28:01 +0000404
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000405Instance attributes (read-only):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000406
407.. attribute:: date.year
408
409 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
410
411
412.. attribute:: date.month
413
414 Between 1 and 12 inclusive.
415
416
417.. attribute:: date.day
418
419 Between 1 and the number of days in the given month of the given year.
420
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000421
Georg Brandl8ec7f652007-08-15 14:28:01 +0000422Supported operations:
423
424+-------------------------------+----------------------------------------------+
425| Operation | Result |
426+===============================+==============================================+
427| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed |
428| | from *date1*. (1) |
429+-------------------------------+----------------------------------------------+
430| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + |
431| | timedelta == date1``. (2) |
432+-------------------------------+----------------------------------------------+
433| ``timedelta = date1 - date2`` | \(3) |
434+-------------------------------+----------------------------------------------+
435| ``date1 < date2`` | *date1* is considered less than *date2* when |
436| | *date1* precedes *date2* in time. (4) |
437+-------------------------------+----------------------------------------------+
438
439Notes:
440
441(1)
442 *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
443 ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``.
444 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
445 :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
446 :const:`MINYEAR` or larger than :const:`MAXYEAR`.
447
448(2)
449 This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
450 isolation can overflow in cases where date1 - timedelta does not.
451 ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
452
453(3)
454 This is exact, and cannot overflow. timedelta.seconds and
455 timedelta.microseconds are 0, and date2 + timedelta == date1 after.
456
457(4)
458 In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
459 date2.toordinal()``. In order to stop comparison from falling back to the
460 default scheme of comparing object addresses, date comparison normally raises
461 :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
462 However, ``NotImplemented`` is returned instead if the other comparand has a
463 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
464 chance at implementing mixed-type comparison. If not, when a :class:`date`
465 object is compared to an object of a different type, :exc:`TypeError` is raised
466 unless the comparison is ``==`` or ``!=``. The latter cases return
467 :const:`False` or :const:`True`, respectively.
468
469Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
470objects are considered to be true.
471
472Instance methods:
473
Georg Brandl8ec7f652007-08-15 14:28:01 +0000474.. method:: date.replace(year, month, day)
475
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700476 Return a date with the same value, except for those parameters given new
477 values by whichever keyword arguments are specified. For example, if ``d ==
478 date(2002, 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000479
480
481.. method:: date.timetuple()
482
483 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
484 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
485 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
Georg Brandl151973e2010-05-23 21:29:29 +0000486 d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1,
487 1).toordinal() + 1`` is the day number within the current year starting with
488 ``1`` for January 1st.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000489
490
491.. method:: date.toordinal()
492
493 Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
494 has ordinal 1. For any :class:`date` object *d*,
495 ``date.fromordinal(d.toordinal()) == d``.
496
497
498.. method:: date.weekday()
499
500 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
501 For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
502 :meth:`isoweekday`.
503
504
505.. method:: date.isoweekday()
506
507 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
508 For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
509 :meth:`weekday`, :meth:`isocalendar`.
510
511
512.. method:: date.isocalendar()
513
514 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
515
516 The ISO calendar is a widely used variant of the Gregorian calendar. See
Georg Brandl0f5d6c02014-10-29 10:57:37 +0100517 http://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm for a good
Mark Dickinson5b544322009-11-03 16:26:14 +0000518 explanation.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000519
520 The ISO year consists of 52 or 53 full weeks, and where a week starts on a
521 Monday and ends on a Sunday. The first week of an ISO year is the first
522 (Gregorian) calendar week of a year containing a Thursday. This is called week
523 number 1, and the ISO year of that Thursday is the same as its Gregorian year.
524
525 For example, 2004 begins on a Thursday, so the first week of ISO year 2004
526 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
527 ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
528 4).isocalendar() == (2004, 1, 7)``.
529
530
531.. method:: date.isoformat()
532
533 Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For
534 example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
535
536
537.. method:: date.__str__()
538
539 For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
540
541
542.. method:: date.ctime()
543
544 Return a string representing the date, for example ``date(2002, 12,
545 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
546 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100547 :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl8ec7f652007-08-15 14:28:01 +0000548 :meth:`date.ctime` does not invoke) conforms to the C standard.
549
550
551.. method:: date.strftime(format)
552
553 Return a string representing the date, controlled by an explicit format string.
David Wolever73480ef2013-04-13 19:12:58 -0400554 Format codes referring to hours, minutes or seconds will see 0 values. For a
555 complete list of formatting directives, see section
556 :ref:`strftime-strptime-behavior`.
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000557
Georg Brandl8ec7f652007-08-15 14:28:01 +0000558
Ezio Melotticfb63cd2013-04-04 09:16:15 +0300559.. method:: date.__format__(format)
560
561 Same as :meth:`.date.strftime`. This makes it possible to specify format
562 string for a :class:`.date` object when using :meth:`str.format`.
563 See section :ref:`strftime-strptime-behavior`.
564
565
Georg Brandle40a6a82007-12-08 11:23:13 +0000566Example of counting days to an event::
567
568 >>> import time
569 >>> from datetime import date
570 >>> today = date.today()
571 >>> today
572 datetime.date(2007, 12, 5)
573 >>> today == date.fromtimestamp(time.time())
574 True
575 >>> my_birthday = date(today.year, 6, 24)
576 >>> if my_birthday < today:
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000577 ... my_birthday = my_birthday.replace(year=today.year + 1)
Georg Brandle40a6a82007-12-08 11:23:13 +0000578 >>> my_birthday
579 datetime.date(2008, 6, 24)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000580 >>> time_to_birthday = abs(my_birthday - today)
Georg Brandle40a6a82007-12-08 11:23:13 +0000581 >>> time_to_birthday.days
582 202
583
Georg Brandl3f043032008-03-22 21:21:57 +0000584Example of working with :class:`date`:
585
586.. doctest::
Georg Brandle40a6a82007-12-08 11:23:13 +0000587
588 >>> from datetime import date
589 >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
590 >>> d
591 datetime.date(2002, 3, 11)
592 >>> t = d.timetuple()
Georg Brandl3f043032008-03-22 21:21:57 +0000593 >>> for i in t: # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +0000594 ... print i
595 2002 # year
596 3 # month
597 11 # day
598 0
599 0
600 0
601 0 # weekday (0 = Monday)
602 70 # 70th day in the year
603 -1
604 >>> ic = d.isocalendar()
Georg Brandl3f043032008-03-22 21:21:57 +0000605 >>> for i in ic: # doctest: +SKIP
606 ... print i
Georg Brandle40a6a82007-12-08 11:23:13 +0000607 2002 # ISO year
608 11 # ISO week number
609 1 # ISO day number ( 1 = Monday )
610 >>> d.isoformat()
611 '2002-03-11'
612 >>> d.strftime("%d/%m/%y")
613 '11/03/02'
614 >>> d.strftime("%A %d. %B %Y")
615 'Monday 11. March 2002'
Ezio Melotticfb63cd2013-04-04 09:16:15 +0300616 >>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")
617 'The day is 11, the month is March.'
Georg Brandle40a6a82007-12-08 11:23:13 +0000618
Georg Brandl8ec7f652007-08-15 14:28:01 +0000619
620.. _datetime-datetime:
621
Benjamin Petersoncf0d31c2015-04-25 14:15:16 -0400622:class:`.datetime` Objects
623--------------------------
Georg Brandl8ec7f652007-08-15 14:28:01 +0000624
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100625A :class:`.datetime` object is a single object containing all the information
626from a :class:`date` object and a :class:`.time` object. Like a :class:`date`
627object, :class:`.datetime` assumes the current Gregorian calendar extended in
628both directions; like a time object, :class:`.datetime` assumes there are exactly
Georg Brandl8ec7f652007-08-15 14:28:01 +00006293600\*24 seconds in every day.
630
631Constructor:
632
Georg Brandl8ec7f652007-08-15 14:28:01 +0000633.. class:: datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])
634
635 The year, month and day arguments are required. *tzinfo* may be ``None``, or an
636 instance of a :class:`tzinfo` subclass. The remaining arguments may be ints or
637 longs, in the following ranges:
638
639 * ``MINYEAR <= year <= MAXYEAR``
640 * ``1 <= month <= 12``
641 * ``1 <= day <= number of days in the given month and year``
642 * ``0 <= hour < 24``
643 * ``0 <= minute < 60``
644 * ``0 <= second < 60``
645 * ``0 <= microsecond < 1000000``
646
647 If an argument outside those ranges is given, :exc:`ValueError` is raised.
648
649Other constructors, all class methods:
650
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000651.. classmethod:: datetime.today()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000652
653 Return the current local datetime, with :attr:`tzinfo` ``None``. This is
654 equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
655 :meth:`fromtimestamp`.
656
657
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000658.. classmethod:: datetime.now([tz])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000659
660 Return the current local date and time. If optional argument *tz* is ``None``
661 or not specified, this is like :meth:`today`, but, if possible, supplies more
662 precision than can be gotten from going through a :func:`time.time` timestamp
663 (for example, this may be possible on platforms supplying the C
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100664 :c:func:`gettimeofday` function).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000665
666 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
667 current date and time are converted to *tz*'s time zone. In this case the
668 result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
669 See also :meth:`today`, :meth:`utcnow`.
670
671
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000672.. classmethod:: datetime.utcnow()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000673
674 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
675 :meth:`now`, but returns the current UTC date and time, as a naive
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100676 :class:`.datetime` object. See also :meth:`now`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000677
678
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000679.. classmethod:: datetime.fromtimestamp(timestamp[, tz])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000680
681 Return the local date and time corresponding to the POSIX timestamp, such as is
682 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
683 specified, the timestamp is converted to the platform's local date and time, and
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100684 the returned :class:`.datetime` object is naive.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000685
686 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
687 timestamp is converted to *tz*'s time zone. In this case the result is
688 equivalent to
689 ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
690
691 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100692 the range of values supported by the platform C :c:func:`localtime` or
693 :c:func:`gmtime` functions. It's common for this to be restricted to years in
Georg Brandl8ec7f652007-08-15 14:28:01 +0000694 1970 through 2038. Note that on non-POSIX systems that include leap seconds in
695 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
696 and then it's possible to have two timestamps differing by a second that yield
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100697 identical :class:`.datetime` objects. See also :meth:`utcfromtimestamp`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000698
699
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000700.. classmethod:: datetime.utcfromtimestamp(timestamp)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000701
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100702 Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with
Georg Brandl8ec7f652007-08-15 14:28:01 +0000703 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100704 out of the range of values supported by the platform C :c:func:`gmtime` function.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000705 It's common for this to be restricted to years in 1970 through 2038. See also
706 :meth:`fromtimestamp`.
707
708
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000709.. classmethod:: datetime.fromordinal(ordinal)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000710
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100711 Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000712 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
713 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
714 microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
715
716
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000717.. classmethod:: datetime.combine(date, time)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000718
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100719 Return a new :class:`.datetime` object whose date components are equal to the
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800720 given :class:`date` object's, and whose time components and :attr:`tzinfo`
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100721 attributes are equal to the given :class:`.time` object's. For any
722 :class:`.datetime` object *d*,
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800723 ``d == datetime.combine(d.date(), d.timetz())``. If date is a
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100724 :class:`.datetime` object, its time components and :attr:`tzinfo` attributes
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800725 are ignored.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000726
727
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000728.. classmethod:: datetime.strptime(date_string, format)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000729
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100730 Return a :class:`.datetime` corresponding to *date_string*, parsed according to
Georg Brandl8ec7f652007-08-15 14:28:01 +0000731 *format*. This is equivalent to ``datetime(*(time.strptime(date_string,
732 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
733 can't be parsed by :func:`time.strptime` or if it returns a value which isn't a
David Wolever73480ef2013-04-13 19:12:58 -0400734 time tuple. For a complete list of formatting directives, see section
735 :ref:`strftime-strptime-behavior`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000736
737 .. versionadded:: 2.5
738
Georg Brandl8ec7f652007-08-15 14:28:01 +0000739
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000740Class attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000741
742.. attribute:: datetime.min
743
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100744 The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000745 tzinfo=None)``.
746
747
748.. attribute:: datetime.max
749
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100750 The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000751 59, 999999, tzinfo=None)``.
752
753
754.. attribute:: datetime.resolution
755
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100756 The smallest possible difference between non-equal :class:`.datetime` objects,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000757 ``timedelta(microseconds=1)``.
758
Georg Brandl8ec7f652007-08-15 14:28:01 +0000759
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000760Instance attributes (read-only):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000761
762.. attribute:: datetime.year
763
764 Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.
765
766
767.. attribute:: datetime.month
768
769 Between 1 and 12 inclusive.
770
771
772.. attribute:: datetime.day
773
774 Between 1 and the number of days in the given month of the given year.
775
776
777.. attribute:: datetime.hour
778
779 In ``range(24)``.
780
781
782.. attribute:: datetime.minute
783
784 In ``range(60)``.
785
786
787.. attribute:: datetime.second
788
789 In ``range(60)``.
790
791
792.. attribute:: datetime.microsecond
793
794 In ``range(1000000)``.
795
796
797.. attribute:: datetime.tzinfo
798
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100799 The object passed as the *tzinfo* argument to the :class:`.datetime` constructor,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000800 or ``None`` if none was passed.
801
Georg Brandl6cbb7f92010-01-17 08:42:30 +0000802
Georg Brandl8ec7f652007-08-15 14:28:01 +0000803Supported operations:
804
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100805+---------------------------------------+--------------------------------+
806| Operation | Result |
807+=======================================+================================+
808| ``datetime2 = datetime1 + timedelta`` | \(1) |
809+---------------------------------------+--------------------------------+
810| ``datetime2 = datetime1 - timedelta`` | \(2) |
811+---------------------------------------+--------------------------------+
812| ``timedelta = datetime1 - datetime2`` | \(3) |
813+---------------------------------------+--------------------------------+
814| ``datetime1 < datetime2`` | Compares :class:`.datetime` to |
815| | :class:`.datetime`. (4) |
816+---------------------------------------+--------------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000817
818(1)
819 datetime2 is a duration of timedelta removed from datetime1, moving forward in
820 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700821 result has the same :attr:`tzinfo` attribute as the input datetime, and
822 datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
823 datetime2.year would be smaller than :const:`MINYEAR` or larger than
824 :const:`MAXYEAR`. Note that no time zone adjustments are done even if the
825 input is an aware object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000826
827(2)
828 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700829 addition, the result has the same :attr:`tzinfo` attribute as the input
830 datetime, and no time zone adjustments are done even if the input is aware.
831 This isn't quite equivalent to datetime1 + (-timedelta), because -timedelta
832 in isolation can overflow in cases where datetime1 - timedelta does not.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000833
834(3)
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100835 Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if
Georg Brandl8ec7f652007-08-15 14:28:01 +0000836 both operands are naive, or if both are aware. If one is aware and the other is
837 naive, :exc:`TypeError` is raised.
838
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700839 If both are naive, or both are aware and have the same :attr:`tzinfo` attribute,
840 the :attr:`tzinfo` attributes are ignored, and the result is a :class:`timedelta`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000841 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
842 are done in this case.
843
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700844 If both are aware and have different :attr:`tzinfo` attributes, ``a-b`` acts
845 as if *a* and *b* were first converted to naive UTC datetimes first. The
846 result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
847 - b.utcoffset())`` except that the implementation never overflows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000848
849(4)
850 *datetime1* is considered less than *datetime2* when *datetime1* precedes
851 *datetime2* in time.
852
853 If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700854 If both comparands are aware, and have the same :attr:`tzinfo` attribute, the
855 common :attr:`tzinfo` attribute is ignored and the base datetimes are
856 compared. If both comparands are aware and have different :attr:`tzinfo`
857 attributes, the comparands are first adjusted by subtracting their UTC
858 offsets (obtained from ``self.utcoffset()``).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000859
860 .. note::
861
862 In order to stop comparison from falling back to the default scheme of comparing
863 object addresses, datetime comparison normally raises :exc:`TypeError` if the
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100864 other comparand isn't also a :class:`.datetime` object. However,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000865 ``NotImplemented`` is returned instead if the other comparand has a
866 :meth:`timetuple` attribute. This hook gives other kinds of date objects a
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100867 chance at implementing mixed-type comparison. If not, when a :class:`.datetime`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000868 object is compared to an object of a different type, :exc:`TypeError` is raised
869 unless the comparison is ``==`` or ``!=``. The latter cases return
870 :const:`False` or :const:`True`, respectively.
871
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100872:class:`.datetime` objects can be used as dictionary keys. In Boolean contexts,
873all :class:`.datetime` objects are considered to be true.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000874
875Instance methods:
876
Georg Brandl8ec7f652007-08-15 14:28:01 +0000877.. method:: datetime.date()
878
879 Return :class:`date` object with same year, month and day.
880
881
882.. method:: datetime.time()
883
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100884 Return :class:`.time` object with same hour, minute, second and microsecond.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000885 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
886
887
888.. method:: datetime.timetz()
889
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100890 Return :class:`.time` object with same hour, minute, second, microsecond, and
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700891 tzinfo attributes. See also method :meth:`time`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000892
893
894.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
895
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700896 Return a datetime with the same attributes, except for those attributes given
897 new values by whichever keyword arguments are specified. Note that
898 ``tzinfo=None`` can be specified to create a naive datetime from an aware
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800899 datetime with no conversion of date and time data.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000900
901
902.. method:: datetime.astimezone(tz)
903
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100904 Return a :class:`.datetime` object with new :attr:`tzinfo` attribute *tz*,
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800905 adjusting the date and time data so the result is the same UTC time as
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700906 *self*, but in *tz*'s local time.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000907
908 *tz* must be an instance of a :class:`tzinfo` subclass, and its
909 :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
910 be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
911 not return ``None``).
912
913 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800914 adjustment of date or time data is performed. Else the result is local
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700915 time in time zone *tz*, representing the same UTC time as *self*: after
916 ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800917 the same date and time data as ``dt - dt.utcoffset()``. The discussion
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700918 of class :class:`tzinfo` explains the cases at Daylight Saving Time transition
919 boundaries where this cannot be achieved (an issue only if *tz* models both
920 standard and daylight time).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000921
922 If you merely want to attach a time zone object *tz* to a datetime *dt* without
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800923 adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you
Georg Brandl8ec7f652007-08-15 14:28:01 +0000924 merely want to remove the time zone object from an aware datetime *dt* without
Senthil Kumaran4c9721a2011-07-17 19:10:10 +0800925 conversion of date and time data, use ``dt.replace(tzinfo=None)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000926
927 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
928 :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
929 Ignoring error cases, :meth:`astimezone` acts like::
930
931 def astimezone(self, tz):
932 if self.tzinfo is tz:
933 return self
934 # Convert self to UTC, and attach the new time zone object.
935 utc = (self - self.utcoffset()).replace(tzinfo=tz)
936 # Convert from UTC to tz's local time.
937 return tz.fromutc(utc)
938
939
940.. method:: datetime.utcoffset()
941
942 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
943 ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
944 return ``None``, or a :class:`timedelta` object representing a whole number of
945 minutes with magnitude less than one day.
946
947
948.. method:: datetime.dst()
949
950 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
951 ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
952 ``None``, or a :class:`timedelta` object representing a whole number of minutes
953 with magnitude less than one day.
954
955
956.. method:: datetime.tzname()
957
958 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
959 ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
960 ``None`` or a string object,
961
962
963.. method:: datetime.timetuple()
964
965 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
966 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
Georg Brandl151973e2010-05-23 21:29:29 +0000967 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
968 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
969 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
970 of the result is set according to the :meth:`dst` method: :attr:`tzinfo` is
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000971 ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
Georg Brandl151973e2010-05-23 21:29:29 +0000972 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
Alexander Belopolsky094c53c2010-06-09 17:08:11 +0000973 else :attr:`tm_isdst` is set to ``0``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000974
975
976.. method:: datetime.utctimetuple()
977
Sandro Tosi8d38fcf2012-02-18 20:28:35 +0100978 If :class:`.datetime` instance *d* is naive, this is the same as
Georg Brandl8ec7f652007-08-15 14:28:01 +0000979 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
980 ``d.dst()`` returns. DST is never in effect for a UTC time.
981
982 If *d* is aware, *d* is normalized to UTC time, by subtracting
983 ``d.utcoffset()``, and a :class:`time.struct_time` for the normalized time is
984 returned. :attr:`tm_isdst` is forced to 0. Note that the result's
985 :attr:`tm_year` member may be :const:`MINYEAR`\ -1 or :const:`MAXYEAR`\ +1, if
986 *d*.year was ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
987 boundary.
988
989
990.. method:: datetime.toordinal()
991
992 Return the proleptic Gregorian ordinal of the date. The same as
993 ``self.date().toordinal()``.
994
995
996.. method:: datetime.weekday()
997
998 Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
999 The same as ``self.date().weekday()``. See also :meth:`isoweekday`.
1000
1001
1002.. method:: datetime.isoweekday()
1003
1004 Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
1005 The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
1006 :meth:`isocalendar`.
1007
1008
1009.. method:: datetime.isocalendar()
1010
1011 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as
1012 ``self.date().isocalendar()``.
1013
1014
1015.. method:: datetime.isoformat([sep])
1016
1017 Return a string representing the date and time in ISO 8601 format,
1018 YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
1019 YYYY-MM-DDTHH:MM:SS
1020
1021 If :meth:`utcoffset` does not return ``None``, a 6-character string is
1022 appended, giving the UTC offset in (signed) hours and minutes:
1023 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
1024 YYYY-MM-DDTHH:MM:SS+HH:MM
1025
1026 The optional argument *sep* (default ``'T'``) is a one-character separator,
Georg Brandl3f043032008-03-22 21:21:57 +00001027 placed between the date and time portions of the result. For example,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001028
1029 >>> from datetime import tzinfo, timedelta, datetime
1030 >>> class TZ(tzinfo):
1031 ... def utcoffset(self, dt): return timedelta(minutes=-399)
1032 ...
1033 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
1034 '2002-12-25 00:00:00-06:39'
1035
1036
1037.. method:: datetime.__str__()
1038
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001039 For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to
Georg Brandl8ec7f652007-08-15 14:28:01 +00001040 ``d.isoformat(' ')``.
1041
1042
1043.. method:: datetime.ctime()
1044
1045 Return a string representing the date and time, for example ``datetime(2002, 12,
1046 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is
1047 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
Sandro Tosi98ed08f2012-01-14 16:42:02 +01001048 native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
Georg Brandl8ec7f652007-08-15 14:28:01 +00001049 :meth:`datetime.ctime` does not invoke) conforms to the C standard.
1050
1051
1052.. method:: datetime.strftime(format)
1053
1054 Return a string representing the date and time, controlled by an explicit format
David Wolever73480ef2013-04-13 19:12:58 -04001055 string. For a complete list of formatting directives, see section
1056 :ref:`strftime-strptime-behavior`.
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001057
Georg Brandl8ec7f652007-08-15 14:28:01 +00001058
Ezio Melotticfb63cd2013-04-04 09:16:15 +03001059.. method:: datetime.__format__(format)
1060
1061 Same as :meth:`.datetime.strftime`. This makes it possible to specify format
1062 string for a :class:`.datetime` object when using :meth:`str.format`.
1063 See section :ref:`strftime-strptime-behavior`.
1064
1065
Georg Brandl3f043032008-03-22 21:21:57 +00001066Examples of working with datetime objects:
1067
1068.. doctest::
1069
Georg Brandle40a6a82007-12-08 11:23:13 +00001070 >>> from datetime import datetime, date, time
1071 >>> # Using datetime.combine()
1072 >>> d = date(2005, 7, 14)
1073 >>> t = time(12, 30)
1074 >>> datetime.combine(d, t)
1075 datetime.datetime(2005, 7, 14, 12, 30)
1076 >>> # Using datetime.now() or datetime.utcnow()
Georg Brandl3f043032008-03-22 21:21:57 +00001077 >>> datetime.now() # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +00001078 datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
Georg Brandl3f043032008-03-22 21:21:57 +00001079 >>> datetime.utcnow() # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +00001080 datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1081 >>> # Using datetime.strptime()
1082 >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1083 >>> dt
1084 datetime.datetime(2006, 11, 21, 16, 30)
1085 >>> # Using datetime.timetuple() to get tuple of all attributes
1086 >>> tt = dt.timetuple()
Georg Brandl3f043032008-03-22 21:21:57 +00001087 >>> for it in tt: # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +00001088 ... print it
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001089 ...
Georg Brandle40a6a82007-12-08 11:23:13 +00001090 2006 # year
1091 11 # month
1092 21 # day
1093 16 # hour
1094 30 # minute
1095 0 # second
1096 1 # weekday (0 = Monday)
1097 325 # number of days since 1st January
1098 -1 # dst - method tzinfo.dst() returned None
1099 >>> # Date in ISO format
1100 >>> ic = dt.isocalendar()
Georg Brandl3f043032008-03-22 21:21:57 +00001101 >>> for it in ic: # doctest: +SKIP
Georg Brandle40a6a82007-12-08 11:23:13 +00001102 ... print it
1103 ...
1104 2006 # ISO year
1105 47 # ISO week
1106 2 # ISO weekday
1107 >>> # Formatting datetime
1108 >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1109 'Tuesday, 21. November 2006 04:30PM'
Ezio Melotticfb63cd2013-04-04 09:16:15 +03001110 >>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
1111 'The day is 21, the month is November, the time is 04:30PM.'
Georg Brandle40a6a82007-12-08 11:23:13 +00001112
Georg Brandl3f043032008-03-22 21:21:57 +00001113Using datetime with tzinfo:
Georg Brandle40a6a82007-12-08 11:23:13 +00001114
1115 >>> from datetime import timedelta, datetime, tzinfo
1116 >>> class GMT1(tzinfo):
Senthil Kumaran189bd912012-06-26 20:05:12 +08001117 ... def utcoffset(self, dt):
1118 ... return timedelta(hours=1) + self.dst(dt)
1119 ... def dst(self, dt):
1120 ... # DST starts last Sunday in March
Georg Brandle40a6a82007-12-08 11:23:13 +00001121 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October
1122 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001123 ... d = datetime(dt.year, 11, 1)
Georg Brandle40a6a82007-12-08 11:23:13 +00001124 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
Georg Brandle40a6a82007-12-08 11:23:13 +00001125 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
1126 ... return timedelta(hours=1)
1127 ... else:
1128 ... return timedelta(0)
1129 ... def tzname(self,dt):
1130 ... return "GMT +1"
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001131 ...
Georg Brandle40a6a82007-12-08 11:23:13 +00001132 >>> class GMT2(tzinfo):
Senthil Kumaran189bd912012-06-26 20:05:12 +08001133 ... def utcoffset(self, dt):
1134 ... return timedelta(hours=2) + self.dst(dt)
1135 ... def dst(self, dt):
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001136 ... d = datetime(dt.year, 4, 1)
Georg Brandle40a6a82007-12-08 11:23:13 +00001137 ... self.dston = d - timedelta(days=d.weekday() + 1)
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001138 ... d = datetime(dt.year, 11, 1)
Georg Brandle40a6a82007-12-08 11:23:13 +00001139 ... self.dstoff = d - timedelta(days=d.weekday() + 1)
Georg Brandle40a6a82007-12-08 11:23:13 +00001140 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
Senthil Kumaran189bd912012-06-26 20:05:12 +08001141 ... return timedelta(hours=1)
Georg Brandle40a6a82007-12-08 11:23:13 +00001142 ... else:
1143 ... return timedelta(0)
1144 ... def tzname(self,dt):
1145 ... return "GMT +2"
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001146 ...
Georg Brandle40a6a82007-12-08 11:23:13 +00001147 >>> gmt1 = GMT1()
1148 >>> # Daylight Saving Time
1149 >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1150 >>> dt1.dst()
1151 datetime.timedelta(0)
1152 >>> dt1.utcoffset()
1153 datetime.timedelta(0, 3600)
1154 >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1155 >>> dt2.dst()
1156 datetime.timedelta(0, 3600)
1157 >>> dt2.utcoffset()
1158 datetime.timedelta(0, 7200)
1159 >>> # Convert datetime to another time zone
1160 >>> dt3 = dt2.astimezone(GMT2())
1161 >>> dt3 # doctest: +ELLIPSIS
1162 datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1163 >>> dt2 # doctest: +ELLIPSIS
1164 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1165 >>> dt2.utctimetuple() == dt3.utctimetuple()
1166 True
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001167
Georg Brandle40a6a82007-12-08 11:23:13 +00001168
Georg Brandl8ec7f652007-08-15 14:28:01 +00001169
1170.. _datetime-time:
1171
1172:class:`time` Objects
1173---------------------
1174
1175A time object represents a (local) time of day, independent of any particular
1176day, and subject to adjustment via a :class:`tzinfo` object.
1177
Andrew Svetlov766849b2012-12-06 16:32:37 +02001178.. class:: time([hour[, minute[, second[, microsecond[, tzinfo]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001179
1180 All arguments are optional. *tzinfo* may be ``None``, or an instance of a
1181 :class:`tzinfo` subclass. The remaining arguments may be ints or longs, in the
1182 following ranges:
1183
1184 * ``0 <= hour < 24``
1185 * ``0 <= minute < 60``
1186 * ``0 <= second < 60``
1187 * ``0 <= microsecond < 1000000``.
1188
1189 If an argument outside those ranges is given, :exc:`ValueError` is raised. All
1190 default to ``0`` except *tzinfo*, which defaults to :const:`None`.
1191
1192Class attributes:
1193
1194
1195.. attribute:: time.min
1196
Ezio Melottif17e4052011-10-02 12:22:13 +03001197 The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001198
1199
1200.. attribute:: time.max
1201
Ezio Melottif17e4052011-10-02 12:22:13 +03001202 The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001203
1204
1205.. attribute:: time.resolution
1206
Ezio Melottif17e4052011-10-02 12:22:13 +03001207 The smallest possible difference between non-equal :class:`.time` objects,
1208 ``timedelta(microseconds=1)``, although note that arithmetic on
1209 :class:`.time` objects is not supported.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001210
Georg Brandl8ec7f652007-08-15 14:28:01 +00001211
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001212Instance attributes (read-only):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001213
1214.. attribute:: time.hour
1215
1216 In ``range(24)``.
1217
1218
1219.. attribute:: time.minute
1220
1221 In ``range(60)``.
1222
1223
1224.. attribute:: time.second
1225
1226 In ``range(60)``.
1227
1228
1229.. attribute:: time.microsecond
1230
1231 In ``range(1000000)``.
1232
1233
1234.. attribute:: time.tzinfo
1235
Ezio Melottif17e4052011-10-02 12:22:13 +03001236 The object passed as the tzinfo argument to the :class:`.time` constructor, or
Georg Brandl8ec7f652007-08-15 14:28:01 +00001237 ``None`` if none was passed.
1238
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001239
Georg Brandl8ec7f652007-08-15 14:28:01 +00001240Supported operations:
1241
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001242* comparison of :class:`.time` to :class:`.time`, where *a* is considered less
Georg Brandl8ec7f652007-08-15 14:28:01 +00001243 than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1244 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
Senthil Kumaran6f18b982011-07-04 12:50:02 -07001245 the same :attr:`tzinfo` attribute, the common :attr:`tzinfo` attribute is
1246 ignored and the base times are compared. If both comparands are aware and
1247 have different :attr:`tzinfo` attributes, the comparands are first adjusted by
1248 subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
1249 to stop mixed-type comparisons from falling back to the default comparison by
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001250 object address, when a :class:`.time` object is compared to an object of a
Senthil Kumaran6f18b982011-07-04 12:50:02 -07001251 different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
1252 ``!=``. The latter cases return :const:`False` or :const:`True`, respectively.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001253
1254* hash, use as dict key
1255
1256* efficient pickling
1257
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001258* in Boolean contexts, a :class:`.time` object is considered to be true if and
Georg Brandl8ec7f652007-08-15 14:28:01 +00001259 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1260 ``0`` if that's ``None``), the result is non-zero.
1261
Georg Brandl8ec7f652007-08-15 14:28:01 +00001262
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001263Instance methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001264
1265.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
1266
Ezio Melottif17e4052011-10-02 12:22:13 +03001267 Return a :class:`.time` with the same value, except for those attributes given
Senthil Kumaran6f18b982011-07-04 12:50:02 -07001268 new values by whichever keyword arguments are specified. Note that
Ezio Melottif17e4052011-10-02 12:22:13 +03001269 ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
1270 aware :class:`.time`, without conversion of the time data.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001271
1272
1273.. method:: time.isoformat()
1274
1275 Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
1276 self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
1277 6-character string is appended, giving the UTC offset in (signed) hours and
1278 minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
1279
1280
1281.. method:: time.__str__()
1282
1283 For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1284
1285
1286.. method:: time.strftime(format)
1287
1288 Return a string representing the time, controlled by an explicit format string.
David Wolever73480ef2013-04-13 19:12:58 -04001289 For a complete list of formatting directives, see section
1290 :ref:`strftime-strptime-behavior`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001291
1292
Ezio Melotticfb63cd2013-04-04 09:16:15 +03001293.. method:: time.__format__(format)
1294
1295 Same as :meth:`.time.strftime`. This makes it possible to specify format string
1296 for a :class:`.time` object when using :meth:`str.format`.
1297 See section :ref:`strftime-strptime-behavior`.
1298
1299
Georg Brandl8ec7f652007-08-15 14:28:01 +00001300.. method:: time.utcoffset()
1301
1302 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1303 ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1304 return ``None`` or a :class:`timedelta` object representing a whole number of
1305 minutes with magnitude less than one day.
1306
1307
1308.. method:: time.dst()
1309
1310 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1311 ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
1312 ``None``, or a :class:`timedelta` object representing a whole number of minutes
1313 with magnitude less than one day.
1314
1315
1316.. method:: time.tzname()
1317
1318 If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1319 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1320 return ``None`` or a string object.
1321
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001322
Georg Brandl3f043032008-03-22 21:21:57 +00001323Example:
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001324
Georg Brandle40a6a82007-12-08 11:23:13 +00001325 >>> from datetime import time, tzinfo
1326 >>> class GMT1(tzinfo):
1327 ... def utcoffset(self, dt):
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001328 ... return timedelta(hours=1)
1329 ... def dst(self, dt):
Georg Brandle40a6a82007-12-08 11:23:13 +00001330 ... return timedelta(0)
1331 ... def tzname(self,dt):
1332 ... return "Europe/Prague"
1333 ...
1334 >>> t = time(12, 10, 30, tzinfo=GMT1())
1335 >>> t # doctest: +ELLIPSIS
1336 datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1337 >>> gmt = GMT1()
1338 >>> t.isoformat()
1339 '12:10:30+01:00'
1340 >>> t.dst()
1341 datetime.timedelta(0)
1342 >>> t.tzname()
1343 'Europe/Prague'
1344 >>> t.strftime("%H:%M:%S %Z")
1345 '12:10:30 Europe/Prague'
Ezio Melotticfb63cd2013-04-04 09:16:15 +03001346 >>> 'The {} is {:%H:%M}.'.format("time", t)
1347 'The time is 12:10.'
Georg Brandle40a6a82007-12-08 11:23:13 +00001348
Georg Brandl8ec7f652007-08-15 14:28:01 +00001349
1350.. _datetime-tzinfo:
1351
1352:class:`tzinfo` Objects
1353-----------------------
1354
Brett Cannon8aa2c6c2009-01-29 00:54:32 +00001355:class:`tzinfo` is an abstract base class, meaning that this class should not be
Georg Brandl8ec7f652007-08-15 14:28:01 +00001356instantiated directly. You need to derive a concrete subclass, and (at least)
1357supply implementations of the standard :class:`tzinfo` methods needed by the
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001358:class:`.datetime` methods you use. The :mod:`datetime` module does not supply
Georg Brandl8ec7f652007-08-15 14:28:01 +00001359any concrete subclasses of :class:`tzinfo`.
1360
1361An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001362constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
Senthil Kumaran6f18b982011-07-04 12:50:02 -07001363view their attributes as being in local time, and the :class:`tzinfo` object
Georg Brandl8ec7f652007-08-15 14:28:01 +00001364supports methods revealing offset of local time from UTC, the name of the time
1365zone, and DST offset, all relative to a date or time object passed to them.
1366
1367Special requirement for pickling: A :class:`tzinfo` subclass must have an
1368:meth:`__init__` method that can be called with no arguments, else it can be
1369pickled but possibly not unpickled again. This is a technical requirement that
1370may be relaxed in the future.
1371
1372A concrete subclass of :class:`tzinfo` may need to implement the following
1373methods. Exactly which methods are needed depends on the uses made of aware
1374:mod:`datetime` objects. If in doubt, simply implement all of them.
1375
1376
1377.. method:: tzinfo.utcoffset(self, dt)
1378
1379 Return offset of local time from UTC, in minutes east of UTC. If local time is
1380 west of UTC, this should be negative. Note that this is intended to be the
1381 total offset from UTC; for example, if a :class:`tzinfo` object represents both
1382 time zone and DST adjustments, :meth:`utcoffset` should return their sum. If
1383 the UTC offset isn't known, return ``None``. Else the value returned must be a
1384 :class:`timedelta` object specifying a whole number of minutes in the range
1385 -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1386 than one day). Most implementations of :meth:`utcoffset` will probably look
1387 like one of these two::
1388
1389 return CONSTANT # fixed-offset class
1390 return CONSTANT + self.dst(dt) # daylight-aware class
1391
1392 If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1393 ``None`` either.
1394
1395 The default implementation of :meth:`utcoffset` raises
1396 :exc:`NotImplementedError`.
1397
1398
1399.. method:: tzinfo.dst(self, dt)
1400
1401 Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1402 ``None`` if DST information isn't known. Return ``timedelta(0)`` if DST is not
1403 in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1404 (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1405 already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1406 no need to consult :meth:`dst` unless you're interested in obtaining DST info
1407 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
Senthil Kumaran6f18b982011-07-04 12:50:02 -07001408 attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
1409 should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
1410 DST changes when crossing time zones.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001411
1412 An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1413 daylight times must be consistent in this sense:
1414
1415 ``tz.utcoffset(dt) - tz.dst(dt)``
1416
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001417 must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo ==
Georg Brandl8ec7f652007-08-15 14:28:01 +00001418 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1419 zone's "standard offset", which should not depend on the date or the time, but
1420 only on geographic location. The implementation of :meth:`datetime.astimezone`
1421 relies on this, but cannot detect violations; it's the programmer's
1422 responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee
1423 this, it may be able to override the default implementation of
1424 :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.
1425
1426 Most implementations of :meth:`dst` will probably look like one of these two::
1427
Sandro Tosi1f3b84f2011-11-01 10:31:26 +01001428 def dst(self, dt):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001429 # a fixed-offset class: doesn't account for DST
1430 return timedelta(0)
1431
1432 or ::
1433
Sandro Tosi1f3b84f2011-11-01 10:31:26 +01001434 def dst(self, dt):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001435 # Code to set dston and dstoff to the time zone's DST
1436 # transition times based on the input dt.year, and expressed
1437 # in standard local time. Then
1438
1439 if dston <= dt.replace(tzinfo=None) < dstoff:
1440 return timedelta(hours=1)
1441 else:
1442 return timedelta(0)
1443
1444 The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1445
1446
1447.. method:: tzinfo.tzname(self, dt)
1448
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001449 Return the time zone name corresponding to the :class:`.datetime` object *dt*, as
Georg Brandl8ec7f652007-08-15 14:28:01 +00001450 a string. Nothing about string names is defined by the :mod:`datetime` module,
1451 and there's no requirement that it mean anything in particular. For example,
1452 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1453 valid replies. Return ``None`` if a string name isn't known. Note that this is
1454 a method rather than a fixed string primarily because some :class:`tzinfo`
1455 subclasses will wish to return different names depending on the specific value
1456 of *dt* passed, especially if the :class:`tzinfo` class is accounting for
1457 daylight time.
1458
1459 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.
1460
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001461
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001462These methods are called by a :class:`.datetime` or :class:`.time` object, in
1463response to their methods of the same names. A :class:`.datetime` object passes
1464itself as the argument, and a :class:`.time` object passes ``None`` as the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001465argument. A :class:`tzinfo` subclass's methods should therefore be prepared to
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001466accept a *dt* argument of ``None``, or of class :class:`.datetime`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001467
1468When ``None`` is passed, it's up to the class designer to decide the best
1469response. For example, returning ``None`` is appropriate if the class wishes to
1470say that time objects don't participate in the :class:`tzinfo` protocols. It
1471may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
1472there is no other convention for discovering the standard offset.
1473
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001474When a :class:`.datetime` object is passed in response to a :class:`.datetime`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001475method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can
1476rely on this, unless user code calls :class:`tzinfo` methods directly. The
1477intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1478time, and not need worry about objects in other timezones.
1479
1480There is one more :class:`tzinfo` method that a subclass may wish to override:
1481
1482
1483.. method:: tzinfo.fromutc(self, dt)
1484
Senthil Kumaran4c9721a2011-07-17 19:10:10 +08001485 This is called from the default :class:`datetime.astimezone()`
1486 implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s
1487 date and time data are to be viewed as expressing a UTC time. The purpose
1488 of :meth:`fromutc` is to adjust the date and time data, returning an
Senthil Kumaran6f18b982011-07-04 12:50:02 -07001489 equivalent datetime in *self*'s local time.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001490
1491 Most :class:`tzinfo` subclasses should be able to inherit the default
1492 :meth:`fromutc` implementation without problems. It's strong enough to handle
1493 fixed-offset time zones, and time zones accounting for both standard and
1494 daylight time, and the latter even if the DST transition times differ in
1495 different years. An example of a time zone the default :meth:`fromutc`
1496 implementation may not handle correctly in all cases is one where the standard
1497 offset (from UTC) depends on the specific date and time passed, which can happen
1498 for political reasons. The default implementations of :meth:`astimezone` and
1499 :meth:`fromutc` may not produce the result you want if the result is one of the
1500 hours straddling the moment the standard offset changes.
1501
1502 Skipping code for error cases, the default :meth:`fromutc` implementation acts
1503 like::
1504
1505 def fromutc(self, dt):
1506 # raise ValueError error if dt.tzinfo is not self
1507 dtoff = dt.utcoffset()
1508 dtdst = dt.dst()
1509 # raise ValueError if dtoff is None or dtdst is None
1510 delta = dtoff - dtdst # this is self's standard offset
1511 if delta:
1512 dt += delta # convert to standard local time
1513 dtdst = dt.dst()
1514 # raise ValueError if dtdst is None
1515 if dtdst:
1516 return dt + dtdst
1517 else:
1518 return dt
1519
1520Example :class:`tzinfo` classes:
1521
1522.. literalinclude:: ../includes/tzinfo-examples.py
1523
1524
1525Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1526subclass accounting for both standard and daylight time, at the DST transition
1527points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the
Georg Brandlce00cf22010-03-21 09:58:36 +00001528minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
15291:59 (EDT) on the first Sunday in November::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001530
1531 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1532 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1533 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1534
1535 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1536
1537 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1538
1539When DST starts (the "start" line), the local wall clock leaps from 1:59 to
15403:00. A wall time of the form 2:MM doesn't really make sense on that day, so
1541``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
1542begins. In order for :meth:`astimezone` to make this guarantee, the
1543:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
1544Eastern) to be in daylight time.
1545
1546When DST ends (the "end" line), there's a potentially worse problem: there's an
1547hour that can't be spelled unambiguously in local wall time: the last hour of
1548daylight time. In Eastern, that's times of the form 5:MM UTC on the day
1549daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
1550to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
1551:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
1552hours into the same local hour then. In the Eastern example, UTC times of the
1553form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1554:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
1555consider times in the "repeated hour" to be in standard time. This is easily
1556arranged, as in the example, by expressing DST switch times in the time zone's
1557standard local time.
1558
1559Applications that can't bear such ambiguities should avoid using hybrid
1560:class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any
1561other fixed-offset :class:`tzinfo` subclass (such as a class representing only
1562EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001563
Sandro Tosi13c598b2012-04-24 19:43:33 +02001564.. seealso::
1565
Georg Brandl06f3b3b2014-10-29 08:36:35 +01001566 `pytz <https://pypi.python.org/pypi/pytz/>`_
Jason R. Coombs86af5812013-01-18 15:33:39 -05001567 The standard library has no :class:`tzinfo` instances, but
Sandro Tosiaa31d522012-04-28 11:19:11 +02001568 there exists a third-party library which brings the *IANA timezone
1569 database* (also known as the Olson database) to Python: *pytz*.
Sandro Tosi13c598b2012-04-24 19:43:33 +02001570
Sandro Tosiaa31d522012-04-28 11:19:11 +02001571 *pytz* contains up-to-date information and its usage is recommended.
1572
1573 `IANA timezone database <http://www.iana.org/time-zones>`_
1574 The Time Zone Database (often called tz or zoneinfo) contains code and
1575 data that represent the history of local time for many representative
1576 locations around the globe. It is updated periodically to reflect changes
1577 made by political bodies to time zone boundaries, UTC offsets, and
1578 daylight-saving rules.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001579
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001580.. _strftime-strptime-behavior:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001581
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001582:meth:`strftime` and :meth:`strptime` Behavior
1583----------------------------------------------
Georg Brandl8ec7f652007-08-15 14:28:01 +00001584
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001585:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
Georg Brandl8ec7f652007-08-15 14:28:01 +00001586``strftime(format)`` method, to create a string representing the time under the
1587control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1588acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1589although not all objects support a :meth:`timetuple` method.
1590
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001591Conversely, the :meth:`datetime.strptime` class method creates a
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001592:class:`.datetime` object from a string representing a date and time and a
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001593corresponding format string. ``datetime.strptime(date_string, format)`` is
1594equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1595
Sandro Tosi8d38fcf2012-02-18 20:28:35 +01001596For :class:`.time` objects, the format codes for year, month, and day should not
Georg Brandl8ec7f652007-08-15 14:28:01 +00001597be used, as time objects have no such values. If they're used anyway, ``1900``
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001598is substituted for the year, and ``1`` for the month and day.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001599
Skip Montanarofc070d22008-03-15 16:04:45 +00001600For :class:`date` objects, the format codes for hours, minutes, seconds, and
1601microseconds should not be used, as :class:`date` objects have no such
1602values. If they're used anyway, ``0`` is substituted for them.
1603
Georg Brandl8ec7f652007-08-15 14:28:01 +00001604The full set of format codes supported varies across platforms, because Python
1605calls the platform C library's :func:`strftime` function, and platform
Georg Brandl1b1c11d2013-10-13 18:28:25 +02001606variations are common. To see the full set of format codes supported on your
1607platform, consult the :manpage:`strftime(3)` documentation.
Georg Brandle40a6a82007-12-08 11:23:13 +00001608
1609The following is a list of all the format codes that the C standard (1989
1610version) requires, and these work on all platforms with a standard C
1611implementation. Note that the 1999 version of the C standard added additional
1612format codes.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001613
1614The exact range of years for which :meth:`strftime` works also varies across
1615platforms. Regardless of platform, years before 1900 cannot be used.
1616
David Wolever73480ef2013-04-13 19:12:58 -04001617+-----------+--------------------------------+------------------------+-------+
1618| Directive | Meaning | Example | Notes |
1619+===========+================================+========================+=======+
David Woleverc7953ef2013-04-13 20:50:24 -04001620| ``%a`` | Weekday as locale's || Sun, Mon, ..., Sat | \(1) |
1621| | abbreviated name. | (en_US); | |
1622| | || So, Mo, ..., Sa | |
David Woleverdb6d10a2013-05-23 17:23:49 -04001623| | | (de_DE) | |
David Wolever73480ef2013-04-13 19:12:58 -04001624+-----------+--------------------------------+------------------------+-------+
David Woleverc7953ef2013-04-13 20:50:24 -04001625| ``%A`` | Weekday as locale's full name. || Sunday, Monday, ..., | \(1) |
1626| | | Saturday (en_US); | |
1627| | || Sonntag, Montag, ..., | |
David Woleverdb6d10a2013-05-23 17:23:49 -04001628| | | Samstag (de_DE) | |
David Wolever73480ef2013-04-13 19:12:58 -04001629+-----------+--------------------------------+------------------------+-------+
1630| ``%w`` | Weekday as a decimal number, | 0, 1, ..., 6 | |
1631| | where 0 is Sunday and 6 is | | |
1632| | Saturday. | | |
1633+-----------+--------------------------------+------------------------+-------+
1634| ``%d`` | Day of the month as a | 01, 02, ..., 31 | |
1635| | zero-padded decimal number. | | |
1636+-----------+--------------------------------+------------------------+-------+
David Woleverc7953ef2013-04-13 20:50:24 -04001637| ``%b`` | Month as locale's abbreviated || Jan, Feb, ..., Dec | \(1) |
1638| | name. | (en_US); | |
1639| | || Jan, Feb, ..., Dez | |
David Woleverdb6d10a2013-05-23 17:23:49 -04001640| | | (de_DE) | |
David Wolever73480ef2013-04-13 19:12:58 -04001641+-----------+--------------------------------+------------------------+-------+
David Woleverc7953ef2013-04-13 20:50:24 -04001642| ``%B`` | Month as locale's full name. || January, February, | \(1) |
1643| | | ..., December (en_US);| |
1644| | || Januar, Februar, ..., | |
David Woleverdb6d10a2013-05-23 17:23:49 -04001645| | | Dezember (de_DE) | |
David Wolever73480ef2013-04-13 19:12:58 -04001646+-----------+--------------------------------+------------------------+-------+
1647| ``%m`` | Month as a zero-padded | 01, 02, ..., 12 | |
1648| | decimal number. | | |
1649+-----------+--------------------------------+------------------------+-------+
1650| ``%y`` | Year without century as a | 00, 01, ..., 99 | |
1651| | zero-padded decimal number. | | |
1652+-----------+--------------------------------+------------------------+-------+
1653| ``%Y`` | Year with century as a decimal | 1970, 1988, 2001, 2013 | |
1654| | number. | | |
1655+-----------+--------------------------------+------------------------+-------+
1656| ``%H`` | Hour (24-hour clock) as a | 00, 01, ..., 23 | |
1657| | zero-padded decimal number. | | |
1658+-----------+--------------------------------+------------------------+-------+
1659| ``%I`` | Hour (12-hour clock) as a | 01, 02, ..., 12 | |
1660| | zero-padded decimal number. | | |
1661+-----------+--------------------------------+------------------------+-------+
David Woleverc7953ef2013-04-13 20:50:24 -04001662| ``%p`` | Locale's equivalent of either || AM, PM (en_US); | \(1), |
David Woleverdb6d10a2013-05-23 17:23:49 -04001663| | AM or PM. || am, pm (de_DE) | \(2) |
David Wolever73480ef2013-04-13 19:12:58 -04001664+-----------+--------------------------------+------------------------+-------+
1665| ``%M`` | Minute as a zero-padded | 00, 01, ..., 59 | |
1666| | decimal number. | | |
1667+-----------+--------------------------------+------------------------+-------+
David Wolevera80d3a02013-08-14 14:33:54 -04001668| ``%S`` | Second as a zero-padded | 00, 01, ..., 59 | \(3) |
David Wolever73480ef2013-04-13 19:12:58 -04001669| | decimal number. | | |
1670+-----------+--------------------------------+------------------------+-------+
David Woleverc7953ef2013-04-13 20:50:24 -04001671| ``%f`` | Microsecond as a decimal | 000000, 000001, ..., | \(4) |
David Wolever73480ef2013-04-13 19:12:58 -04001672| | number, zero-padded on the | 999999 | |
1673| | left. | | |
1674+-----------+--------------------------------+------------------------+-------+
David Woleverc7953ef2013-04-13 20:50:24 -04001675| ``%z`` | UTC offset in the form +HHMM | (empty), +0000, -0400, | \(5) |
David Wolever73480ef2013-04-13 19:12:58 -04001676| | or -HHMM (empty string if the | +1030 | |
1677| | the object is naive). | | |
1678+-----------+--------------------------------+------------------------+-------+
1679| ``%Z`` | Time zone name (empty string | (empty), UTC, EST, CST | |
1680| | if the object is naive). | | |
1681+-----------+--------------------------------+------------------------+-------+
David Woleverc7953ef2013-04-13 20:50:24 -04001682| ``%j`` | Day of the year as a | 001, 002, ..., 366 | |
1683| | zero-padded decimal number. | | |
1684+-----------+--------------------------------+------------------------+-------+
1685| ``%U`` | Week number of the year | 00, 01, ..., 53 | \(6) |
David Wolever73480ef2013-04-13 19:12:58 -04001686| | (Sunday as the first day of | | |
1687| | the week) as a zero padded | | |
1688| | decimal number. All days in a | | |
1689| | new year preceding the first | | |
1690| | Sunday are considered to be in | | |
1691| | week 0. | | |
1692+-----------+--------------------------------+------------------------+-------+
David Woleverc7953ef2013-04-13 20:50:24 -04001693| ``%W`` | Week number of the year | 00, 01, ..., 53 | \(6) |
David Wolever73480ef2013-04-13 19:12:58 -04001694| | (Monday as the first day of | | |
1695| | the week) as a decimal number. | | |
1696| | All days in a new year | | |
1697| | preceding the first Monday | | |
1698| | are considered to be in | | |
1699| | week 0. | | |
1700+-----------+--------------------------------+------------------------+-------+
David Woleverc7953ef2013-04-13 20:50:24 -04001701| ``%c`` | Locale's appropriate date and || Tue Aug 16 21:30:00 | \(1) |
David Woleverdb6d10a2013-05-23 17:23:49 -04001702| | time representation. | 1988 (en_US); | |
David Woleverc7953ef2013-04-13 20:50:24 -04001703| | || Di 16 Aug 21:30:00 | |
David Woleverdb6d10a2013-05-23 17:23:49 -04001704| | | 1988 (de_DE) | |
David Wolever73480ef2013-04-13 19:12:58 -04001705+-----------+--------------------------------+------------------------+-------+
David Woleverdb6d10a2013-05-23 17:23:49 -04001706| ``%x`` | Locale's appropriate date || 08/16/88 (None); | \(1) |
1707| | representation. || 08/16/1988 (en_US); | |
1708| | || 16.08.1988 (de_DE) | |
David Wolever73480ef2013-04-13 19:12:58 -04001709+-----------+--------------------------------+------------------------+-------+
David Woleverdb6d10a2013-05-23 17:23:49 -04001710| ``%X`` | Locale's appropriate time || 21:30:00 (en_US); | \(1) |
1711| | representation. || 21:30:00 (de_DE) | |
David Wolever73480ef2013-04-13 19:12:58 -04001712+-----------+--------------------------------+------------------------+-------+
1713| ``%%`` | A literal ``'%'`` character. | % | |
1714+-----------+--------------------------------+------------------------+-------+
Georg Brandl8ec7f652007-08-15 14:28:01 +00001715
Georg Brandle40a6a82007-12-08 11:23:13 +00001716Notes:
1717
1718(1)
David Woleverc7953ef2013-04-13 20:50:24 -04001719 Because the format depends on the current locale, care should be taken when
1720 making assumptions about the output value. Field orderings will vary (for
1721 example, "month/day/year" versus "day/month/year"), and the output may
David Woleverbd9cbf02013-05-23 17:42:14 -04001722 contain Unicode characters encoded using the locale's default encoding (for
Georg Brandlb64f40f2013-10-29 08:05:10 +01001723 example, if the current locale is ``ja_JP``, the default encoding could be
David Woleverbd9cbf02013-05-23 17:42:14 -04001724 any one of ``eucJP``, ``SJIS``, or ``utf-8``; use :meth:`locale.getlocale`
1725 to determine the current locale's encoding).
Skip Montanarofc070d22008-03-15 16:04:45 +00001726
1727(2)
Georg Brandl6cbb7f92010-01-17 08:42:30 +00001728 When used with the :meth:`strptime` method, the ``%p`` directive only affects
Georg Brandle40a6a82007-12-08 11:23:13 +00001729 the output hour field if the ``%I`` directive is used to parse the hour.
1730
Skip Montanarofc070d22008-03-15 16:04:45 +00001731(3)
David Wolevera80d3a02013-08-14 14:33:54 -04001732 Unlike the :mod:`time` module, the :mod:`datetime` module does not support
1733 leap seconds.
Georg Brandle40a6a82007-12-08 11:23:13 +00001734
Skip Montanarofc070d22008-03-15 16:04:45 +00001735(4)
David Wolever73480ef2013-04-13 19:12:58 -04001736 ``%f`` is an extension to the set of format characters in the C standard
1737 (but implemented separately in datetime objects, and therefore always
1738 available). When used with the :meth:`strptime` method, the ``%f``
David Wolever452dd382013-08-12 15:50:10 -04001739 directive accepts from one to six digits and zero pads on the right.
David Wolever73480ef2013-04-13 19:12:58 -04001740
1741 .. versionadded:: 2.6
Georg Brandle40a6a82007-12-08 11:23:13 +00001742
Skip Montanarofc070d22008-03-15 16:04:45 +00001743(5)
David Wolever73480ef2013-04-13 19:12:58 -04001744 For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1745 strings.
1746
1747 For an aware object:
1748
1749 ``%z``
1750 :meth:`utcoffset` is transformed into a 5-character string of the form
1751 +HHMM or -HHMM, where HH is a 2-digit string giving the number of UTC
1752 offset hours, and MM is a 2-digit string giving the number of UTC offset
1753 minutes. For example, if :meth:`utcoffset` returns
1754 ``timedelta(hours=-3, minutes=-30)``, ``%z`` is replaced with the string
1755 ``'-0330'``.
1756
1757 ``%Z``
1758 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty
1759 string. Otherwise ``%Z`` is replaced by the returned value, which must
1760 be a string.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001761
David Woleverc7953ef2013-04-13 20:50:24 -04001762(6)
David Wolever73480ef2013-04-13 19:12:58 -04001763 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used
1764 in calculations when the day of the week and the year are specified.
R David Murray089d4d42012-05-14 22:32:44 -04001765
1766
1767.. rubric:: Footnotes
1768
1769.. [#] If, that is, we ignore the effects of Relativity