datetime_math.py 11 KB

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