rest25/library/datetime.rst => rest262/library/datetime.rst
n1-.. % 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
n10+.. XXX what order should the types be discussed in?
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
n19-formatting and manipulation.
n17+formatting and manipulation. For related
18+functionality, see also the :mod:`time` and :mod:`calendar` modules.
20
21There are two kinds of date and time objects: "naive" and "aware". This
22distinction refers to whether the object has any notion of time zone, daylight
23saving time, or other kind of algorithmic or political time adjustment.  Whether
24a naive :class:`datetime` object represents Coordinated Universal Time (UTC),
25local time, or time in some other timezone is purely up to the program, just
26like it's up to the program whether a particular number represents metres,
27miles, or mass.  Naive :class:`datetime` objects are easy to understand and to
134.. class:: timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
135
136   All arguments are optional and default to ``0``.  Arguments may be ints, longs,
137   or floats, and may be positive or negative.
138
139   Only *days*, *seconds* and *microseconds* are stored internally.  Arguments are
140   converted to those units:
141
n142-* A millisecond is converted to 1000 microseconds.
n141+   * A millisecond is converted to 1000 microseconds.
143- 
144-* A minute is converted to 60 seconds.
142+   * A minute is converted to 60 seconds.
145- 
146-* An hour is converted to 3600 seconds.
143+   * An hour is converted to 3600 seconds.
147- 
148-* A week is converted to 7 days.
144+   * 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
n153-* ``0 <= microseconds < 1000000``
n149+   * ``0 <= microseconds < 1000000``
154- 
155-* ``0 <= seconds < 3600*24`` (the number of seconds in one day)
150+   * ``0 <= seconds < 3600*24`` (the number of seconds in one day)
156- 
157-* ``-999999999 <= days <= 999999999``
151+   * ``-999999999 <= days <= 999999999``
158
159   If any argument is a float and there are fractional microseconds, the fractional
160   microseconds left over from all arguments are combined and their sum is rounded
161   to the nearest microsecond.  If no argument is a float, the conversion and
162   normalization processes are exact (no information is lost).
163
164   If the normalized value of days lies outside the indicated range,
165   :exc:`OverflowError` is raised.
166
167   Note that normalization of negative values may be surprising at first. For
n168-   example, ::
n162+   example,
169
n164+      >>> from datetime import timedelta
170      >>> d = timedelta(microseconds=-1)
171      >>> (d.days, d.seconds, d.microseconds)
172      (-1, 86399, 999999)
173
174Class attributes are:
175
176
177.. attribute:: timedelta.min
202+------------------+--------------------------------------------+
203| ``seconds``      | Between 0 and 86399 inclusive              |
204+------------------+--------------------------------------------+
205| ``microseconds`` | Between 0 and 999999 inclusive             |
206+------------------+--------------------------------------------+
207
208Supported operations:
209
n210-.. % XXX this table is too wide!
n205+.. XXX this table is too wide!
211
212+--------------------------------+-----------------------------------------------+
213| Operation                      | Result                                        |
214+================================+===============================================+
215| ``t1 = t2 + t3``               | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == |
216|                                | *t3* and *t1*-*t3* == *t2* are true. (1)      |
217+--------------------------------+-----------------------------------------------+
218| ``t1 = t2 - t3``               | Difference of *t2* and *t3*. Afterwards *t1*  |
261Comparisons of :class:`timedelta` objects are supported with the
262:class:`timedelta` object representing the smaller duration considered to be the
263smaller timedelta. In order to stop mixed-type comparisons from falling back to
264the default comparison by object address, when a :class:`timedelta` object is
265compared to an object of a different type, :exc:`TypeError` is raised unless the
266comparison is ``==`` or ``!=``.  The latter cases return :const:`False` or
267:const:`True`, respectively.
268
n269-:class:`timedelta` objects are hashable (usable as dictionary keys), support
n264+:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
270efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
271considered to be true if and only if it isn't equal to ``timedelta(0)``.
n267+ 
268+Example usage:
269+ 
270+    >>> from datetime import timedelta
271+    >>> year = timedelta(days=365)
272+    >>> another_year = timedelta(weeks=40, days=84, hours=23,
273+    ...                          minutes=50, seconds=600)  # adds up to 365 days
274+    >>> year == another_year
275+    True
276+    >>> ten_years = 10 * year
277+    >>> ten_years, ten_years.days // 365
278+    (datetime.timedelta(3650), 10)
279+    >>> nine_years = ten_years - year
280+    >>> nine_years, nine_years.days // 365
281+    (datetime.timedelta(3285), 9)
282+    >>> three_years = nine_years // 3;
283+    >>> three_years, three_years.days // 365
284+    (datetime.timedelta(1095), 3)
285+    >>> abs(three_years - ten_years) == 2 * three_years + year
286+    True
272
273
274.. _datetime-date:
275
276:class:`date` Objects
277---------------------
278
279A :class:`date` object represents a date (year, month and day) in an idealized
286systems.
287
288
289.. class:: date(year, month, day)
290
291   All arguments are required.  Arguments may be ints or longs, in the following
292   ranges:
293
n294-* ``MINYEAR <= year <= MAXYEAR``
n309+   * ``MINYEAR <= year <= MAXYEAR``
295- 
296-* ``1 <= month <= 12``
310+   * ``1 <= month <= 12``
297- 
298-* ``1 <= day <= number of days in the given month and year``
311+   * ``1 <= day <= number of days in the given month and year``
299
300   If an argument outside those ranges is given, :exc:`ValueError` is raised.
301
302Other constructors, all class methods:
303
304
305.. method:: date.today()
306
449   :meth:`weekday`, :meth:`isocalendar`.
450
451
452.. method:: date.isocalendar()
453
454   Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
455
456   The ISO calendar is a widely used variant of the Gregorian calendar. See
n457-   `<http://www.phys.uu.nl/ vgent/calendar/isocalendar.htm>`_ for a good
n470+   http://www.phys.uu.nl/ vgent/calendar/isocalendar.htm for a good explanation.
458-   explanation.
459
460   The ISO year consists of 52 or 53 full weeks, and where a week starts on a
461   Monday and ends on a Sunday.  The first week of an ISO year is the first
462   (Gregorian) calendar week of a year containing a Thursday. This is called week
463   number 1, and the ISO year of that Thursday is the same as its Gregorian year.
464
465   For example, 2004 begins on a Thursday, so the first week of ISO year 2004
466   begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
476
477.. method:: date.__str__()
478
479   For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.
480
481
482.. method:: date.ctime()
483
n484-   Return a string representing the date, for example date(2002, 12, 4).ctime() ==
n496+   Return a string representing the date, for example ``date(2002, 12,
485-   'Wed Dec  4 00:00:00 2002'. ``d.ctime()`` is equivalent to
497+   4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
486   ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
487   :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
488   :meth:`date.ctime` does not invoke) conforms to the C standard.
489
490
491.. method:: date.strftime(format)
492
493   Return a string representing the date, controlled by an explicit format string.
494   Format codes referring to hours, minutes or seconds will see 0 values. See
n495-   section :ref:`strftime-behavior` -- :meth:`strftime` behavior.
n507+   section :ref:`strftime-behavior`.
508+ 
509+Example of counting days to an event::
510+ 
511+    >>> import time
512+    >>> from datetime import date
513+    >>> today = date.today()
514+    >>> today
515+    datetime.date(2007, 12, 5)
516+    >>> today == date.fromtimestamp(time.time())
517+    True
518+    >>> my_birthday = date(today.year, 6, 24)
519+    >>> if my_birthday < today:
520+    ...     my_birthday = my_birthday.replace(year=today.year + 1)
521+    >>> my_birthday
522+    datetime.date(2008, 6, 24)
523+    >>> time_to_birthday = abs(my_birthday - today)
524+    >>> time_to_birthday.days
525+    202
526+ 
527+Example of working with :class:`date`:
528+ 
529+.. doctest::
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:     # doctest: +SKIP
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:    # doctest: +SKIP
549+    ...     print i
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'
496
497
498.. _datetime-datetime:
499
500:class:`datetime` Objects
501-------------------------
502
503A :class:`datetime` object is a single object containing all the information
510
511
512.. class:: datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])
513
514   The year, month and day arguments are required.  *tzinfo* may be ``None``, or an
515   instance of a :class:`tzinfo` subclass.  The remaining arguments may be ints or
516   longs, in the following ranges:
517
n518-* ``MINYEAR <= year <= MAXYEAR``
n581+   * ``MINYEAR <= year <= MAXYEAR``
519- 
520-* ``1 <= month <= 12``
582+   * ``1 <= month <= 12``
521- 
522-* ``1 <= day <= number of days in the given month and year``
583+   * ``1 <= day <= number of days in the given month and year``
523- 
524-* ``0 <= hour < 24``
584+   * ``0 <= hour < 24``
525- 
526-* ``0 <= minute < 60``
585+   * ``0 <= minute < 60``
527- 
528-* ``0 <= second < 60``
586+   * ``0 <= second < 60``
529- 
530-* ``0 <= microsecond < 1000000``
587+   * ``0 <= microsecond < 1000000``
531
532   If an argument outside those ranges is given, :exc:`ValueError` is raised.
533
534Other constructors, all class methods:
535
536
537.. method:: datetime.today()
538
890.. method:: datetime.isocalendar()
891
892   Return a 3-tuple, (ISO year, ISO week number, ISO weekday).  The same as
893   ``self.date().isocalendar()``.
894
895
896.. method:: datetime.isoformat([sep])
897
n898-   Return a string representing the date and time in ISO 8601 format, YYYY-MM-
n955+   Return a string representing the date and time in ISO 8601 format,
899-   DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0, YYYY-MM-DDTHH:MM:SS
956+   YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
957+   YYYY-MM-DDTHH:MM:SS
900
n901-   If :meth:`utcoffset` does not return ``None``, a 6-character string is appended,
n959+   If :meth:`utcoffset` does not return ``None``, a 6-character string is
902-   giving the UTC offset in (signed) hours and minutes: YYYY-MM-
960+   appended, giving the UTC offset in (signed) hours and minutes:
903-   DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0 YYYY-MM-
961+   YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
904-   DDTHH:MM:SS+HH:MM
962+   YYYY-MM-DDTHH:MM:SS+HH:MM
905
906   The optional argument *sep* (default ``'T'``) is a one-character separator,
n907-   placed between the date and time portions of the result.  For example, ::
n965+   placed between the date and time portions of the result.  For example,
908
909      >>> from datetime import tzinfo, timedelta, datetime
910      >>> class TZ(tzinfo):
911      ...     def utcoffset(self, dt): return timedelta(minutes=-399)
912      ...
913      >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
914      '2002-12-25 00:00:00-06:39'
915
927   equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
928   native C :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which
929   :meth:`datetime.ctime` does not invoke) conforms to the C standard.
930
931
932.. method:: datetime.strftime(format)
933
934   Return a string representing the date and time, controlled by an explicit format
n935-   string.  See section :ref:`strftime-behavior` -- :meth:`strftime` behavior.
n993+   string.  See section :ref:`strftime-behavior`.
994+ 
995+Examples of working with datetime objects:
996+ 
997+.. doctest::
998+ 
999+    >>> from datetime import datetime, date, time
1000+    >>> # Using datetime.combine()
1001+    >>> d = date(2005, 7, 14)
1002+    >>> t = time(12, 30)
1003+    >>> datetime.combine(d, t)
1004+    datetime.datetime(2005, 7, 14, 12, 30)
1005+    >>> # Using datetime.now() or datetime.utcnow()
1006+    >>> datetime.now()   # doctest: +SKIP
1007+    datetime.datetime(2007, 12, 6, 16, 29, 43, 79043)   # GMT +1
1008+    >>> datetime.utcnow()   # doctest: +SKIP
1009+    datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
1010+    >>> # Using datetime.strptime()
1011+    >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
1012+    >>> dt
1013+    datetime.datetime(2006, 11, 21, 16, 30)
1014+    >>> # Using datetime.timetuple() to get tuple of all attributes
1015+    >>> tt = dt.timetuple()
1016+    >>> for it in tt:   # doctest: +SKIP
1017+    ...     print it
1018+    ...
1019+    2006    # year
1020+    11      # month
1021+    21      # day
1022+    16      # hour
1023+    30      # minute
1024+    0       # second
1025+    1       # weekday (0 = Monday)
1026+    325     # number of days since 1st January
1027+    -1      # dst - method tzinfo.dst() returned None
1028+    >>> # Date in ISO format
1029+    >>> ic = dt.isocalendar()
1030+    >>> for it in ic:   # doctest: +SKIP
1031+    ...     print it
1032+    ...
1033+    2006    # ISO year
1034+    47      # ISO week
1035+    2       # ISO weekday
1036+    >>> # Formatting datetime
1037+    >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
1038+    'Tuesday, 21. November 2006 04:30PM'
1039+ 
1040+Using datetime with tzinfo:
1041+ 
1042+    >>> from datetime import timedelta, datetime, tzinfo
1043+    >>> class GMT1(tzinfo):
1044+    ...     def __init__(self):         # DST starts last Sunday in March
1045+    ...         d = datetime(dt.year, 4, 1)   # ends last Sunday in October
1046+    ...         self.dston = d - timedelta(days=d.weekday() + 1)
1047+    ...         d = datetime(dt.year, 11, 1)
1048+    ...         self.dstoff = d - timedelta(days=d.weekday() + 1)
1049+    ...     def utcoffset(self, dt):
1050+    ...         return timedelta(hours=1) + self.dst(dt)
1051+    ...     def dst(self, dt):
1052+    ...         if self.dston <=  dt.replace(tzinfo=None) < self.dstoff:
1053+    ...             return timedelta(hours=1)
1054+    ...         else:
1055+    ...             return timedelta(0)
1056+    ...     def tzname(self,dt):
1057+    ...          return "GMT +1"
1058+    ...
1059+    >>> class GMT2(tzinfo):
1060+    ...     def __init__(self):
1061+    ...         d = datetime(dt.year, 4, 1)
1062+    ...         self.dston = d - timedelta(days=d.weekday() + 1)
1063+    ...         d = datetime(dt.year, 11, 1)
1064+    ...         self.dstoff = d - timedelta(days=d.weekday() + 1)
1065+    ...     def utcoffset(self, dt):
1066+    ...         return timedelta(hours=1) + self.dst(dt)
1067+    ...     def dst(self, dt):
1068+    ...         if self.dston <=  dt.replace(tzinfo=None) < self.dstoff:
1069+    ...             return timedelta(hours=2)
1070+    ...         else:
1071+    ...             return timedelta(0)
1072+    ...     def tzname(self,dt):
1073+    ...         return "GMT +2"
1074+    ...
1075+    >>> gmt1 = GMT1()
1076+    >>> # Daylight Saving Time
1077+    >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
1078+    >>> dt1.dst()
1079+    datetime.timedelta(0)
1080+    >>> dt1.utcoffset()
1081+    datetime.timedelta(0, 3600)
1082+    >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
1083+    >>> dt2.dst()
1084+    datetime.timedelta(0, 3600)
1085+    >>> dt2.utcoffset()
1086+    datetime.timedelta(0, 7200)
1087+    >>> # Convert datetime to another time zone
1088+    >>> dt3 = dt2.astimezone(GMT2())
1089+    >>> dt3     # doctest: +ELLIPSIS
1090+    datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
1091+    >>> dt2     # doctest: +ELLIPSIS
1092+    datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
1093+    >>> dt2.utctimetuple() == dt3.utctimetuple()
1094+    True
1095+ 
936
937
938.. _datetime-time:
939
940:class:`time` Objects
941---------------------
942
943A time object represents a (local) time of day, independent of any particular
945
946
947.. class:: time(hour[, minute[, second[, microsecond[, tzinfo]]]])
948
949   All arguments are optional.  *tzinfo* may be ``None``, or an instance of a
950   :class:`tzinfo` subclass.  The remaining arguments may be ints or longs, in the
951   following ranges:
952
n953-* ``0 <= hour < 24``
n1113+   * ``0 <= hour < 24``
954- 
955-* ``0 <= minute < 60``
1114+   * ``0 <= minute < 60``
956- 
957-* ``0 <= second < 60``
1115+   * ``0 <= second < 60``
958- 
959-* ``0 <= microsecond < 1000000``.
1116+   * ``0 <= microsecond < 1000000``.
960
961   If an argument outside those ranges is given, :exc:`ValueError` is raised.  All
962   default to ``0`` except *tzinfo*, which defaults to :const:`None`.
963
964Class attributes:
965
966
967.. attribute:: time.min
1052.. method:: time.__str__()
1053
1054   For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.
1055
1056
1057.. method:: time.strftime(format)
1058
1059   Return a string representing the time, controlled by an explicit format string.
n1060-   See section :ref:`strftime-behavior` -- :meth:`strftime` behavior.
n1217+   See section :ref:`strftime-behavior`.
1061
1062
1063.. method:: time.utcoffset()
1064
1065   If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1066   ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
1067   return ``None`` or a :class:`timedelta` object representing a whole number of
1068   minutes with magnitude less than one day.
1077
1078
1079.. method:: time.tzname()
1080
1081   If :attr:`tzinfo` is ``None``, returns ``None``, else returns
1082   ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
1083   return ``None`` or a string object.
1084
n1242+Example:
1243+ 
1244+    >>> from datetime import time, tzinfo
1245+    >>> class GMT1(tzinfo):
1246+    ...     def utcoffset(self, dt):
1247+    ...         return timedelta(hours=1)
1248+    ...     def dst(self, dt):
1249+    ...         return timedelta(0)
1250+    ...     def tzname(self,dt):
1251+    ...         return "Europe/Prague"
1252+    ...
1253+    >>> t = time(12, 10, 30, tzinfo=GMT1())
1254+    >>> t                               # doctest: +ELLIPSIS
1255+    datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
1256+    >>> gmt = GMT1()
1257+    >>> t.isoformat()
1258+    '12:10:30+01:00'
1259+    >>> t.dst()
1260+    datetime.timedelta(0)
1261+    >>> t.tzname()
1262+    'Europe/Prague'
1263+    >>> t.strftime("%H:%M:%S %Z")
1264+    '12:10:30 Europe/Prague'
1265+ 
1085
1086.. _datetime-tzinfo:
1087
1088:class:`tzinfo` Objects
1089-----------------------
1090
n1091-:class:`tzinfo` is an abstract base clase, meaning that this class should not be
n1272+:class:`tzinfo` is an abstract base class, meaning that this class should not be
1092instantiated directly.  You need to derive a concrete subclass, and (at least)
1093supply implementations of the standard :class:`tzinfo` methods needed by the
1094:class:`datetime` methods you use.  The :mod:`datetime` module does not supply
1095any concrete subclasses of :class:`tzinfo`.
1096
1097An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
1098constructors for :class:`datetime` and :class:`time` objects. The latter objects
1099view their members as being in local time, and the :class:`tzinfo` object
1105pickled but possibly not unpickled again.  This is a technical requirement that
1106may be relaxed in the future.
1107
1108A concrete subclass of :class:`tzinfo` may need to implement the following
1109methods.  Exactly which methods are needed depends on the uses made of aware
1110:mod:`datetime` objects.  If in doubt, simply implement all of them.
1111
1112
n1113-.. method:: XXX Class.utcoffset(self, dt)
n1294+.. method:: tzinfo.utcoffset(self, dt)
1114
1115   Return offset of local time from UTC, in minutes east of UTC.  If local time is
1116   west of UTC, this should be negative.  Note that this is intended to be the
1117   total offset from UTC; for example, if a :class:`tzinfo` object represents both
1118   time zone and DST adjustments, :meth:`utcoffset` should return their sum.  If
1119   the UTC offset isn't known, return ``None``.  Else the value returned must be a
1120   :class:`timedelta` object specifying a whole number of minutes in the range
1121   -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
1127
1128   If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
1129   ``None`` either.
1130
1131   The default implementation of :meth:`utcoffset` raises
1132   :exc:`NotImplementedError`.
1133
1134
n1135-.. method:: XXX Class.dst(self, dt)
n1316+.. method:: tzinfo.dst(self, dt)
1136
1137   Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
1138   ``None`` if DST information isn't known.  Return ``timedelta(0)`` if DST is not
1139   in effect. If DST is in effect, return the offset as a :class:`timedelta` object
1140   (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
1141   already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1142   no need to consult :meth:`dst` unless you're interested in obtaining DST info
1143   separately.  For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
1175          if dston <= dt.replace(tzinfo=None) < dstoff:
1176              return timedelta(hours=1)
1177          else:
1178              return timedelta(0)
1179
1180   The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
1181
1182
n1183-.. method:: XXX Class.tzname(self, dt)
n1364+.. method:: tzinfo.tzname(self, dt)
1184
1185   Return the time zone name corresponding to the :class:`datetime` object *dt*, as
1186   a string. Nothing about string names is defined by the :mod:`datetime` module,
1187   and there's no requirement that it mean anything in particular.  For example,
1188   "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
1189   valid replies.  Return ``None`` if a string name isn't known.  Note that this is
1190   a method rather than a fixed string primarily because some :class:`tzinfo`
1191   subclasses will wish to return different names depending on the specific value
1210method, ``dt.tzinfo`` is the same object as *self*.  :class:`tzinfo` methods can
1211rely on this, unless user code calls :class:`tzinfo` methods directly.  The
1212intent is that the :class:`tzinfo` methods interpret *dt* as being in local
1213time, and not need worry about objects in other timezones.
1214
1215There is one more :class:`tzinfo` method that a subclass may wish to override:
1216
1217
n1218-.. method:: XXX Class.fromutc(self, dt)
n1399+.. method:: tzinfo.fromutc(self, dt)
1219
1220   This is called from the default :class:`datetime.astimezone()` implementation.
1221   When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members
1222   are to be viewed as expressing a UTC time.  The purpose of :meth:`fromutc` is to
1223   adjust the date and time members, returning an equivalent datetime in *self*'s
1224   local time.
1225
1226   Most :class:`tzinfo` subclasses should be able to inherit the default
1249              # raise ValueError if dtdst is None
1250          if dtdst:
1251              return dt + dtdst
1252          else:
1253              return dt
1254
1255Example :class:`tzinfo` classes:
1256
n1257- 
1258-.. include:: ../includes/tzinfo-examples.py
1438+.. literalinclude:: ../includes/tzinfo-examples.py
1259-   :literal:
1439+ 
1260
1261Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
1262subclass accounting for both standard and daylight time, at the DST transition
1263points.  For concreteness, consider US Eastern (UTC -0500), where EDT begins the
1264minute after 1:59 (EST) on the first Sunday in April, and ends the minute after
12651:59 (EDT) on the last Sunday in October::
1266
1267     UTC   3:MM  4:MM  5:MM  6:MM  7:MM  8:MM
1308control of an explicit format string.  Broadly speaking, ``d.strftime(fmt)``
1309acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1310although not all objects support a :meth:`timetuple` method.
1311
1312For :class:`time` objects, the format codes for year, month, and day should not
1313be used, as time objects have no such values.  If they're used anyway, ``1900``
1314is substituted for the year, and ``0`` for the month and day.
1315
n1316-For :class:`date` objects, the format codes for hours, minutes, and seconds
n1496+For :class:`date` objects, the format codes for hours, minutes, seconds, and
1317-should not be used, as :class:`date` objects have no such values.  If they're
1497+microseconds should not be used, as :class:`date` objects have no such
1318-used anyway, ``0`` is substituted for them.
1498+values.  If they're used anyway, ``0`` is substituted for them.
1499+ 
1500+.. versionadded:: 2.6
1501+   :class:`time` and :class:`datetime` objects support a ``%f`` format code
1502+   which expands to the number of microseconds in the object, zero-padded on
1503+   the left to six places.
1319
1320For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
1321strings.
1322
1323For an aware object:
1324
1325``%z``
1326   :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or
1330   replaced with the string ``'-0330'``.
1331
1332``%Z``
1333   If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.
1334   Otherwise ``%Z`` is replaced by the returned value, which must be a string.
1335
1336The full set of format codes supported varies across platforms, because Python
1337calls the platform C library's :func:`strftime` function, and platform
n1338-variations are common.  The documentation for Python's :mod:`time` module lists
n1523+variations are common.
1339-the format codes that the C standard (1989 version) requires, and those work on
1524+ 
1340-all platforms with a standard C implementation.  Note that the 1999 version of
1525+The following is a list of all the format codes that the C standard (1989
1341-the C standard added additional format codes.
1526+version) requires, and these work on all platforms with a standard C
1527+implementation.  Note that the 1999 version of the C standard added additional
1528+format codes.
1342
1343The exact range of years for which :meth:`strftime` works also varies across
1344platforms.  Regardless of platform, years before 1900 cannot be used.
1345
n1533++-----------+--------------------------------+-------+
1534+| Directive | Meaning                        | Notes |
1535++===========+================================+=======+
1536+| ``%a``    | Locale's abbreviated weekday   |       |
1537+|           | name.                          |       |
1538++-----------+--------------------------------+-------+
1539+| ``%A``    | Locale's full weekday name.    |       |
1540++-----------+--------------------------------+-------+
1541+| ``%b``    | Locale's abbreviated month     |       |
1542+|           | name.                          |       |
1543++-----------+--------------------------------+-------+
1544+| ``%B``    | Locale's full month name.      |       |
1545++-----------+--------------------------------+-------+
1546+| ``%c``    | Locale's appropriate date and  |       |
1547+|           | time representation.           |       |
1548++-----------+--------------------------------+-------+
1549+| ``%d``    | Day of the month as a decimal  |       |
1550+|           | number [01,31].                |       |
1551++-----------+--------------------------------+-------+
1552+| ``%f``    | Microsecond as a decimal       | \(1)  |
1553+|           | number [0,999999], zero-padded |       |
1554+|           | on the left                    |       |
1555++-----------+--------------------------------+-------+
1556+| ``%H``    | Hour (24-hour clock) as a      |       |
1557+|           | decimal number [00,23].        |       |
1558++-----------+--------------------------------+-------+
1559+| ``%I``    | Hour (12-hour clock) as a      |       |
1560+|           | decimal number [01,12].        |       |
1561++-----------+--------------------------------+-------+
1562+| ``%j``    | Day of the year as a decimal   |       |
1563+|           | number [001,366].              |       |
1564++-----------+--------------------------------+-------+
1565+| ``%m``    | Month as a decimal number      |       |
1566+|           | [01,12].                       |       |
1567++-----------+--------------------------------+-------+
1568+| ``%M``    | Minute as a decimal number     |       |
1569+|           | [00,59].                       |       |
1570++-----------+--------------------------------+-------+
1571+| ``%p``    | Locale's equivalent of either  | \(2)  |
1572+|           | AM or PM.                      |       |
1573++-----------+--------------------------------+-------+
1574+| ``%S``    | Second as a decimal number     | \(3)  |
1575+|           | [00,61].                       |       |
1576++-----------+--------------------------------+-------+
1577+| ``%U``    | Week number of the year        | \(4)  |
1578+|           | (Sunday as the first day of    |       |
1579+|           | the week) as a decimal number  |       |
1580+|           | [00,53].  All days in a new    |       |
1581+|           | year preceding the first       |       |
1582+|           | Sunday are considered to be in |       |
1583+|           | week 0.                        |       |
1584++-----------+--------------------------------+-------+
1585+| ``%w``    | Weekday as a decimal number    |       |
1586+|           | [0(Sunday),6].                 |       |
1587++-----------+--------------------------------+-------+
1588+| ``%W``    | Week number of the year        | \(4)  |
1589+|           | (Monday as the first day of    |       |
1590+|           | the week) as a decimal number  |       |
1591+|           | [00,53].  All days in a new    |       |
1592+|           | year preceding the first       |       |
1593+|           | Monday are considered to be in |       |
1594+|           | week 0.                        |       |
1595++-----------+--------------------------------+-------+
1596+| ``%x``    | Locale's appropriate date      |       |
1597+|           | representation.                |       |
1598++-----------+--------------------------------+-------+
1599+| ``%X``    | Locale's appropriate time      |       |
1600+|           | representation.                |       |
1601++-----------+--------------------------------+-------+
1602+| ``%y``    | Year without century as a      |       |
1603+|           | decimal number [00,99].        |       |
1604++-----------+--------------------------------+-------+
1605+| ``%Y``    | Year with century as a decimal |       |
1606+|           | number.                        |       |
1607++-----------+--------------------------------+-------+
1608+| ``%z``    | UTC offset in the form +HHMM   | \(5)  |
1609+|           | or -HHMM (empty string if the  |       |
1610+|           | the object is naive).          |       |
1611++-----------+--------------------------------+-------+
1612+| ``%Z``    | Time zone name (empty string   |       |
1613+|           | if the object is naive).       |       |
1614++-----------+--------------------------------+-------+
1615+| ``%%``    | A literal ``'%'`` character.   |       |
1616++-----------+--------------------------------+-------+
1346
n1347-Examples
n1618+Notes:
1348---------
1349
n1620+(1)
1621+   When used with the :func:`strptime` function, the ``%f`` directive
1622+   accepts from one to six digits and zero pads on the right.  ``%f`` is
1623+   an extension to the set of format characters in the C standard (but
1624+   implemented separately in datetime objects, and therefore always
1625+   available).
1350
n1351-Creating Datetime Objects from Formatted Strings
n1627+(2)
1352-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1628+   When used with the :func:`strptime` function, the ``%p`` directive only affects
1629+   the output hour field if the ``%I`` directive is used to parse the hour.
1353
n1354-The :class:`datetime` class does not directly support parsing formatted time
n1631+(3)
1355-strings.  You can use :func:`time.strptime` to do the parsing and create a
1632+   The range really is ``0`` to ``61``; according to the Posix standard this
1356-:class:`datetime` object from the tuple it returns::
1633+   accounts for leap seconds and the (very rare) double leap seconds.
1634+   The :mod:`time` module may produce and does accept leap seconds since
1635+   it is based on the Posix standard, but the :mod:`datetime` module
1636+   does not accept leap seconds in :func:`strptime` input nor will it
1637+   produce them in :func:`strftime` output.
1357
n1358-   >>> s = "2005-12-06T12:13:14"
n1639+(4)
1359-   >>> from datetime import datetime
1640+   When used with the :func:`strptime` function, ``%U`` and ``%W`` are only used in
1360-   >>> from time import strptime
1641+   calculations when the day of the week and the year are specified.
1361-   >>> datetime(*strptime(s, "%Y-%m-%dT%H:%M:%S")[0:6])
1362-   datetime.datetime(2005, 12, 6, 12, 13, 14)
1363
t1643+(5)
1644+   For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
1645+   ``%z`` is replaced with the string ``'-0330'``.
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op