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