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