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