idatetime.py 20 KB

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