PageRenderTime 64ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/Doc/library/datetime.rst

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