datetime_math.py 11 KB

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