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