source: vendor/python/2.5/Doc/lib/libdatetime.tex

Last change on this file was 3225, checked in by bird, 18 years ago

Python 2.5

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