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