datetime_math.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. """!@package grass.temporal
  2. @brief GRASS Python scripting module (temporal GIS functions)
  3. Temporal GIS datetime math functions to be used in Python sripts.
  4. Usage:
  5. @code
  6. import grass.temporal as tgis
  7. tgis.increment_datetime_by_string(mydate, "3 month, 2 hours")
  8. ...
  9. @endcode
  10. (C) 2008-2011 by the GRASS Development Team
  11. This program is free software under the GNU General Public
  12. License (>=v2). Read the file COPYING that comes with GRASS
  13. for details.
  14. @author Soeren Gebbert
  15. """
  16. from datetime import datetime, date, time, timedelta
  17. import grass.script.core as core
  18. import copy
  19. ###############################################################################
  20. def increment_datetime_by_string(mydate, increment, mult = 1):
  21. """Return a new datetime object incremented with the provided relative dates specified as string.
  22. Additional a multiplier can be specified to multiply the increment bevor adding to the provided datetime object.
  23. @param mydate A datetime object to incremented
  24. @param increment A string providing increment information:
  25. The string may include comma separated values of type seconds, minutes, hours, days, weeks, months and years
  26. Example: Increment the datetime 2001-01-01 00:00:00 with "60 seconds, 4 minutes, 12 hours, 10 days, 1 weeks, 5 months, 1 years"
  27. will result in the datetime 2003-02-18 12:05:00
  28. @param mult A multiplier, default is 1
  29. """
  30. if increment:
  31. seconds = 0
  32. minutes = 0
  33. hours = 0
  34. days = 0
  35. weeks = 0
  36. months = 0
  37. years = 0
  38. inclist = []
  39. # Split the increment string
  40. incparts = increment.split(",")
  41. for incpart in incparts:
  42. inclist.append(incpart.strip().split(" "))
  43. for inc in inclist:
  44. if inc[1].find("seconds") >= 0:
  45. seconds = mult * int(inc[0])
  46. elif inc[1].find("minutes") >= 0:
  47. minutes = mult * int(inc[0])
  48. elif inc[1].find("hours") >= 0:
  49. hours = mult * int(inc[0])
  50. elif inc[1].find("days") >= 0:
  51. days = mult * int(inc[0])
  52. elif inc[1].find("weeks") >= 0:
  53. weeks = mult * int(inc[0])
  54. elif inc[1].find("months") >= 0:
  55. months = mult * int(inc[0])
  56. elif inc[1].find("years") >= 0:
  57. years = mult * int(inc[0])
  58. else:
  59. core.error(_("Wrong increment format: %s") % (increment))
  60. return None
  61. return increment_datetime(mydate, years, months, weeks, days, hours, minutes, seconds)
  62. return mydate
  63. ###############################################################################
  64. def test_increment_datetime_by_string():
  65. # First test
  66. print "# Test 1"
  67. dt = datetime(2001, 9, 1, 0, 0, 0)
  68. string = "60 seconds, 4 minutes, 12 hours, 10 days, 1 weeks, 5 months, 1 years"
  69. dt1 = datetime(2003,2,18,12,5,0)
  70. dt2 = increment_datetime_by_string(dt, string)
  71. print dt
  72. print dt2
  73. delta = dt1 -dt2
  74. if delta.days != 0 or delta.seconds != 0:
  75. core.error("increment computation is wrong %s" % (delta))
  76. # Second test
  77. print "# Test 2"
  78. dt = datetime(2001, 11, 1, 0, 0, 0)
  79. string = "1 months"
  80. dt1 = datetime(2001,12,1)
  81. dt2 = increment_datetime_by_string(dt, string)
  82. print dt
  83. print dt2
  84. delta = dt1 -dt2
  85. if delta.days != 0 or delta.seconds != 0:
  86. core.error("increment computation is wrong %s" % (delta))
  87. # Third test
  88. print "# Test 3"
  89. dt = datetime(2001, 11, 1, 0, 0, 0)
  90. string = "13 months"
  91. dt1 = datetime(2002,12,1)
  92. dt2 = increment_datetime_by_string(dt, string)
  93. print dt
  94. print dt2
  95. delta = dt1 -dt2
  96. if delta.days != 0 or delta.seconds != 0:
  97. core.error("increment computation is wrong %s" % (delta))
  98. # 4. test
  99. print "# Test 4"
  100. dt = datetime(2001, 1, 1, 0, 0, 0)
  101. string = "72 months"
  102. dt1 = datetime(2007,1,1)
  103. dt2 = increment_datetime_by_string(dt, string)
  104. print dt
  105. print dt2
  106. delta = dt1 -dt2
  107. if delta.days != 0 or delta.seconds != 0:
  108. core.error("increment computation is wrong %s" % (delta))
  109. ###############################################################################
  110. def increment_datetime(mydate, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0):
  111. """Return a new datetime object incremented with the provided relative dates and times"""
  112. tdelta_seconds = timedelta(seconds=seconds)
  113. tdelta_minutes = timedelta(minutes=minutes)
  114. tdelta_hours = timedelta(hours=hours)
  115. tdelta_days = timedelta(days=days)
  116. tdelta_weeks = timedelta(weeks=weeks)
  117. tdelta_months = timedelta(0)
  118. tdelta_years = timedelta(0)
  119. if months > 0:
  120. # Compute the actual number of days in the month to add as timedelta
  121. year = mydate.year
  122. month = mydate.month
  123. all_months = int(months) + int(month)
  124. years_to_add = int(all_months/12.001)
  125. residual_months = all_months - (years_to_add * 12)
  126. # Make a deep copy of the datetime object
  127. dt1 = copy.copy(mydate)
  128. # Make sure the montha starts with a 1
  129. if residual_months == 0:
  130. residual_months = 1
  131. dt1 = dt1.replace(year = year + years_to_add, month = residual_months)
  132. tdelta_months = dt1 - mydate
  133. if years > 0:
  134. # Make a deep copy of the datetime object
  135. dt1 = copy.copy(mydate)
  136. # Compute the number of days
  137. dt1 = dt1.replace(year=mydate.year + int(years))
  138. tdelta_years = dt1 - mydate
  139. return mydate + tdelta_seconds + tdelta_minutes + tdelta_hours + \
  140. tdelta_days + tdelta_weeks + tdelta_months + tdelta_years
  141. ###############################################################################
  142. def adjust_datetime_to_granularity(mydate, granularity):
  143. """Mofiy the datetime object to fit the given granularity """
  144. if granularity:
  145. has_seconds = False
  146. has_minutes = False
  147. has_hours = False
  148. has_days = False
  149. has_weeks = False
  150. has_months = False
  151. has_years = False
  152. seconds = mydate.second
  153. minutes = mydate.minute
  154. hours = mydate.hour
  155. days = mydate.day
  156. weekday = mydate.weekday()
  157. months = mydate.month
  158. years = mydate.year
  159. granlist = []
  160. # Split the increment string
  161. granparts = granularity.split(",")
  162. for granpart in granparts:
  163. granlist.append(granpart.strip().split(" "))
  164. for inc in granlist:
  165. if inc[1].find("seconds") >= 0:
  166. has_seconds = True
  167. elif inc[1].find("minutes") >= 0:
  168. has_minutes = True
  169. elif inc[1].find("hours") >= 0:
  170. has_hours = True
  171. elif inc[1].find("days") >= 0:
  172. has_days = True
  173. elif inc[1].find("weeks") >= 0:
  174. has_weeks = True
  175. elif inc[1].find("months") >= 0:
  176. has_months = True
  177. elif inc[1].find("years") >= 0:
  178. has_years = True
  179. else:
  180. core.error(_("Wrong granularity format: %s") % (granularity))
  181. return None
  182. if has_seconds:
  183. pass
  184. elif has_minutes: # Start at 0 seconds
  185. seconds = 0
  186. elif has_hours: # Start at 0 minutes and seconds
  187. seconds = 0
  188. minutes = 0
  189. elif has_days: # Start at 0 hours, minuts and seconds
  190. seconds = 0
  191. minutes = 0
  192. hours = 0
  193. elif has_weeks: # Start at the first day of the week (monday) at 00:00:00
  194. seconds = 0
  195. minutes = 0
  196. hours = 0
  197. days = days - weekday
  198. elif has_months: # Start at the first day of the month at 00:00:00
  199. seconds = 0
  200. minutes = 0
  201. hours = 0
  202. days = 1
  203. elif has_years: # Start at the first day of the first month at 00:00:00
  204. seconds = 0
  205. minutes = 0
  206. hours = 0
  207. days = 1
  208. months = 1
  209. dt = copy.copy(mydate)
  210. result = dt.replace(year=years, month=months, day=days, hour=hours, minute=minutes, second=seconds)
  211. core.verbose(_("Adjust datetime from %s to %s with granularity %s") % (dt, result, granularity))
  212. return result
  213. def test_adjust_datetime_to_granularity():
  214. # First test
  215. print "Test 1"
  216. dt = datetime(2001, 8, 8, 12,30,30)
  217. result = adjust_datetime_to_granularity(dt, "5 seconds")
  218. correct = datetime(2001, 8, 8, 12,30,30)
  219. delta = correct - result
  220. if delta.days != 0 or delta.seconds != 0:
  221. core.error("Granularity adjustment computation is wrong %s" % (delta))
  222. # Second test
  223. print "Test 2"
  224. result = adjust_datetime_to_granularity(dt, "20 minutes")
  225. correct = datetime(2001, 8, 8, 12,30,00)
  226. delta = correct - result
  227. if delta.days != 0 or delta.seconds != 0:
  228. core.error("Granularity adjustment computation is wrong %s" % (delta))
  229. # Third test
  230. print "Test 2"
  231. result = adjust_datetime_to_granularity(dt, "20 minutes")
  232. correct = datetime(2001, 8, 8, 12,30,00)
  233. delta = correct - result
  234. if delta.days != 0 or delta.seconds != 0:
  235. core.error("Granularity adjustment computation is wrong %s" % (delta))
  236. # 4. test
  237. print "Test 4"
  238. result = adjust_datetime_to_granularity(dt, "3 hours")
  239. correct = datetime(2001, 8, 8, 12,00,00)
  240. delta = correct - result
  241. if delta.days != 0 or delta.seconds != 0:
  242. core.error("Granularity adjustment computation is wrong %s" % (delta))
  243. # 5. test
  244. print "Test 5"
  245. result = adjust_datetime_to_granularity(dt, "5 days")
  246. correct = datetime(2001, 8, 8, 00,00,00)
  247. delta = correct - result
  248. if delta.days != 0 or delta.seconds != 0:
  249. core.error("Granularity adjustment computation is wrong %s" % (delta))
  250. # 6. test
  251. print "Test 6"
  252. result = adjust_datetime_to_granularity(dt, "2 weeks")
  253. correct = datetime(2001, 8, 6, 00,00,00)
  254. delta = correct - result
  255. if delta.days != 0 or delta.seconds != 0:
  256. core.error("Granularity adjustment computation is wrong %s" % (delta))
  257. # 7. test
  258. print "Test 7"
  259. result = adjust_datetime_to_granularity(dt, "6 months")
  260. correct = datetime(2001, 8, 1, 00,00,00)
  261. delta = correct - result
  262. if delta.days != 0 or delta.seconds != 0:
  263. core.error("Granularity adjustment computation is wrong %s" % (delta))
  264. # 8. test
  265. print "Test 8"
  266. result = adjust_datetime_to_granularity(dt, "2 years")
  267. correct = datetime(2001, 1, 1, 00,00,00)
  268. delta = correct - result
  269. if delta.days != 0 or delta.seconds != 0:
  270. core.error("Granularity adjustment computation is wrong %s" % (delta))
  271. # 9. test
  272. print "Test 9"
  273. result = adjust_datetime_to_granularity(dt, "2 years, 3 months, 5 days, 3 hours, 3 minutes, 2 seconds")
  274. correct = datetime(2001, 8, 8, 12,30,30)
  275. delta = correct - result
  276. if delta.days != 0 or delta.seconds != 0:
  277. core.error("Granularity adjustment computation is wrong %s" % (delta))
  278. # 10. test
  279. print "Test 10"
  280. result = adjust_datetime_to_granularity(dt, "3 months, 5 days, 3 minutes")
  281. correct = datetime(2001, 8, 8, 12,30,00)
  282. delta = correct - result
  283. if delta.days != 0 or delta.seconds != 0:
  284. core.error("Granularity adjustment computation is wrong %s" % (delta))
  285. # 11. test
  286. print "Test 11"
  287. result = adjust_datetime_to_granularity(dt, "3 weeks, 5 days")
  288. correct = datetime(2001, 8, 8, 00,00,00)
  289. delta = correct - result
  290. if delta.days != 0 or delta.seconds != 0:
  291. core.error("Granularity adjustment computation is wrong %s" % (delta))