datetime_math.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. from dateutil import parser
  20. ###############################################################################
  21. def relative_time_to_time_delta(value):
  22. """Convert the double value representing days
  23. into a timedelta object.
  24. """
  25. days = int(value)
  26. seconds = value % 1
  27. seconds = round(seconds * 86400)
  28. return timedelta(days, seconds)
  29. ###############################################################################
  30. def time_delta_to_relative_time(delta):
  31. """Convert the time delta into a
  32. double value, representing days.
  33. """
  34. return float(delta.days) + float(delta.seconds/86400.0)
  35. ###############################################################################
  36. def increment_datetime_by_string(mydate, increment, mult = 1):
  37. """Return a new datetime object incremented with the provided relative dates specified as string.
  38. Additional a multiplier can be specified to multiply the increment bevor adding to the provided datetime object.
  39. @param mydate A datetime object to incremented
  40. @param increment A string providing increment information:
  41. The string may include comma separated values of type seconds, minutes, hours, days, weeks, months and years
  42. 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"
  43. will result in the datetime 2003-02-18 12:05:00
  44. @param mult A multiplier, default is 1
  45. """
  46. if increment:
  47. seconds = 0
  48. minutes = 0
  49. hours = 0
  50. days = 0
  51. weeks = 0
  52. months = 0
  53. years = 0
  54. inclist = []
  55. # Split the increment string
  56. incparts = increment.split(",")
  57. for incpart in incparts:
  58. inclist.append(incpart.strip().split(" "))
  59. for inc in inclist:
  60. if inc[1].find("seconds") >= 0:
  61. seconds = mult * int(inc[0])
  62. elif inc[1].find("minutes") >= 0:
  63. minutes = mult * int(inc[0])
  64. elif inc[1].find("hours") >= 0:
  65. hours = mult * int(inc[0])
  66. elif inc[1].find("days") >= 0:
  67. days = mult * int(inc[0])
  68. elif inc[1].find("weeks") >= 0:
  69. weeks = mult * int(inc[0])
  70. elif inc[1].find("months") >= 0:
  71. months = mult * int(inc[0])
  72. elif inc[1].find("years") >= 0:
  73. years = mult * int(inc[0])
  74. else:
  75. core.error(_("Wrong increment format: %s") % (increment))
  76. return None
  77. return increment_datetime(mydate, years, months, weeks, days, hours, minutes, seconds)
  78. return mydate
  79. ###############################################################################
  80. def increment_datetime(mydate, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0):
  81. """Return a new datetime object incremented with the provided relative dates and times"""
  82. tdelta_seconds = timedelta(seconds=seconds)
  83. tdelta_minutes = timedelta(minutes=minutes)
  84. tdelta_hours = timedelta(hours=hours)
  85. tdelta_days = timedelta(days=days)
  86. tdelta_weeks = timedelta(weeks=weeks)
  87. tdelta_months = timedelta(0)
  88. tdelta_years = timedelta(0)
  89. if months > 0:
  90. # Compute the actual number of days in the month to add as timedelta
  91. year = mydate.year
  92. month = mydate.month
  93. all_months = int(months) + int(month)
  94. years_to_add = int(all_months/12.001)
  95. residual_months = all_months - (years_to_add * 12)
  96. # Make a deep copy of the datetime object
  97. dt1 = copy.copy(mydate)
  98. # Make sure the montha starts with a 1
  99. if residual_months == 0:
  100. residual_months = 1
  101. dt1 = dt1.replace(year = year + years_to_add, month = residual_months)
  102. tdelta_months = dt1 - mydate
  103. if years > 0:
  104. # Make a deep copy of the datetime object
  105. dt1 = copy.copy(mydate)
  106. # Compute the number of days
  107. dt1 = dt1.replace(year=mydate.year + int(years))
  108. tdelta_years = dt1 - mydate
  109. return mydate + tdelta_seconds + tdelta_minutes + tdelta_hours + \
  110. tdelta_days + tdelta_weeks + tdelta_months + tdelta_years
  111. ###############################################################################
  112. def adjust_datetime_to_granularity(mydate, granularity):
  113. """Mofiy the datetime object to fit the given granularity """
  114. if granularity:
  115. has_seconds = False
  116. has_minutes = False
  117. has_hours = False
  118. has_days = False
  119. has_weeks = False
  120. has_months = False
  121. has_years = False
  122. seconds = mydate.second
  123. minutes = mydate.minute
  124. hours = mydate.hour
  125. days = mydate.day
  126. weekday = mydate.weekday()
  127. months = mydate.month
  128. years = mydate.year
  129. granlist = []
  130. # Split the increment string
  131. granparts = granularity.split(",")
  132. for granpart in granparts:
  133. granlist.append(granpart.strip().split(" "))
  134. for inc in granlist:
  135. if inc[1].find("seconds") >= 0:
  136. has_seconds = True
  137. elif inc[1].find("minutes") >= 0:
  138. has_minutes = True
  139. elif inc[1].find("hours") >= 0:
  140. has_hours = True
  141. elif inc[1].find("days") >= 0:
  142. has_days = True
  143. elif inc[1].find("weeks") >= 0:
  144. has_weeks = True
  145. elif inc[1].find("months") >= 0:
  146. has_months = True
  147. elif inc[1].find("years") >= 0:
  148. has_years = True
  149. else:
  150. core.error(_("Wrong granularity format: %s") % (granularity))
  151. return None
  152. if has_seconds:
  153. pass
  154. elif has_minutes: # Start at 0 seconds
  155. seconds = 0
  156. elif has_hours: # Start at 0 minutes and seconds
  157. seconds = 0
  158. minutes = 0
  159. elif has_days: # Start at 0 hours, minuts and seconds
  160. seconds = 0
  161. minutes = 0
  162. hours = 0
  163. elif has_weeks: # Start at the first day of the week (monday) at 00:00:00
  164. seconds = 0
  165. minutes = 0
  166. hours = 0
  167. days = days - weekday
  168. elif has_months: # Start at the first day of the month at 00:00:00
  169. seconds = 0
  170. minutes = 0
  171. hours = 0
  172. days = 1
  173. elif has_years: # Start at the first day of the first month at 00:00:00
  174. seconds = 0
  175. minutes = 0
  176. hours = 0
  177. days = 1
  178. months = 1
  179. dt = copy.copy(mydate)
  180. result = dt.replace(year=years, month=months, day=days, hour=hours, minute=minutes, second=seconds)
  181. core.verbose(_("Adjust datetime from %s to %s with granularity %s") % (dt, result, granularity))
  182. return result
  183. ###############################################################################
  184. def compute_datetime_delta(start, end):
  185. """Return a dictionary with the accumulated delta in year, month, day, hour, minute and second
  186. @return A dictionary with year, month, day, hour, minute and second as keys()
  187. """
  188. comp = {}
  189. day_diff = (end - start).days
  190. comp["max_days"] = day_diff
  191. # Date
  192. # Count full years
  193. d = end.year - start.year
  194. comp["year"] = d
  195. # Count full months
  196. if start.month == 1 and end.month == 1:
  197. comp["month"] = 0
  198. elif start.day == 1 and end.day == 1:
  199. d = end.month - start.month
  200. if d < 0:
  201. d = d + 12 * comp["year"]
  202. elif d == 0:
  203. d = 12 * comp["year"]
  204. comp["month"] = d
  205. # Count full days
  206. if start.day == 1 and end.day == 1:
  207. comp["day"] = 0
  208. else:
  209. comp["day"] = day_diff
  210. # Time
  211. # Hours
  212. if start.hour == 0 and end.hour == 0:
  213. comp["hour"] = 0
  214. else:
  215. d = end.hour - start.hour
  216. if d < 0:
  217. d = d + 24 + 24 * day_diff
  218. else:
  219. d = d + 24 * day_diff
  220. comp["hour"] = d
  221. # Minutes
  222. if start.minute == 0 and end.minute == 0:
  223. comp["minute"] = 0
  224. else:
  225. d = end.minute - start.minute
  226. if d != 0:
  227. if comp["hour"]:
  228. d = d + 60 * comp["hour"]
  229. else:
  230. d = d + 24 * 60 * day_diff
  231. elif d == 0:
  232. if comp["hour"]:
  233. d = 60* comp["hour"]
  234. else:
  235. d = 24 * 60 * day_diff
  236. comp["minute"] = d
  237. # Seconds
  238. if start.second == 0 and end.second == 0:
  239. comp["second"] = 0
  240. else:
  241. d = end.second - start.second
  242. if d != 0:
  243. if comp["minute"]:
  244. d = d + 60* comp["minute"]
  245. elif comp["hour"]:
  246. d = d + 3600* comp["hour"]
  247. else:
  248. d = d + 24 * 60 * 60 * day_diff
  249. elif d == 0:
  250. if comp["minute"]:
  251. d = 60* comp["minute"]
  252. elif comp["hour"]:
  253. d = 3600 * comp["hour"]
  254. else:
  255. d = 24 * 60 * 60 * day_diff
  256. comp["second"] = d
  257. return comp
  258. ###############################################################################
  259. def string_to_datetime(time_string):
  260. """Convert a string into a datetime object using the dateutil parser. Return None in case of failure"""
  261. # BC is not suported
  262. if time_string.find("bc") > 0:
  263. core.error("Dates Before Christ are not supported in the temporal database")
  264. return None
  265. try:
  266. dt = parser.parse(time_string)
  267. return dt
  268. except:
  269. return None
  270. ###############################################################################
  271. def datetime_to_grass_datetime_string(dt):
  272. """Convert a python datetime object into a GRASS datetime string"""
  273. # GRASS datetime month names
  274. month_names = ["", "jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"]
  275. # Check for time zone infor in the datetime object
  276. if dt.tzinfo != None:
  277. string = "%.2i %s %.2i %.2i:%.2i:%.2i %+.4i"%(dt.day, month_names[dt.month], dt.year, \
  278. dt.hour, dt.minute, dt.second, dt.tzinfo._offset.seconds/3600*100)
  279. else:
  280. string = "%.2i %s %.4i %.2i:%.2i:%.2i"%(dt.day, month_names[dt.month], dt.year, dt.hour, dt.minute, dt.second)
  281. return string