idatetime.py 21 KB

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