Update for release.
[python/dscho.git] / Doc / lib / libdatetime.tex
blobc8b251f0f06fc8df30a0d0d4ae0a15757917e54d
1 % XXX what order should the types be discussed in?
3 \section{\module{datetime} ---
4 Basic date and time types}
6 \declaremodule{builtin}{datetime}
7 \modulesynopsis{Basic date and time types.}
8 \moduleauthor{Tim Peters}{tim@zope.com}
9 \sectionauthor{Tim Peters}{tim@zope.com}
10 \sectionauthor{A.M. Kuchling}{amk@amk.ca}
11 \sectionauthor{Raymond D. Hettinger}{python@rcn.com}
13 \versionadded{2.3}
16 The \module{datetime} module supplies classes for manipulating dates
17 and times in both simple and complex ways. While date and time
18 arithmetic is supported, the focus of the implementation is on
19 efficient member extraction for output formatting and manipulation.
21 There are two kinds of date and time objects: ``naive'' and ``aware''.
22 This distinction refers to whether the object has any notion of time
23 zone, daylight saving time, or other kind of algorithmic or political
24 time adjustment. Whether a naive \class{datetime} object represents
25 Coordinated Universal Time (UTC), local time, or time in some other
26 timezone is purely up to the program, just like it's up to the program
27 whether a particular number represents meters, miles, or mass. Naive
28 \class{datetime} objects are easy to understand and to work with, at
29 the cost of ignoring some aspects of reality.
31 For applications requiring more, \class{datetime} and \class{time}
32 objects have an optional time zone information member,
33 \member{tzinfo}, that can contain an instance of a subclass of
34 the abstract \class{tzinfo} class. These \class{tzinfo} objects
35 capture information about the offset from UTC time, the time zone
36 name, and whether Daylight Saving Time is in effect. Note that no
37 concrete \class{tzinfo} classes are supplied by the \module{datetime}
38 module. Instead, they provide a framework for incorporating the level
39 of detail an application may require. The rules for time adjustment across
40 the world are more political than rational, and there is no standard
41 suitable for every application.
43 The \module{datetime} module exports the following constants:
45 \begin{datadesc}{MINYEAR}
46 The smallest year number allowed in a \class{date} or
47 \class{datetime} object. \constant{MINYEAR}
48 is \code{1}.
49 \end{datadesc}
51 \begin{datadesc}{MAXYEAR}
52 The largest year number allowed in a \class{date} or \class{datetime}
53 object. \constant{MAXYEAR} is \code{9999}.
54 \end{datadesc}
56 \begin{seealso}
57 \seemodule{calendar}{General calendar related functions.}
58 \seemodule{time}{Time access and conversions.}
59 \end{seealso}
61 \subsection{Available Types}
63 \begin{classdesc*}{date}
64 An idealized naive date, assuming the current Gregorian calendar
65 always was, and always will be, in effect.
66 Attributes: \member{year}, \member{month}, and \member{day}.
67 \end{classdesc*}
69 \begin{classdesc*}{time}
70 An idealized time, independent of any particular day, assuming
71 that every day has exactly 24*60*60 seconds (there is no notion
72 of "leap seconds" here).
73 Attributes: \member{hour}, \member{minute}, \member{second},
74 \member{microsecond}, and \member{tzinfo}.
75 \end{classdesc*}
77 \begin{classdesc*}{datetime}
78 A combination of a date and a time.
79 Attributes: \member{year}, \member{month}, \member{day},
80 \member{hour}, \member{minute}, \member{second},
81 \member{microsecond}, and \member{tzinfo}.
82 \end{classdesc*}
84 \begin{classdesc*}{timedelta}
85 A duration expressing the difference between two \class{date},
86 \class{time}, or \class{datetime} instances to microsecond
87 resolution.
88 \end{classdesc*}
90 \begin{classdesc*}{tzinfo}
91 An abstract base class for time zone information objects. These
92 are used by the \class{datetime} and \class{time} classes to
93 provide a customizable notion of time adjustment (for example, to
94 account for time zone and/or daylight saving time).
95 \end{classdesc*}
97 Objects of these types are immutable.
99 Objects of the \class{date} type are always naive.
101 An object \var{d} of type \class{time} or \class{datetime} may be
102 naive or aware. \var{d} is aware if \code{\var{d}.tzinfo} is not
103 \code{None} and \code{\var{d}.tzinfo.utcoffset(\var{d})} does not return
104 \code{None}. If \code{\var{d}.tzinfo} is \code{None}, or if
105 \code{\var{d}.tzinfo} is not \code{None} but
106 \code{\var{d}.tzinfo.utcoffset(\var{d})} returns \code{None}, \var{d}
107 is naive.
109 The distinction between naive and aware doesn't apply to
110 \code{timedelta} objects.
112 Subclass relationships:
114 \begin{verbatim}
115 object
116 timedelta
117 tzinfo
118 time
119 date
120 datetime
121 \end{verbatim}
123 \subsection{\class{timedelta} Objects \label{datetime-timedelta}}
125 A \class{timedelta} object represents a duration, the difference
126 between two dates or times.
128 \begin{classdesc}{timedelta}{days=0, seconds=0, microseconds=0,
129 milliseconds=0, minutes=0, hours=0, weeks=0}
131 All arguments are optional. Arguments may be ints, longs, or floats,
132 and may be positive or negative.
134 Only \var{days}, \var{seconds} and \var{microseconds} are stored
135 internally. Arguments are converted to those units:
137 \begin{itemize}
138 \item A millisecond is converted to 1000 microseconds.
139 \item A minute is converted to 60 seconds.
140 \item An hour is converted to 3600 seconds.
141 \item A week is converted to 7 days.
142 \end{itemize}
144 and days, seconds and microseconds are then normalized so that the
145 representation is unique, with
147 \begin{itemize}
148 \item \code{0 <= \var{microseconds} < 1000000}
149 \item \code{0 <= \var{seconds} < 3600*24} (the number of seconds in one day)
150 \item \code{-999999999 <= \var{days} <= 999999999}
151 \end{itemize}
153 If any argument is a float and there are fractional microseconds,
154 the fractional microseconds left over from all arguments are combined
155 and their sum is rounded to the nearest microsecond. If no
156 argument is a float, the conversion and normalization processes
157 are exact (no information is lost).
159 If the normalized value of days lies outside the indicated range,
160 \exception{OverflowError} is raised.
162 Note that normalization of negative values may be surprising at first.
163 For example,
165 \begin{verbatim}
166 >>> d = timedelta(microseconds=-1)
167 >>> (d.days, d.seconds, d.microseconds)
168 (-1, 86399, 999999)
169 \end{verbatim}
170 \end{classdesc}
172 Class attributes are:
174 \begin{memberdesc}{min}
175 The most negative \class{timedelta} object,
176 \code{timedelta(-999999999)}.
177 \end{memberdesc}
179 \begin{memberdesc}{max}
180 The most positive \class{timedelta} object,
181 \code{timedelta(days=999999999, hours=23, minutes=59, seconds=59,
182 microseconds=999999)}.
183 \end{memberdesc}
185 \begin{memberdesc}{resolution}
186 The smallest possible difference between non-equal
187 \class{timedelta} objects, \code{timedelta(microseconds=1)}.
188 \end{memberdesc}
190 Note that, because of normalization, \code{timedelta.max} \textgreater
191 \code{-timedelta.min}. \code{-timedelta.max} is not representable as
192 a \class{timedelta} object.
194 Instance attributes (read-only):
196 \begin{tableii}{c|l}{code}{Attribute}{Value}
197 \lineii{days}{Between -999999999 and 999999999 inclusive}
198 \lineii{seconds}{Between 0 and 86399 inclusive}
199 \lineii{microseconds}{Between 0 and 999999 inclusive}
200 \end{tableii}
202 Supported operations:
204 % XXX this table is too wide!
205 \begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
206 \lineiii{\var{t1} = \var{t2} + \var{t3}}
207 {Sum of \var{t2} and \var{t3}.
208 Afterwards \var{t1}-\var{t2} == \var{t3} and \var{t1}-\var{t3}
209 == \var{t2} are true.}
210 {(1)}
211 \lineiii{\var{t1} = \var{t2} - \var{t3}}
212 {Difference of \var{t2} and \var{t3}. Afterwards \var{t1} ==
213 \var{t2} - \var{t3} and \var{t2} == \var{t1} + \var{t3} are
214 true.}
215 {(1)}
216 \lineiii{\var{t1} = \var{t2} * \var{i} or \var{t1} = \var{i} * \var{t2}}
217 {Delta multiplied by an integer or long.
218 Afterwards \var{t1} // i == \var{t2} is true,
219 provided \code{i != 0}.
220 In general, \var{t1} * i == \var{t1} * (i-1) + \var{t1} is true.}
221 {(1)}
222 \lineiii{\var{t1} = \var{t2} // \var{i}}
223 {The floor is computed and the remainder (if any) is thrown away.}
224 {(3)}
225 \lineiii{+\var{t1}}
226 {Returns a \class{timedelta} object with the same value.}
227 {(2)}
228 \lineiii{-\var{t1}}
229 {equivalent to \class{timedelta}(-\var{t1.days}, -\var{t1.seconds},
230 -\var{t1.microseconds}), and to \var{t1}* -1.}
231 {(1)(4)}
232 \lineiii{abs(\var{t})}
233 {equivalent to +\var{t} when \code{t.days >= 0}, and to
234 -\var{t} when \code{t.days < 0}.}
235 {(2)}
236 \end{tableiii}
237 \noindent
238 Notes:
240 \begin{description}
241 \item[(1)]
242 This is exact, but may overflow.
244 \item[(2)]
245 This is exact, and cannot overflow.
247 \item[(3)]
248 Division by 0 raises \exception{ZeroDivisionError}.
250 \item[(4)]
251 -\var{timedelta.max} is not representable as a \class{timedelta} object.
252 \end{description}
254 In addition to the operations listed above \class{timedelta} objects
255 support certain additions and subtractions with \class{date} and
256 \class{datetime} objects (see below).
258 Comparisons of \class{timedelta} objects are supported with the
259 \class{timedelta} object representing the smaller duration considered
260 to be the smaller timedelta.
262 \class{timedelta} objects are hashable (usable as dictionary keys),
263 support efficient pickling, and in Boolean contexts, a \class{timedelta}
264 object is considered to be true if and only if it isn't equal to
265 \code{timedelta(0)}.
268 \subsection{\class{date} Objects \label{datetime-date}}
270 A \class{date} object represents a date (year, month and day) in an idealized
271 calendar, the current Gregorian calendar indefinitely extended in both
272 directions. January 1 of year 1 is called day number 1, January 2 of year
273 1 is called day number 2, and so on. This matches the definition of the
274 "proleptic Gregorian" calendar in Dershowitz and Reingold's book
275 \citetitle{Calendrical Calculations}, where it's the base calendar for all
276 computations. See the book for algorithms for converting between
277 proleptic Gregorian ordinals and many other calendar systems.
279 \begin{classdesc}{date}{year, month, day}
280 All arguments are required. Arguments may be ints or longs, in the
281 following ranges:
283 \begin{itemize}
284 \item \code{MINYEAR <= \var{year} <= MAXYEAR}
285 \item \code{1 <= \var{month} <= 12}
286 \item \code{1 <= \var{day} <= number of days in the given month and year}
287 \end{itemize}
289 If an argument outside those ranges is given, \exception{ValueError}
290 is raised.
291 \end{classdesc}
293 Other constructors, all class methods:
295 \begin{methoddesc}{today}{}
296 Return the current local date. This is equivalent to
297 \code{date.fromtimestamp(time.time())}.
298 \end{methoddesc}
300 \begin{methoddesc}{fromtimestamp}{timestamp}
301 Return the local date corresponding to the POSIX timestamp, such
302 as is returned by \function{time.time()}. This may raise
303 \exception{ValueError}, if the timestamp is out of the range of
304 values supported by the platform C \cfunction{localtime()}
305 function. It's common for this to be restricted to years from 1970
306 through 2038. Note that on non-POSIX systems that include leap
307 seconds in their notion of a timestamp, leap seconds are ignored by
308 \method{fromtimestamp()}.
309 \end{methoddesc}
311 \begin{methoddesc}{fromordinal}{ordinal}
312 Return the date corresponding to the proleptic Gregorian ordinal,
313 where January 1 of year 1 has ordinal 1. \exception{ValueError} is
314 raised unless \code{1 <= \var{ordinal} <= date.max.toordinal()}.
315 For any date \var{d}, \code{date.fromordinal(\var{d}.toordinal()) ==
316 \var{d}}.
317 \end{methoddesc}
319 Class attributes:
321 \begin{memberdesc}{min}
322 The earliest representable date, \code{date(MINYEAR, 1, 1)}.
323 \end{memberdesc}
325 \begin{memberdesc}{max}
326 The latest representable date, \code{date(MAXYEAR, 12, 31)}.
327 \end{memberdesc}
329 \begin{memberdesc}{resolution}
330 The smallest possible difference between non-equal date
331 objects, \code{timedelta(days=1)}.
332 \end{memberdesc}
334 Instance attributes (read-only):
336 \begin{memberdesc}{year}
337 Between \constant{MINYEAR} and \constant{MAXYEAR} inclusive.
338 \end{memberdesc}
340 \begin{memberdesc}{month}
341 Between 1 and 12 inclusive.
342 \end{memberdesc}
344 \begin{memberdesc}{day}
345 Between 1 and the number of days in the given month of the given
346 year.
347 \end{memberdesc}
349 Supported operations:
351 % XXX rewrite to be a table
352 \begin{itemize}
353 \item
354 date1 + timedelta -> date2
356 timedelta + date1 -> date2
358 date2 is timedelta.days days removed from the date1, moving forward
359 in time if timedelta.days > 0, or backward if timedetla.days < 0.
360 date2 - date1 == timedelta.days after. timedelta.seconds and
361 timedelta.microseconds are ignored. \exception{OverflowError} is
362 raised if date2.year would be smaller than \constant{MINYEAR} or
363 larger than \constant{MAXYEAR}.
365 \item
366 date1 - timedelta -> date2
368 Computes the date2 such that date2 + timedelta == date1. This
369 isn't quite equivalent to date1 + (-timedelta), because -timedelta
370 in isolation can overflow in cases where date1 - timedelta does
371 not. timedelta.seconds and timedelta.microseconds are ignored.
373 \item
374 date1 - date2 -> timedelta
376 This is exact, and cannot overflow. timedelta.seconds and
377 timedelta.microseconds are 0, and date2 + timedelta == date1
378 after.
380 \item
381 comparison of date to date, where date1 is considered less than
382 date2 when date1 precedes date2 in time. In other words,
383 date1 < date2 if and only if date1.toordinal() < date2.toordinal().
384 \note{In order to stop comparison from falling back to the default
385 scheme of comparing object addresses, date comparison
386 normally raises \exception{TypeError} if the other comparand
387 isn't also a \class{date} object. However, \code{NotImplemented}
388 is returned instead if the other comparand has a
389 \method{timetuple} attribute. This hook gives other kinds of
390 date objects a chance at implementing mixed-type comparison.}
393 \item
394 hash, use as dict key
396 \item
397 efficient pickling
399 \item
400 in Boolean contexts, all \class{date} objects are considered to be true
401 \end{itemize}
403 Instance methods:
405 \begin{methoddesc}{replace}{year, month, day}
406 Return a date with the same value, except for those members given
407 new values by whichever keyword arguments are specified. For
408 example, if \code{d == date(2002, 12, 31)}, then
409 \code{d.replace(day=26) == date(2000, 12, 26)}.
410 \end{methoddesc}
412 \begin{methoddesc}{timetuple}{}
413 Return a 9-element tuple of the form returned by
414 \function{time.localtime()}. The hours, minutes and seconds are
415 0, and the DST flag is -1.
416 \code{\var{d}.timetuple()} is equivalent to
417 \code{(\var{d}.year, \var{d}.month, \var{d}.day,
418 0, 0, 0, \# h, m, s
419 \var{d}.weekday(), \# 0 is Monday
420 \var{d}.toordinal() - date(\var{d}.year, 1, 1).toordinal() + 1,
421 \# day of year
422 -1)}
423 \end{methoddesc}
425 \begin{methoddesc}{toordinal}{}
426 Return the proleptic Gregorian ordinal of the date, where January 1
427 of year 1 has ordinal 1. For any \class{date} object \var{d},
428 \code{date.fromordinal(\var{d}.toordinal()) == \var{d}}.
429 \end{methoddesc}
431 \begin{methoddesc}{weekday}{}
432 Return the day of the week as an integer, where Monday is 0 and
433 Sunday is 6. For example, date(2002, 12, 4).weekday() == 2, a
434 Wednesday.
435 See also \method{isoweekday()}.
436 \end{methoddesc}
438 \begin{methoddesc}{isoweekday}{}
439 Return the day of the week as an integer, where Monday is 1 and
440 Sunday is 7. For example, date(2002, 12, 4).isoweekday() == 3, a
441 Wednesday.
442 See also \method{weekday()}, \method{isocalendar()}.
443 \end{methoddesc}
445 \begin{methoddesc}{isocalendar}{}
446 Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
448 The ISO calendar is a widely used variant of the Gregorian calendar.
449 See \url{http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm}
450 for a good explanation.
452 The ISO year consists of 52 or 53 full weeks, and where a week starts
453 on a Monday and ends on a Sunday. The first week of an ISO year is
454 the first (Gregorian) calendar week of a year containing a Thursday.
455 This is called week number 1, and the ISO year of that Thursday is
456 the same as its Gregorian year.
458 For example, 2004 begins on a Thursday, so the first week of ISO
459 year 2004 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan
460 2004, so that
462 date(2003, 12, 29).isocalendar() == (2004, 1, 1)
463 date(2004, 1, 4).isocalendar() == (2004, 1, 7)
464 \end{methoddesc}
466 \begin{methoddesc}{isoformat}{}
467 Return a string representing the date in ISO 8601 format,
468 'YYYY-MM-DD'. For example,
469 date(2002, 12, 4).isoformat() == '2002-12-04'.
470 \end{methoddesc}
472 \begin{methoddesc}{__str__}{}
473 For a date \var{d}, \code{str(\var{d})} is equivalent to
474 \code{\var{d}.isoformat()}.
475 \end{methoddesc}
477 \begin{methoddesc}{ctime}{}
478 Return a string representing the date, for example
479 date(2002, 12, 4).ctime() == 'Wed Dec 4 00:00:00 2002'.
480 \code{\var{d}.ctime()} is equivalent to
481 \code{time.ctime(time.mktime(\var{d}.timetuple()))}
482 on platforms where the native C \cfunction{ctime()} function
483 (which \function{time.ctime()} invokes, but which
484 \method{date.ctime()} does not invoke) conforms to the C standard.
485 \end{methoddesc}
487 \begin{methoddesc}{strftime}{format}
488 Return a string representing the date, controlled by an explicit
489 format string. Format codes referring to hours, minutes or seconds
490 will see 0 values.
491 See the section on \method{strftime()} behavior.
492 \end{methoddesc}
495 \subsection{\class{datetime} Objects \label{datetime-datetime}}
497 A \class{datetime} object is a single object containing all the
498 information from a \class{date} object and a \class{time} object. Like a
499 \class{date} object, \class{datetime} assumes the current Gregorian
500 calendar extended in both directions; like a time object,
501 \class{datetime} assumes there are exactly 3600*24 seconds in every
502 day.
504 Constructor:
506 \begin{classdesc}{datetime}{year, month, day,
507 hour=0, minute=0, second=0, microsecond=0,
508 tzinfo=None}
509 The year, month and day arguments are required. \var{tzinfo} may
510 be \code{None}, or an instance of a \class{tzinfo} subclass. The
511 remaining arguments may be ints or longs, in the following ranges:
513 \begin{itemize}
514 \item \code{MINYEAR <= \var{year} <= MAXYEAR}
515 \item \code{1 <= \var{month} <= 12}
516 \item \code{1 <= \var{day} <= number of days in the given month and year}
517 \item \code{0 <= \var{hour} < 24}
518 \item \code{0 <= \var{minute} < 60}
519 \item \code{0 <= \var{second} < 60}
520 \item \code{0 <= \var{microsecond} < 1000000}
521 \end{itemize}
523 If an argument outside those ranges is given,
524 \exception{ValueError} is raised.
525 \end{classdesc}
527 Other constructors, all class methods:
529 \begin{methoddesc}{today}{}
530 Return the current local datetime, with \member{tzinfo} \code{None}.
531 This is equivalent to
532 \code{datetime.fromtimestamp(time.time())}.
533 See also \method{now()}, \method{fromtimestamp()}.
534 \end{methoddesc}
536 \begin{methoddesc}{now(tz=None)}{}
537 Return the current local date and time. If optional argument
538 \var{tz} is \code{None} or not specified, this is like
539 \method{today()}, but, if possible, supplies more precision than can
540 be gotten from going through a \function{time.time()} timestamp (for
541 example, this may be possible on platforms supplying the C
542 \cfunction{gettimeofday()} function).
544 Else \var{tz} must be an instance of a class \class{tzinfo} subclass,
545 and the current date and time are converted to \var{tz}'s time
546 zone. In this case the result is equivalent to
547 \code{\var{tz}.fromutc(datetime.utcnow().replace(tzinfo=\var{tz}))}.
548 See also \method{today()}, \method{utcnow()}.
549 \end{methoddesc}
551 \begin{methoddesc}{utcnow}{}
552 Return the current UTC date and time, with \member{tzinfo} \code{None}.
553 This is like \method{now()}, but returns the current UTC date and time,
554 as a naive \class{datetime} object.
555 See also \method{now()}.
556 \end{methoddesc}
558 \begin{methoddesc}{fromtimestamp}{timestamp, tz=None}
559 Return the local date and time corresponding to the \POSIX{}
560 timestamp, such as is returned by \function{time.time()}.
561 If optional argument \var{tz} is \code{None} or not specified, the
562 timestamp is converted to the platform's local date and time, and
563 the returned \class{datetime} object is naive.
565 Else \var{tz} must be an instance of a class \class{tzinfo} subclass,
566 and the timestamp is converted to \var{tz}'s time zone. In this case
567 the result is equivalent to
568 \code{\var{tz}.fromutc(datetime.utcfromtimestamp(\var{timestamp}).replace(tzinfo=\var{tz}))}.
570 \method{fromtimestamp()} may raise \exception{ValueError}, if the
571 timestamp is out of the range of values supported by the platform C
572 \cfunction{localtime()} or \cfunction{gmtime()} functions. It's common
573 for this to be restricted to years in 1970 through 2038.
574 Note that on non-POSIX systems that include leap seconds in their
575 notion of a timestamp, leap seconds are ignored by
576 \method{fromtimestamp()}, and then it's possible to have two timestamps
577 differing by a second that yield identical \class{datetime} objects.
578 See also \method{utcfromtimestamp()}.
579 \end{methoddesc}
581 \begin{methoddesc}{utcfromtimestamp}{timestamp}
582 Return the UTC \class{datetime} corresponding to the \POSIX{}
583 timestamp, with \member{tzinfo} \code{None}.
584 This may raise \exception{ValueError}, if the
585 timestamp is out of the range of values supported by the platform
586 C \cfunction{gmtime()} function. It's common for this to be
587 restricted to years in 1970 through 2038.
588 See also \method{fromtimestamp()}.
589 \end{methoddesc}
591 \begin{methoddesc}{fromordinal}{ordinal}
592 Return the \class{datetime} corresponding to the proleptic
593 Gregorian ordinal, where January 1 of year 1 has ordinal 1.
594 \exception{ValueError} is raised unless 1 <= ordinal <=
595 datetime.max.toordinal(). The hour, minute, second and
596 microsecond of the result are all 0,
597 and \member{tzinfo} is \code{None}.
598 \end{methoddesc}
600 \begin{methoddesc}{combine}{date, time}
601 Return a new \class{datetime} object whose date members are
602 equal to the given \class{date} object's, and whose time
603 and \member{tzinfo} members are equal to the given \class{time} object's.
604 For any \class{datetime} object \var{d}, \code{\var{d} ==
605 datetime.combine(\var{d}.date(), \var{d}.timetz())}. If date is a
606 \class{datetime} object, its time and \member{tzinfo} members are
607 ignored.
608 \end{methoddesc}
610 Class attributes:
612 \begin{memberdesc}{min}
613 The earliest representable \class{datetime},
614 \code{datetime(MINYEAR, 1, 1, tzinfo=None)}.
615 \end{memberdesc}
617 \begin{memberdesc}{max}
618 The latest representable \class{datetime},
619 \code{datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=None)}.
620 \end{memberdesc}
622 \begin{memberdesc}{resolution}
623 The smallest possible difference between non-equal \class{datetime}
624 objects, \code{timedelta(microseconds=1)}.
625 \end{memberdesc}
627 Instance attributes (read-only):
629 \begin{memberdesc}{year}
630 Between \constant{MINYEAR} and \constant{MAXYEAR} inclusive.
631 \end{memberdesc}
633 \begin{memberdesc}{month}
634 Between 1 and 12 inclusive.
635 \end{memberdesc}
637 \begin{memberdesc}{day}
638 Between 1 and the number of days in the given month of the given
639 year.
640 \end{memberdesc}
642 \begin{memberdesc}{hour}
643 In \code{range(24)}.
644 \end{memberdesc}
646 \begin{memberdesc}{minute}
647 In \code{range(60)}.
648 \end{memberdesc}
650 \begin{memberdesc}{second}
651 In \code{range(60)}.
652 \end{memberdesc}
654 \begin{memberdesc}{microsecond}
655 In \code{range(1000000)}.
656 \end{memberdesc}
658 \begin{memberdesc}{tzinfo}
659 The object passed as the \var{tzinfo} argument to the
660 \class{datetime} constructor, or \code{None} if none was passed.
661 \end{memberdesc}
663 Supported operations:
665 \begin{itemize}
666 \item
667 datetime1 + timedelta -> datetime2
669 timedelta + datetime1 -> datetime2
671 datetime2 is a duration of timedelta removed from datetime1, moving
672 forward in time if timedelta.days > 0, or backward if
673 timedelta.days < 0. The result has the same \member{tzinfo} member
674 as the input datetime, and datetime2 - datetime1 == timedelta after.
675 \exception{OverflowError} is raised if datetime2.year would be
676 smaller than \constant{MINYEAR} or larger than \constant{MAXYEAR}.
677 Note that no time zone adjustments are done even if the input is an
678 aware object.
680 \item
681 datetime1 - timedelta -> datetime2
683 Computes the datetime2 such that datetime2 + timedelta == datetime1.
684 As for addition, the result has the same \member{tzinfo} member
685 as the input datetime, and no time zone adjustments are done even
686 if the input is aware.
687 This isn't quite equivalent to datetime1 + (-timedelta), because
688 -timedelta in isolation can overflow in cases where
689 datetime1 - timedelta does not.
691 \item
692 datetime1 - datetime2 -> timedelta
694 Subtraction of a \class{datetime} from a
695 \class{datetime} is defined only if both
696 operands are naive, or if both are aware. If one is aware and the
697 other is naive, \exception{TypeError} is raised.
699 If both are naive, or both are aware and have the same \member{tzinfo}
700 member, the \member{tzinfo} members are ignored, and the result is
701 a \class{timedelta} object \var{t} such that
702 \code{\var{datetime2} + \var{t} == \var{datetime1}}. No time zone
703 adjustments are done in this case.
705 If both are aware and have different \member{tzinfo} members,
706 \code{a-b} acts as if \var{a} and \var{b} were first converted to
707 naive UTC datetimes first. The result is
708 \code{(\var{a}.replace(tzinfo=None) - \var{a}.utcoffset()) -
709 (\var{b}.replace(tzinfo=None) - \var{b}.utcoffset())}
710 except that the implementation never overflows.
712 \item
713 comparison of \class{datetime} to \class{datetime},
714 where \var{a} is considered less than \var{b}
715 when \var{a} precedes \var{b} in time. If one comparand is naive and
716 the other is aware, \exception{TypeError} is raised. If both
717 comparands are aware, and have the same \member{tzinfo} member,
718 the common \member{tzinfo} member is ignored and the base datetimes
719 are compared. If both comparands are aware and have different
720 \member{tzinfo} members, the comparands are first adjusted by
721 subtracting their UTC offsets (obtained from \code{self.utcoffset()}).
722 \note{In order to stop comparison from falling back to the default
723 scheme of comparing object addresses, datetime comparison
724 normally raises \exception{TypeError} if the other comparand
725 isn't also a \class{datetime} object. However,
726 \code{NotImplemented} is returned instead if the other comparand
727 has a \method{timetuple} attribute. This hook gives other
728 kinds of date objects a chance at implementing mixed-type
729 comparison.}
731 \item
732 hash, use as dict key
734 \item
735 efficient pickling
737 \item
738 in Boolean contexts, all \class{datetime} objects are considered
739 to be true
740 \end{itemize}
742 Instance methods:
744 \begin{methoddesc}{date}{}
745 Return \class{date} object with same year, month and day.
746 \end{methoddesc}
748 \begin{methoddesc}{time}{}
749 Return \class{time} object with same hour, minute, second and microsecond.
750 \member{tzinfo} is \code{None}. See also method \method{timetz()}.
751 \end{methoddesc}
753 \begin{methoddesc}{timetz}{}
754 Return \class{time} object with same hour, minute, second, microsecond,
755 and tzinfo members. See also method \method{time()}.
756 \end{methoddesc}
758 \begin{methoddesc}{replace}{year=, month=, day=, hour=, minute=, second=,
759 microsecond=, tzinfo=}
760 Return a datetime with the same members, except for those members given
761 new values by whichever keyword arguments are specified. Note that
762 \code{tzinfo=None} can be specified to create a naive datetime from
763 an aware datetime with no conversion of date and time members.
764 \end{methoddesc}
766 \begin{methoddesc}{astimezone}{tz}
767 Return a \class{datetime} object with new \member{tzinfo} member
768 \var{tz}, adjusting the date and time members so the result is the
769 same UTC time as \var{self}, but in \var{tz}'s local time.
771 \var{tz} must be an instance of a \class{tzinfo} subclass, and its
772 \method{utcoffset()} and \method{dst()} methods must not return
773 \code{None}. \var{self} must be aware (\code{\var{self}.tzinfo} must
774 not be \code{None}, and \code{\var{self}.utcoffset()} must not return
775 \code{None}).
777 If code{\var{self}.tzinfo} is \var{tz},
778 \code{\var{self}.astimezone(\var{tz})} is equal to \var{self}: no
779 adjustment of date or time members is performed.
780 Else the result is local time in time zone \var{tz}, representing the
781 same UTC time as \var{self}: after \code{\var{astz} =
782 \var{dt}.astimezone(\var{tz})},
783 \code{\var{astz} - \var{astz}.utcoffset()} will usually have the same
784 date and time members as \code{\var{dt} - \var{dt}.utcoffset()}.
785 The discussion of class \class{tzinfo} explains the cases at Daylight
786 Saving Time transition boundaries where this cannot be achieved (an issue
787 only if \var{tz} models both standard and daylight time).
789 If you merely want to attach a time zone object \var{tz} to a
790 datetime \var{dt} without adjustment of date and time members,
791 use \code{\var{dt}.replace(tzinfo=\var{tz})}. If
792 you merely want to remove the time zone object from an aware datetime
793 \var{dt} without conversion of date and time members, use
794 \code{\var{dt}.replace(tzinfo=None)}.
796 Note that the default \method{tzinfo.fromutc()} method can be overridden
797 in a \class{tzinfo} subclass to effect the result returned by
798 \method{astimezone()}. Ignoring error cases, \method{astimezone()}
799 acts like:
801 \begin{verbatim}
802 def astimezone(self, tz):
803 if self.tzinfo is tz:
804 return self
805 # Convert self to UTC, and attach the new time zone object.
806 utc = (self - self.utcoffset()).replace(tzinfo=tz)
807 # Convert from UTC to tz's local time.
808 return tz.fromutc(utc)
809 \end{verbatim}
810 \end{methoddesc}
812 \begin{methoddesc}{utcoffset}{}
813 If \member{tzinfo} is \code{None}, returns \code{None}, else
814 returns \code{\var{self}.tzinfo.utcoffset(\var{self})}, and
815 raises an exception if the latter doesn't return \code{None}, or
816 a \class{timedelta} object representing a whole number of minutes
817 with magnitude less than one day.
818 \end{methoddesc}
820 \begin{methoddesc}{dst}{}
821 If \member{tzinfo} is \code{None}, returns \code{None}, else
822 returns \code{\var{self}.tzinfo.dst(\var{self})}, and
823 raises an exception if the latter doesn't return \code{None}, or
824 a \class{timedelta} object representing a whole number of minutes
825 with magnitude less than one day.
826 \end{methoddesc}
828 \begin{methoddesc}{tzname}{}
829 If \member{tzinfo} is \code{None}, returns \code{None}, else
830 returns \code{\var{self}.tzinfo.tzname(\var{self})},
831 raises an exception if the latter doesn't return \code{None} or
832 a string object,
833 \end{methoddesc}
835 \begin{methoddesc}{timetuple}{}
836 Return a 9-element tuple of the form returned by
837 \function{time.localtime()}.
838 \code{\var{d}.timetuple()} is equivalent to
839 \code{(\var{d}.year, \var{d}.month, \var{d}.day,
840 \var{d}.hour, \var{d}.minute, \var{d}.second,
841 \var{d}.weekday(),
842 \var{d}.toordinal() - date(\var{d}.year, 1, 1).toordinal() + 1,
843 dst)}
844 The \member{tm_isdst} flag of the result is set according to
845 the \method{dst()} method: \member{tzinfo} is \code{None} or
846 \method{dst()} returns \code{None},
847 \member{tm_isdst} is set to \code{-1}; else if \method{dst()} returns
848 a non-zero value, \member{tm_isdst} is set to \code{1};
849 else \code{tm_isdst} is set to \code{0}.
850 \end{methoddesc}
852 \begin{methoddesc}{utctimetuple}{}
853 If \class{datetime} instance \var{d} is naive, this is the same as
854 \code{\var{d}.timetuple()} except that \member{tm_isdst} is forced to 0
855 regardless of what \code{d.dst()} returns. DST is never in effect
856 for a UTC time.
858 If \var{d} is aware, \var{d} is normalized to UTC time, by subtracting
859 \code{\var{d}.utcoffset()}, and a timetuple for the
860 normalized time is returned. \member{tm_isdst} is forced to 0.
861 Note that the result's \member{tm_year} member may be
862 \constant{MINYEAR}-1 or \constant{MAXYEAR}+1, if \var{d}.year was
863 \code{MINYEAR} or \code{MAXYEAR} and UTC adjustment spills over a
864 year boundary.
865 \end{methoddesc}
867 \begin{methoddesc}{toordinal}{}
868 Return the proleptic Gregorian ordinal of the date. The same as
869 \code{self.date().toordinal()}.
870 \end{methoddesc}
872 \begin{methoddesc}{weekday}{}
873 Return the day of the week as an integer, where Monday is 0 and
874 Sunday is 6. The same as \code{self.date().weekday()}.
875 See also \method{isoweekday()}.
876 \end{methoddesc}
878 \begin{methoddesc}{isoweekday}{}
879 Return the day of the week as an integer, where Monday is 1 and
880 Sunday is 7. The same as \code{self.date().isoweekday)}.
881 See also \method{weekday()}, \method{isocalendar()}.
882 \end{methoddesc}
884 \begin{methoddesc}{isocalendar}{}
885 Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The
886 same as \code{self.date().isocalendar()}.
887 \end{methoddesc}
889 \begin{methoddesc}{isoformat}{sep='T'}
890 Return a string representing the date and time in ISO 8601 format,
891 YYYY-MM-DDTHH:MM:SS.mmmmmm
892 or, if \member{microsecond} is 0,
893 YYYY-MM-DDTHH:MM:SS
895 If \method{utcoffset()} does not return \code{None}, a 6-character
896 string is appended, giving the UTC offset in (signed) hours and
897 minutes:
898 YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM
899 or, if \member{microsecond} is 0
900 YYYY-MM-DDTHH:MM:SS+HH:MM
902 The optional argument \var{sep} (default \code{'T'}) is a
903 one-character separator, placed between the date and time portions
904 of the result. For example,
906 \begin{verbatim}
907 >>> from datetime import tzinfo, timedelta, datetime
908 >>> class TZ(tzinfo):
909 ... def utcoffset(self, dt): return timedelta(minutes=-399)
911 >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
912 '2002-12-25 00:00:00-06:39'
913 \end{verbatim}
914 \end{methoddesc}
916 \begin{methoddesc}{__str__}{}
917 For a \class{datetime} instance \var{d}, \code{str(\var{d})} is
918 equivalent to \code{\var{d}.isoformat(' ')}.
919 \end{methoddesc}
921 \begin{methoddesc}{ctime}{}
922 Return a string representing the date and time, for example
923 \code{datetime(2002, 12, 4, 20, 30, 40).ctime() ==
924 'Wed Dec 4 20:30:40 2002'}.
925 \code{d.ctime()} is equivalent to
926 \code{time.ctime(time.mktime(d.timetuple()))} on platforms where
927 the native C \cfunction{ctime()} function (which
928 \function{time.ctime()} invokes, but which
929 \method{datetime.ctime()} does not invoke) conforms to the C
930 standard.
931 \end{methoddesc}
933 \begin{methoddesc}{strftime}{format}
934 Return a string representing the date and time, controlled by an
935 explicit format string. See the section on \method{strftime()}
936 behavior.
937 \end{methoddesc}
940 \subsection{\class{time} Objects \label{datetime-time}}
942 A time object represents a (local) time of day, independent of any
943 particular day, and subject to adjustment via a \class{tzinfo} object.
945 \begin{classdesc}{time}{hour=0, minute=0, second=0, microsecond=0,
946 tzinfo=None}
947 All arguments are optional. \var{tzinfo} may be \code{None}, or
948 an instance of a \class{tzinfo} subclass. The remaining arguments
949 may be ints or longs, in the following ranges:
951 \begin{itemize}
952 \item \code{0 <= \var{hour} < 24}
953 \item \code{0 <= \var{minute} < 60}
954 \item \code{0 <= \var{second} < 60}
955 \item \code{0 <= \var{microsecond} < 1000000}.
956 \end{itemize}
958 If an argument outside those ranges is given,
959 \exception{ValueError} is raised.
960 \end{classdesc}
962 Class attributes:
964 \begin{memberdesc}{min}
965 The earliest representable \class{time}, \code{time(0, 0, 0, 0)}.
966 \end{memberdesc}
968 \begin{memberdesc}{max}
969 The latest representable \class{time}, \code{time(23, 59, 59, 999999)}.
970 \end{memberdesc}
972 \begin{memberdesc}{resolution}
973 The smallest possible difference between non-equal \class{time}
974 objects, \code{timedelta(microseconds=1)}, although note that
975 arithmetic on \class{time} objects is not supported.
976 \end{memberdesc}
978 Instance attributes (read-only):
980 \begin{memberdesc}{hour}
981 In \code{range(24)}.
982 \end{memberdesc}
984 \begin{memberdesc}{minute}
985 In \code{range(60)}.
986 \end{memberdesc}
988 \begin{memberdesc}{second}
989 In \code{range(60)}.
990 \end{memberdesc}
992 \begin{memberdesc}{microsecond}
993 In \code{range(1000000)}.
994 \end{memberdesc}
996 \begin{memberdesc}{tzinfo}
997 The object passed as the tzinfo argument to the \class{time}
998 constructor, or \code{None} if none was passed.
999 \end{memberdesc}
1001 Supported operations:
1003 \begin{itemize}
1004 \item
1005 comparison of \class{time} to \class{time},
1006 where \var{a} is considered less than \var{b} when \var{a} precedes
1007 \var{b} in time. If one comparand is naive and the other is aware,
1008 \exception{TypeError} is raised. If both comparands are aware, and
1009 have the same \member{tzinfo} member, the common \member{tzinfo}
1010 member is ignored and the base times are compared. If both
1011 comparands are aware and have different \member{tzinfo} members,
1012 the comparands are first adjusted by subtracting their UTC offsets
1013 (obtained from \code{self.utcoffset()}).
1015 \item
1016 hash, use as dict key
1018 \item
1019 efficient pickling
1021 \item
1022 in Boolean contexts, a \class{time} object is considered to be
1023 true if and only if, after converting it to minutes and
1024 subtracting \method{utcoffset()} (or \code{0} if that's
1025 \code{None}), the result is non-zero.
1026 \end{itemize}
1028 Instance methods:
1030 \begin{methoddesc}{replace}(hour=, minute=, second=, microsecond=, tzinfo=)
1031 Return a \class{time} with the same value, except for those members given
1032 new values by whichever keyword arguments are specified. Note that
1033 \code{tzinfo=None} can be specified to create a naive \class{time} from
1034 an aware \class{time}, without conversion of the time members.
1035 \end{methoddesc}
1037 \begin{methoddesc}{isoformat}{}
1038 Return a string representing the time in ISO 8601 format,
1039 HH:MM:SS.mmmmmm
1040 or, if self.microsecond is 0,
1041 HH:MM:SS
1042 If \method{utcoffset()} does not return \code{None}, a 6-character
1043 string is appended, giving the UTC offset in (signed) hours and
1044 minutes:
1045 HH:MM:SS.mmmmmm+HH:MM
1046 or, if self.microsecond is 0,
1047 HH:MM:SS+HH:MM
1048 \end{methoddesc}
1050 \begin{methoddesc}{__str__}{}
1051 For a time \var{t}, \code{str(\var{t})} is equivalent to
1052 \code{\var{t}.isoformat()}.
1053 \end{methoddesc}
1055 \begin{methoddesc}{strftime}{format}
1056 Return a string representing the time, controlled by an explicit
1057 format string. See the section on \method{strftime()} behavior.
1058 \end{methoddesc}
1060 \begin{methoddesc}{utcoffset}{}
1061 If \member{tzinfo} is \code{None}, returns \code{None}, else
1062 returns \code{\var{self}.tzinfo.utcoffset(None)}, and
1063 raises an exception if the latter doesn't return \code{None} or
1064 a \class{timedelta} object representing a whole number of minutes
1065 with magnitude less than one day.
1066 \end{methoddesc}
1068 \begin{methoddesc}{dst}{}
1069 If \member{tzinfo} is \code{None}, returns \code{None}, else
1070 returns \code{\var{self}.tzinfo.dst(None)}, and
1071 raises an exception if the latter doesn't return \code{None}, or
1072 a \class{timedelta} object representing a whole number of minutes
1073 with magnitude less than one day.
1074 \end{methoddesc}
1076 \begin{methoddesc}{tzname}{}
1077 If \member{tzinfo} is \code{None}, returns \code{None}, else
1078 returns \code{\var{self}.tzinfo.tzname(None)}, or
1079 raises an exception if the latter doesn't return \code{None} or
1080 a string object.
1081 \end{methoddesc}
1084 \subsection{\class{tzinfo} Objects \label{datetime-tzinfo}}
1086 \class{tzinfo} is an abstract base clase, meaning that this class
1087 should not be instantiated directly. You need to derive a concrete
1088 subclass, and (at least) supply implementations of the standard
1089 \class{tzinfo} methods needed by the \class{datetime} methods you
1090 use. The \module{datetime} module does not supply any concrete
1091 subclasses of \class{tzinfo}.
1093 An instance of (a concrete subclass of) \class{tzinfo} can be passed
1094 to the constructors for \class{datetime} and \class{time} objects.
1095 The latter objects view their members as being in local time, and the
1096 \class{tzinfo} object supports methods revealing offset of local time
1097 from UTC, the name of the time zone, and DST offset, all relative to a
1098 date or time object passed to them.
1100 Special requirement for pickling: A \class{tzinfo} subclass must have an
1101 \method{__init__} method that can be called with no arguments, else it
1102 can be pickled but possibly not unpickled again. This is a technical
1103 requirement that may be relaxed in the future.
1105 A concrete subclass of \class{tzinfo} may need to implement the
1106 following methods. Exactly which methods are needed depends on the
1107 uses made of aware \module{datetime} objects. If in doubt, simply
1108 implement all of them.
1110 \begin{methoddesc}{utcoffset}{self, dt}
1111 Return offset of local time from UTC, in minutes east of UTC. If
1112 local time is west of UTC, this should be negative. Note that this
1113 is intended to be the total offset from UTC; for example, if a
1114 \class{tzinfo} object represents both time zone and DST adjustments,
1115 \method{utcoffset()} should return their sum. If the UTC offset
1116 isn't known, return \code{None}. Else the value returned must be
1117 a \class{timedelta} object specifying a whole number of minutes in the
1118 range -1439 to 1439 inclusive (1440 = 24*60; the magnitude of the offset
1119 must be less than one day). Most implementations of
1120 \method{utcoffset()} will probably look like one of these two:
1122 \begin{verbatim}
1123 return CONSTANT # fixed-offset class
1124 return CONSTANT + self.dst(dt) # daylight-aware class
1125 \end{verbatim}
1127 If \method{utcoffset()} does not return \code{None},
1128 \method{dst()} should not return \code{None} either.
1130 The default implementation of \method{utcoffset()} raises
1131 \exception{NotImplementedError}.
1132 \end{methoddesc}
1134 \begin{methoddesc}{dst}{self, dt}
1135 Return the daylight saving time (DST) adjustment, in minutes east of
1136 UTC, or \code{None} if DST information isn't known. Return
1137 \code{timedelta(0)} if DST is not in effect.
1138 If DST is in effect, return the offset as a
1139 \class{timedelta} object (see \method{utcoffset()} for details).
1140 Note that DST offset, if applicable, has
1141 already been added to the UTC offset returned by
1142 \method{utcoffset()}, so there's no need to consult \method{dst()}
1143 unless you're interested in obtaining DST info separately. For
1144 example, \method{datetime.timetuple()} calls its \member{tzinfo}
1145 member's \method{dst()} method to determine how the
1146 \member{tm_isdst} flag should be set, and
1147 \method{tzinfo.fromutc()} calls \method{dst()} to account for
1148 DST changes when crossing time zones.
1150 An instance \var{tz} of a \class{tzinfo} subclass that models both
1151 standard and daylight times must be consistent in this sense:
1153 \code{\var{tz}.utcoffset(\var{dt}) - \var{tz}.dst(\var{dt})}
1155 must return the same result for every \class{datetime} \var{dt}
1156 with \code{\var{dt}.tzinfo==\var{tz}} For sane \class{tzinfo}
1157 subclasses, this expression yields the time zone's "standard offset",
1158 which should not depend on the date or the time, but only on geographic
1159 location. The implementation of \method{datetime.astimezone()} relies
1160 on this, but cannot detect violations; it's the programmer's
1161 responsibility to ensure it. If a \class{tzinfo} subclass cannot
1162 guarantee this, it may be able to override the default implementation
1163 of \method{tzinfo.fromutc()} to work correctly with \method{astimezone()}
1164 regardless.
1166 Most implementations of \method{dst()} will probably look like one
1167 of these two:
1169 \begin{verbatim}
1170 return timedelta(0) # a fixed-offset class: doesn't account for DST
1174 # Code to set dston and dstoff to the time zone's DST transition
1175 # times based on the input dt.year, and expressed in standard local
1176 # time. Then
1178 if dston <= dt.replace(tzinfo=None) < dstoff:
1179 return timedelta(hours=1)
1180 else:
1181 return timedelta(0)
1182 \end{verbatim}
1184 The default implementation of \method{dst()} raises
1185 \exception{NotImplementedError}.
1186 \end{methoddesc}
1188 \begin{methoddesc}{tzname}{self, dt}
1189 Return the time zone name corresponding to the \class{datetime}
1190 object \var{dt}, as a string.
1191 Nothing about string names is defined by the
1192 \module{datetime} module, and there's no requirement that it mean
1193 anything in particular. For example, "GMT", "UTC", "-500", "-5:00",
1194 "EDT", "US/Eastern", "America/New York" are all valid replies. Return
1195 \code{None} if a string name isn't known. Note that this is a method
1196 rather than a fixed string primarily because some \class{tzinfo}
1197 subclasses will wish to return different names depending on the specific
1198 value of \var{dt} passed, especially if the \class{tzinfo} class is
1199 accounting for daylight time.
1201 The default implementation of \method{tzname()} raises
1202 \exception{NotImplementedError}.
1203 \end{methoddesc}
1205 These methods are called by a \class{datetime} or \class{time} object,
1206 in response to their methods of the same names. A \class{datetime}
1207 object passes itself as the argument, and a \class{time} object passes
1208 \code{None} as the argument. A \class{tzinfo} subclass's methods should
1209 therefore be prepared to accept a \var{dt} argument of \code{None}, or of
1210 class \class{datetime}.
1212 When \code{None} is passed, it's up to the class designer to decide the
1213 best response. For example, returning \code{None} is appropriate if the
1214 class wishes to say that time objects don't participate in the
1215 \class{tzinfo} protocols. It may be more useful for \code{utcoffset(None)}
1216 to return the standard UTC offset, as there is no other convention for
1217 discovering the standard offset.
1219 When a \class{datetime} object is passed in response to a
1220 \class{datetime} method, \code{dt.tzinfo} is the same object as
1221 \var{self}. \class{tzinfo} methods can rely on this, unless
1222 user code calls \class{tzinfo} methods directly. The intent is that
1223 the \class{tzinfo} methods interpret \var{dt} as being in local time,
1224 and not need worry about objects in other timezones.
1226 There is one more \class{tzinfo} method that a subclass may wish to
1227 override:
1229 \begin{methoddesc}{fromutc}{self, dt}
1230 This is called from the default \class{datetime.astimezone()}
1231 implementation. When called from that, \code{\var{dt}.tzinfo} is
1232 \var{self}, and \var{dt}'s date and time members are to be viewed as
1233 expressing a UTC time. The purpose of \method{fromutc()} is to
1234 adjust the date and time members, returning an equivalent datetime in
1235 \var{self}'s local time.
1237 Most \class{tzinfo} subclasses should be able to inherit the default
1238 \method{fromutc()} implementation without problems. It's strong enough
1239 to handle fixed-offset time zones, and time zones accounting for both
1240 standard and daylight time, and the latter even if the DST transition
1241 times differ in different years. An example of a time zone the default
1242 \method{fromutc()} implementation may not handle correctly in all cases
1243 is one where the standard offset (from UTC) depends on the specific date
1244 and time passed, which can happen for political reasons.
1245 The default implementations of \method{astimezone()} and
1246 \method{fromutc()} may not produce the result you want if the result is
1247 one of the hours straddling the moment the standard offset changes.
1249 Skipping code for error cases, the default \method{fromutc()}
1250 implementation acts like:
1252 \begin{verbatim}
1253 def fromutc(self, dt):
1254 # raise ValueError error if dt.tzinfo is not self
1255 dtoff = dt.utcoffset()
1256 dtdst = dt.dst()
1257 # raise ValueError if dtoff is None or dtdst is None
1258 delta = dtoff - dtdst # this is self's standard offset
1259 if delta:
1260 dt += delta # convert to standard local time
1261 dtdst = dt.dst()
1262 # raise ValueError if dtdst is None
1263 if dtdst:
1264 return dt + dtdst
1265 else:
1266 return dt
1267 \end{verbatim}
1268 \end{methoddesc}
1270 Example \class{tzinfo} classes:
1272 \verbatiminput{tzinfo-examples.py}
1274 Note that there are unavoidable subtleties twice per year in a
1275 \class{tzinfo}
1276 subclass accounting for both standard and daylight time, at the DST
1277 transition points. For concreteness, consider US Eastern (UTC -0500),
1278 where EDT begins the minute after 1:59 (EST) on the first Sunday in
1279 April, and ends the minute after 1:59 (EDT) on the last Sunday in October:
1281 \begin{verbatim}
1282 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
1283 EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
1284 EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
1286 start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
1288 end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
1289 \end{verbatim}
1291 When DST starts (the "start" line), the local wall clock leaps from 1:59
1292 to 3:00. A wall time of the form 2:MM doesn't really make sense on that
1293 day, so \code{astimezone(Eastern)} won't deliver a result with
1294 \code{hour==2} on the
1295 day DST begins. In order for \method{astimezone()} to make this
1296 guarantee, the \method{rzinfo.dst()} method must consider times
1297 in the "missing hour" (2:MM for Eastern) to be in daylight time.
1299 When DST ends (the "end" line), there's a potentially worse problem:
1300 there's an hour that can't be spelled unambiguously in local wall time:
1301 the last hour of daylight time. In Eastern, that's times of
1302 the form 5:MM UTC on the day daylight time ends. The local wall clock
1303 leaps from 1:59 (daylight time) back to 1:00 (standard time) again.
1304 Local times of the form 1:MM are ambiguous. \method{astimezone()} mimics
1305 the local clock's behavior by mapping two adjacent UTC hours into the
1306 same local hour then. In the Eastern example, UTC times of the form
1307 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
1308 \method{astimezone()} to make this guarantee, the \method{tzinfo.dst()}
1309 method must consider times in the "repeated hour" to be in
1310 standard time. This is easily arranged, as in the example, by expressing
1311 DST switch times in the time zone's standard local time.
1313 Applications that can't bear such ambiguities should avoid using hybrid
1314 \class{tzinfo} subclasses; there are no ambiguities when using UTC, or
1315 any other fixed-offset \class{tzinfo} subclass (such as a class
1316 representing only EST (fixed offset -5 hours), or only EDT (fixed offset
1317 -4 hours)).
1320 \subsection{\method{strftime()} Behavior}
1322 \class{date}, \class{datetime}, and \class{time}
1323 objects all support a \code{strftime(\var{format})}
1324 method, to create a string representing the time under the control of
1325 an explicit format string. Broadly speaking,
1326 \code{d.strftime(fmt)}
1327 acts like the \refmodule{time} module's
1328 \code{time.strftime(fmt, d.timetuple())}
1329 although not all objects support a \method{timetuple()} method.
1331 For \class{time} objects, the format codes for
1332 year, month, and day should not be used, as time objects have no such
1333 values. If they're used anyway, \code{1900} is substituted for the
1334 year, and \code{0} for the month and day.
1336 For \class{date} objects, the format codes for hours, minutes, and
1337 seconds should not be used, as \class{date} objects have no such
1338 values. If they're used anyway, \code{0} is substituted for them.
1340 For a naive object, the \code{\%z} and \code{\%Z} format codes are
1341 replaced by empty strings.
1343 For an aware object:
1345 \begin{itemize}
1346 \item[\code{\%z}]
1347 \method{utcoffset()} is transformed into a 5-character string of
1348 the form +HHMM or -HHMM, where HH is a 2-digit string giving the
1349 number of UTC offset hours, and MM is a 2-digit string giving the
1350 number of UTC offset minutes. For example, if
1351 \method{utcoffset()} returns \code{timedelta(hours=-3, minutes=-30)},
1352 \code{\%z} is replaced with the string \code{'-0330'}.
1354 \item[\code{\%Z}]
1355 If \method{tzname()} returns \code{None}, \code{\%Z} is replaced
1356 by an empty string. Otherwise \code{\%Z} is replaced by the returned
1357 value, which must be a string.
1358 \end{itemize}
1360 The full set of format codes supported varies across platforms,
1361 because Python calls the platform C library's \function{strftime()}
1362 function, and platform variations are common. The documentation for
1363 Python's \refmodule{time} module lists the format codes that the C
1364 standard (1989 version) requires, and those work on all platforms
1365 with a standard C implementation. Note that the 1999 version of the
1366 C standard added additional format codes.
1368 The exact range of years for which \method{strftime()} works also
1369 varies across platforms. Regardless of platform, years before 1900
1370 cannot be used.
1373 \begin{comment}
1375 \subsection{C API}
1377 Struct typedefs:
1379 PyDateTime_Date
1380 PyDateTime_DateTime
1381 PyDateTime_Time
1382 PyDateTime_Delta
1383 PyDateTime_TZInfo
1385 Type-check macros:
1387 PyDate_Check(op)
1388 PyDate_CheckExact(op)
1390 PyDateTime_Check(op)
1391 PyDateTime_CheckExact(op)
1393 PyTime_Check(op)
1394 PyTime_CheckExact(op)
1396 PyDelta_Check(op)
1397 PyDelta_CheckExact(op)
1399 PyTZInfo_Check(op)
1400 PyTZInfo_CheckExact(op)
1402 Accessor macros:
1404 All objects are immutable, so accessors are read-only. All macros
1405 return ints:
1407 For \class{date} and \class{datetime} instances:
1408 PyDateTime_GET_YEAR(o)
1409 PyDateTime_GET_MONTH(o)
1410 PyDateTime_GET_DAY(o)
1412 For \class{datetime} instances:
1413 PyDateTime_DATE_GET_HOUR(o)
1414 PyDateTime_DATE_GET_MINUTE(o)
1415 PyDateTime_DATE_GET_SECOND(o)
1416 PyDateTime_DATE_GET_MICROSECOND(o)
1418 For \class{time} instances:
1419 PyDateTime_TIME_GET_HOUR(o)
1420 PyDateTime_TIME_GET_MINUTE(o)
1421 PyDateTime_TIME_GET_SECOND(o)
1422 PyDateTime_TIME_GET_MICROSECOND(o)
1424 \end{comment}