datetime_math.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. """!@package grass.temporal
  2. @brief GRASS Python scripting module (temporal GIS functions)
  3. Temporal GIS datetime math functions to be used in Python scripts.
  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 before 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 month 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. if days > weekday:
  168. days = days - weekday # this needs to be fixed
  169. else:
  170. days = days + weekday # this needs to be fixed
  171. elif has_months: # Start at the first day of the month at 00:00:00
  172. seconds = 0
  173. minutes = 0
  174. hours = 0
  175. days = 1
  176. elif has_years: # Start at the first day of the first month at 00:00:00
  177. seconds = 0
  178. minutes = 0
  179. hours = 0
  180. days = 1
  181. months = 1
  182. dt = copy.copy(mydate)
  183. result = dt.replace(year=years, month=months, day=days, hour=hours, minute=minutes, second=seconds)
  184. core.verbose(_("Adjust datetime from %s to %s with granularity %s") % (dt, result, granularity))
  185. return result
  186. ###############################################################################
  187. def compute_datetime_delta(start, end):
  188. """!Return a dictionary with the accumulated delta in year, month, day, hour, minute and second
  189. @return A dictionary with year, month, day, hour, minute and second as keys()
  190. """
  191. comp = {}
  192. day_diff = (end - start).days
  193. comp["max_days"] = day_diff
  194. # Date
  195. # Count full years
  196. d = end.year - start.year
  197. comp["year"] = d
  198. # Count full months
  199. if start.month == 1 and end.month == 1:
  200. comp["month"] = 0
  201. elif start.day == 1 and end.day == 1:
  202. d = end.month - start.month
  203. if d < 0:
  204. d = d + 12 * comp["year"]
  205. elif d == 0:
  206. d = 12 * comp["year"]
  207. comp["month"] = d
  208. # Count full days
  209. if start.day == 1 and end.day == 1:
  210. comp["day"] = 0
  211. else:
  212. comp["day"] = day_diff
  213. # Time
  214. # Hours
  215. if start.hour == 0 and end.hour == 0:
  216. comp["hour"] = 0
  217. else:
  218. d = end.hour - start.hour
  219. if d < 0:
  220. d = d + 24 + 24 * day_diff
  221. else:
  222. d = d + 24 * day_diff
  223. comp["hour"] = d
  224. # Minutes
  225. if start.minute == 0 and end.minute == 0:
  226. comp["minute"] = 0
  227. else:
  228. d = end.minute - start.minute
  229. if d != 0:
  230. if comp["hour"]:
  231. d = d + 60 * comp["hour"]
  232. else:
  233. d = d + 24 * 60 * day_diff
  234. elif d == 0:
  235. if comp["hour"]:
  236. d = 60* comp["hour"]
  237. else:
  238. d = 24 * 60 * day_diff
  239. comp["minute"] = d
  240. # Seconds
  241. if start.second == 0 and end.second == 0:
  242. comp["second"] = 0
  243. else:
  244. d = end.second - start.second
  245. if d != 0:
  246. if comp["minute"]:
  247. d = d + 60* comp["minute"]
  248. elif comp["hour"]:
  249. d = d + 3600* comp["hour"]
  250. else:
  251. d = d + 24 * 60 * 60 * day_diff
  252. elif d == 0:
  253. if comp["minute"]:
  254. d = 60* comp["minute"]
  255. elif comp["hour"]:
  256. d = 3600 * comp["hour"]
  257. else:
  258. d = 24 * 60 * 60 * day_diff
  259. comp["second"] = d
  260. return comp
  261. ###############################################################################
  262. def string_to_datetime(time_string):
  263. """!Convert a string into a datetime object using the dateutil parser. Return None in case of failure"""
  264. # BC is not supported
  265. if time_string.find("bc") > 0:
  266. core.error("Dates Before Christ are not supported in the temporal database")
  267. return None
  268. try:
  269. dt = parser.parse(time_string)
  270. return dt
  271. except:
  272. return None
  273. ###############################################################################
  274. def datetime_to_grass_datetime_string(dt):
  275. """!Convert a python datetime object into a GRASS datetime string"""
  276. # GRASS datetime month names
  277. month_names = ["", "jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"]
  278. # Check for time zone info in the datetime object
  279. if dt.tzinfo != None:
  280. string = "%.2i %s %.2i %.2i:%.2i:%.2i %+.4i"%(dt.day, month_names[dt.month], dt.year, \
  281. dt.hour, dt.minute, dt.second, dt.tzinfo._offset.seconds/60)
  282. else:
  283. string = "%.2i %s %.4i %.2i:%.2i:%.2i"%(dt.day, month_names[dt.month], dt.year, dt.hour, dt.minute, dt.second)
  284. return string