You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

idatetime.py 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. ##############################################################################
  2. # Copyright (c) 2002 Zope Foundation and Contributors.
  3. # All Rights Reserved.
  4. #
  5. # This software is subject to the provisions of the Zope Public License,
  6. # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
  7. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  8. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  9. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  10. # FOR A PARTICULAR PURPOSE.
  11. ##############################################################################
  12. """Datetime interfaces.
  13. This module is called idatetime because if it were called datetime the import
  14. of the real datetime would fail.
  15. """
  16. from datetime import timedelta, date, datetime, time, tzinfo
  17. from zope.interface import Interface, Attribute
  18. from zope.interface import classImplements
  19. class ITimeDeltaClass(Interface):
  20. """This is the timedelta class interface.
  21. This is symbolic; this module does **not** make
  22. `datetime.timedelta` provide this interface.
  23. """
  24. min = Attribute("The most negative timedelta object")
  25. max = Attribute("The most positive timedelta object")
  26. resolution = Attribute(
  27. "The smallest difference between non-equal timedelta objects")
  28. class ITimeDelta(ITimeDeltaClass):
  29. """Represent the difference between two datetime objects.
  30. Implemented by `datetime.timedelta`.
  31. Supported operators:
  32. - add, subtract timedelta
  33. - unary plus, minus, abs
  34. - compare to timedelta
  35. - multiply, divide by int/long
  36. In addition, `.datetime` supports subtraction of two `.datetime` objects
  37. returning a `.timedelta`, and addition or subtraction of a `.datetime`
  38. and a `.timedelta` giving a `.datetime`.
  39. Representation: (days, seconds, microseconds).
  40. """
  41. days = Attribute("Days between -999999999 and 999999999 inclusive")
  42. seconds = Attribute("Seconds between 0 and 86399 inclusive")
  43. microseconds = Attribute("Microseconds between 0 and 999999 inclusive")
  44. class IDateClass(Interface):
  45. """This is the date class interface.
  46. This is symbolic; this module does **not** make
  47. `datetime.date` provide this interface.
  48. """
  49. min = Attribute("The earliest representable date")
  50. max = Attribute("The latest representable date")
  51. resolution = Attribute(
  52. "The smallest difference between non-equal date objects")
  53. def today():
  54. """Return the current local time.
  55. This is equivalent to ``date.fromtimestamp(time.time())``"""
  56. def fromtimestamp(timestamp):
  57. """Return the local date from a POSIX timestamp (like time.time())
  58. This may raise `ValueError`, if the timestamp is out of the range of
  59. values supported by the platform C ``localtime()`` function. It's common
  60. for this to be restricted to years from 1970 through 2038. Note that
  61. on non-POSIX systems that include leap seconds in their notion of a
  62. timestamp, leap seconds are ignored by `fromtimestamp`.
  63. """
  64. def fromordinal(ordinal):
  65. """Return the date corresponding to the proleptic Gregorian ordinal.
  66. January 1 of year 1 has ordinal 1. `ValueError` is raised unless
  67. 1 <= ordinal <= date.max.toordinal().
  68. For any date *d*, ``date.fromordinal(d.toordinal()) == d``.
  69. """
  70. class IDate(IDateClass):
  71. """Represents a date (year, month and day) in an idealized calendar.
  72. Implemented by `datetime.date`.
  73. Operators:
  74. __repr__, __str__
  75. __cmp__, __hash__
  76. __add__, __radd__, __sub__ (add/radd only with timedelta arg)
  77. """
  78. year = Attribute("Between MINYEAR and MAXYEAR inclusive.")
  79. month = Attribute("Between 1 and 12 inclusive")
  80. day = Attribute(
  81. "Between 1 and the number of days in the given month of the given year.")
  82. def replace(year, month, day):
  83. """Return a date with the same value.
  84. Except for those members given new values by whichever keyword
  85. arguments are specified. For example, if ``d == date(2002, 12, 31)``, then
  86. ``d.replace(day=26) == date(2000, 12, 26)``.
  87. """
  88. def timetuple():
  89. """Return a 9-element tuple of the form returned by `time.localtime`.
  90. The hours, minutes and seconds are 0, and the DST flag is -1.
  91. ``d.timetuple()`` is equivalent to
  92. ``(d.year, d.month, d.day, 0, 0, 0, d.weekday(), d.toordinal() -
  93. date(d.year, 1, 1).toordinal() + 1, -1)``
  94. """
  95. def toordinal():
  96. """Return the proleptic Gregorian ordinal of the date
  97. January 1 of year 1 has ordinal 1. For any date object *d*,
  98. ``date.fromordinal(d.toordinal()) == d``.
  99. """
  100. def weekday():
  101. """Return the day of the week as an integer.
  102. Monday is 0 and Sunday is 6. For example,
  103. ``date(2002, 12, 4).weekday() == 2``, a Wednesday.
  104. .. seealso:: `isoweekday`.
  105. """
  106. def isoweekday():
  107. """Return the day of the week as an integer.
  108. Monday is 1 and Sunday is 7. For example,
  109. date(2002, 12, 4).isoweekday() == 3, a Wednesday.
  110. .. seealso:: `weekday`, `isocalendar`.
  111. """
  112. def isocalendar():
  113. """Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
  114. The ISO calendar is a widely used variant of the Gregorian calendar.
  115. See http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good
  116. explanation.
  117. The ISO year consists of 52 or 53 full weeks, and where a week starts
  118. on a Monday and ends on a Sunday. The first week of an ISO year is the
  119. first (Gregorian) calendar week of a year containing a Thursday. This
  120. is called week number 1, and the ISO year of that Thursday is the same
  121. as its Gregorian year.
  122. For example, 2004 begins on a Thursday, so the first week of ISO year
  123. 2004 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so
  124. that ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and
  125. ``date(2004, 1, 4).isocalendar() == (2004, 1, 7)``.
  126. """
  127. def isoformat():
  128. """Return a string representing the date in ISO 8601 format.
  129. This is 'YYYY-MM-DD'.
  130. For example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.
  131. """
  132. def __str__():
  133. """For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``."""
  134. def ctime():
  135. """Return a string representing the date.
  136. For example date(2002, 12, 4).ctime() == 'Wed Dec 4 00:00:00 2002'.
  137. d.ctime() is equivalent to time.ctime(time.mktime(d.timetuple()))
  138. on platforms where the native C ctime() function
  139. (which `time.ctime` invokes, but which date.ctime() does not invoke)
  140. conforms to the C standard.
  141. """
  142. def strftime(format):
  143. """Return a string representing the date.
  144. Controlled by an explicit format string. Format codes referring to
  145. hours, minutes or seconds will see 0 values.
  146. """
  147. class IDateTimeClass(Interface):
  148. """This is the datetime class interface.
  149. This is symbolic; this module does **not** make
  150. `datetime.datetime` provide this interface.
  151. """
  152. min = Attribute("The earliest representable datetime")
  153. max = Attribute("The latest representable datetime")
  154. resolution = Attribute(
  155. "The smallest possible difference between non-equal datetime objects")
  156. def today():
  157. """Return the current local datetime, with tzinfo None.
  158. This is equivalent to ``datetime.fromtimestamp(time.time())``.
  159. .. seealso:: `now`, `fromtimestamp`.
  160. """
  161. def now(tz=None):
  162. """Return the current local date and time.
  163. If optional argument *tz* is None or not specified, this is like `today`,
  164. but, if possible, supplies more precision than can be gotten from going
  165. through a `time.time` timestamp (for example, this may be possible on
  166. platforms supplying the C ``gettimeofday()`` function).
  167. Else tz must be an instance of a class tzinfo subclass, and the current
  168. date and time are converted to tz's time zone. In this case the result
  169. is equivalent to tz.fromutc(datetime.utcnow().replace(tzinfo=tz)).
  170. .. seealso:: `today`, `utcnow`.
  171. """
  172. def utcnow():
  173. """Return the current UTC date and time, with tzinfo None.
  174. This is like `now`, but returns the current UTC date and time, as a
  175. naive datetime object.
  176. .. seealso:: `now`.
  177. """
  178. def fromtimestamp(timestamp, tz=None):
  179. """Return the local date and time corresponding to the POSIX timestamp.
  180. Same as is returned by time.time(). If optional argument tz is None or
  181. not specified, the timestamp is converted to the platform's local date
  182. and time, and the returned datetime object is naive.
  183. Else tz must be an instance of a class tzinfo subclass, and the
  184. timestamp is converted to tz's time zone. In this case the result is
  185. equivalent to
  186. ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
  187. fromtimestamp() may raise `ValueError`, if the timestamp is out of the
  188. range of values supported by the platform C localtime() or gmtime()
  189. functions. It's common for this to be restricted to years in 1970
  190. through 2038. Note that on non-POSIX systems that include leap seconds
  191. in their notion of a timestamp, leap seconds are ignored by
  192. fromtimestamp(), and then it's possible to have two timestamps
  193. differing by a second that yield identical datetime objects.
  194. .. seealso:: `utcfromtimestamp`.
  195. """
  196. def utcfromtimestamp(timestamp):
  197. """Return the UTC datetime from the POSIX timestamp with tzinfo None.
  198. This may raise `ValueError`, if the timestamp is out of the range of
  199. values supported by the platform C ``gmtime()`` function. It's common for
  200. this to be restricted to years in 1970 through 2038.
  201. .. seealso:: `fromtimestamp`.
  202. """
  203. def fromordinal(ordinal):
  204. """Return the datetime from the proleptic Gregorian ordinal.
  205. January 1 of year 1 has ordinal 1. `ValueError` is raised unless
  206. 1 <= ordinal <= datetime.max.toordinal().
  207. The hour, minute, second and microsecond of the result are all 0, and
  208. tzinfo is None.
  209. """
  210. def combine(date, time):
  211. """Return a new datetime object.
  212. Its date members are equal to the given date object's, and whose time
  213. and tzinfo members are equal to the given time object's. For any
  214. datetime object *d*, ``d == datetime.combine(d.date(), d.timetz())``.
  215. If date is a datetime object, its time and tzinfo members are ignored.
  216. """
  217. class IDateTime(IDate, IDateTimeClass):
  218. """Object contains all the information from a date object and a time object.
  219. Implemented by `datetime.datetime`.
  220. """
  221. year = Attribute("Year between MINYEAR and MAXYEAR inclusive")
  222. month = Attribute("Month between 1 and 12 inclusive")
  223. day = Attribute(
  224. "Day between 1 and the number of days in the given month of the year")
  225. hour = Attribute("Hour in range(24)")
  226. minute = Attribute("Minute in range(60)")
  227. second = Attribute("Second in range(60)")
  228. microsecond = Attribute("Microsecond in range(1000000)")
  229. tzinfo = Attribute(
  230. """The object passed as the tzinfo argument to the datetime constructor
  231. or None if none was passed""")
  232. def date():
  233. """Return date object with same year, month and day."""
  234. def time():
  235. """Return time object with same hour, minute, second, microsecond.
  236. tzinfo is None.
  237. .. seealso:: Method :meth:`timetz`.
  238. """
  239. def timetz():
  240. """Return time object with same hour, minute, second, microsecond,
  241. and tzinfo.
  242. .. seealso:: Method :meth:`time`.
  243. """
  244. def replace(year, month, day, hour, minute, second, microsecond, tzinfo):
  245. """Return a datetime with the same members, except for those members
  246. given new values by whichever keyword arguments are specified.
  247. Note that ``tzinfo=None`` can be specified to create a naive datetime from
  248. an aware datetime with no conversion of date and time members.
  249. """
  250. def astimezone(tz):
  251. """Return a datetime object with new tzinfo member tz, adjusting the
  252. date and time members so the result is the same UTC time as self, but
  253. in tz's local time.
  254. tz must be an instance of a tzinfo subclass, and its utcoffset() and
  255. dst() methods must not return None. self must be aware (self.tzinfo
  256. must not be None, and self.utcoffset() must not return None).
  257. If self.tzinfo is tz, self.astimezone(tz) is equal to self: no
  258. adjustment of date or time members is performed. Else the result is
  259. local time in time zone tz, representing the same UTC time as self:
  260. after astz = dt.astimezone(tz), astz - astz.utcoffset()
  261. will usually have the same date and time members as dt - dt.utcoffset().
  262. The discussion of class `datetime.tzinfo` explains the cases at Daylight Saving
  263. Time transition boundaries where this cannot be achieved (an issue only
  264. if tz models both standard and daylight time).
  265. If you merely want to attach a time zone object *tz* to a datetime *dt*
  266. without adjustment of date and time members, use ``dt.replace(tzinfo=tz)``.
  267. If you merely want to remove the time zone object from an aware
  268. datetime dt without conversion of date and time members, use
  269. ``dt.replace(tzinfo=None)``.
  270. Note that the default `tzinfo.fromutc` method can be overridden in a
  271. tzinfo subclass to effect the result returned by `astimezone`.
  272. """
  273. def utcoffset():
  274. """Return the timezone offset in minutes east of UTC (negative west of
  275. UTC)."""
  276. def dst():
  277. """Return 0 if DST is not in effect, or the DST offset (in minutes
  278. eastward) if DST is in effect.
  279. """
  280. def tzname():
  281. """Return the timezone name."""
  282. def timetuple():
  283. """Return a 9-element tuple of the form returned by `time.localtime`."""
  284. def utctimetuple():
  285. """Return UTC time tuple compatilble with `time.gmtime`."""
  286. def toordinal():
  287. """Return the proleptic Gregorian ordinal of the date.
  288. The same as self.date().toordinal().
  289. """
  290. def weekday():
  291. """Return the day of the week as an integer.
  292. Monday is 0 and Sunday is 6. The same as self.date().weekday().
  293. See also isoweekday().
  294. """
  295. def isoweekday():
  296. """Return the day of the week as an integer.
  297. Monday is 1 and Sunday is 7. The same as self.date().isoweekday.
  298. .. seealso:: `weekday`, `isocalendar`.
  299. """
  300. def isocalendar():
  301. """Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
  302. The same as self.date().isocalendar().
  303. """
  304. def isoformat(sep='T'):
  305. """Return a string representing the date and time in ISO 8601 format.
  306. YYYY-MM-DDTHH:MM:SS.mmmmmm or YYYY-MM-DDTHH:MM:SS if microsecond is 0
  307. If `utcoffset` does not return None, a 6-character string is appended,
  308. giving the UTC offset in (signed) hours and minutes:
  309. YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or YYYY-MM-DDTHH:MM:SS+HH:MM
  310. if microsecond is 0.
  311. The optional argument sep (default 'T') is a one-character separator,
  312. placed between the date and time portions of the result.
  313. """
  314. def __str__():
  315. """For a datetime instance *d*, ``str(d)`` is equivalent to ``d.isoformat(' ')``.
  316. """
  317. def ctime():
  318. """Return a string representing the date and time.
  319. ``datetime(2002, 12, 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``.
  320. ``d.ctime()`` is equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on
  321. platforms where the native C ``ctime()`` function (which `time.ctime`
  322. invokes, but which `datetime.ctime` does not invoke) conforms to the
  323. C standard.
  324. """
  325. def strftime(format):
  326. """Return a string representing the date and time.
  327. This is controlled by an explicit format string.
  328. """
  329. class ITimeClass(Interface):
  330. """This is the time class interface.
  331. This is symbolic; this module does **not** make
  332. `datetime.time` provide this interface.
  333. """
  334. min = Attribute("The earliest representable time")
  335. max = Attribute("The latest representable time")
  336. resolution = Attribute(
  337. "The smallest possible difference between non-equal time objects")
  338. class ITime(ITimeClass):
  339. """Represent time with time zone.
  340. Implemented by `datetime.time`.
  341. Operators:
  342. __repr__, __str__
  343. __cmp__, __hash__
  344. """
  345. hour = Attribute("Hour in range(24)")
  346. minute = Attribute("Minute in range(60)")
  347. second = Attribute("Second in range(60)")
  348. microsecond = Attribute("Microsecond in range(1000000)")
  349. tzinfo = Attribute(
  350. """The object passed as the tzinfo argument to the time constructor
  351. or None if none was passed.""")
  352. def replace(hour, minute, second, microsecond, tzinfo):
  353. """Return a time with the same value.
  354. Except for those members given new values by whichever keyword
  355. arguments are specified. Note that tzinfo=None can be specified
  356. to create a naive time from an aware time, without conversion of the
  357. time members.
  358. """
  359. def isoformat():
  360. """Return a string representing the time in ISO 8601 format.
  361. That is HH:MM:SS.mmmmmm or, if self.microsecond is 0, HH:MM:SS
  362. If utcoffset() does not return None, a 6-character string is appended,
  363. giving the UTC offset in (signed) hours and minutes:
  364. HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
  365. """
  366. def __str__():
  367. """For a time t, str(t) is equivalent to t.isoformat()."""
  368. def strftime(format):
  369. """Return a string representing the time.
  370. This is controlled by an explicit format string.
  371. """
  372. def utcoffset():
  373. """Return the timezone offset in minutes east of UTC (negative west of
  374. UTC).
  375. If tzinfo is None, returns None, else returns
  376. self.tzinfo.utcoffset(None), and raises an exception if the latter
  377. doesn't return None or a timedelta object representing a whole number
  378. of minutes with magnitude less than one day.
  379. """
  380. def dst():
  381. """Return 0 if DST is not in effect, or the DST offset (in minutes
  382. eastward) if DST is in effect.
  383. If tzinfo is None, returns None, else returns self.tzinfo.dst(None),
  384. and raises an exception if the latter doesn't return None, or a
  385. timedelta object representing a whole number of minutes with
  386. magnitude less than one day.
  387. """
  388. def tzname():
  389. """Return the timezone name.
  390. If tzinfo is None, returns None, else returns self.tzinfo.tzname(None),
  391. or raises an exception if the latter doesn't return None or a string
  392. object.
  393. """
  394. class ITZInfo(Interface):
  395. """Time zone info class.
  396. """
  397. def utcoffset(dt):
  398. """Return offset of local time from UTC, in minutes east of UTC.
  399. If local time is west of UTC, this should be negative.
  400. Note that this is intended to be the total offset from UTC;
  401. for example, if a tzinfo object represents both time zone and DST
  402. adjustments, utcoffset() should return their sum. If the UTC offset
  403. isn't known, return None. Else the value returned must be a timedelta
  404. object specifying a whole number of minutes in the range -1439 to 1439
  405. inclusive (1440 = 24*60; the magnitude of the offset must be less
  406. than one day).
  407. """
  408. def dst(dt):
  409. """Return the daylight saving time (DST) adjustment, in minutes east
  410. of UTC, or None if DST information isn't known.
  411. """
  412. def tzname(dt):
  413. """Return the time zone name corresponding to the datetime object as
  414. a string.
  415. """
  416. def fromutc(dt):
  417. """Return an equivalent datetime in self's local time."""
  418. classImplements(timedelta, ITimeDelta)
  419. classImplements(date, IDate)
  420. classImplements(datetime, IDateTime)
  421. classImplements(time, ITime)
  422. classImplements(tzinfo, ITZInfo)
  423. ## directlyProvides(timedelta, ITimeDeltaClass)
  424. ## directlyProvides(date, IDateClass)
  425. ## directlyProvides(datetime, IDateTimeClass)
  426. ## directlyProvides(time, ITimeClass)