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