datetime_math.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. """!@package grass.temporal
  2. @brief GRASS Python scripting module (temporal GIS functions)
  3. Temporal GIS datetime math functions to be used in library functions and modules.
  4. (C) 2011-2013 by the GRASS Development Team
  5. This program is free software under the GNU General Public
  6. License (>=v2). Read the file COPYING that comes with GRASS
  7. for details.
  8. @author Soeren Gebbert
  9. """
  10. from datetime import datetime, date, time, timedelta
  11. import grass.script.core as core
  12. import copy
  13. DAY_IN_SECONDS = 86400
  14. SECOND_AS_DAY = 1.1574074074074073e-05
  15. ###############################################################################
  16. def relative_time_to_time_delta(value):
  17. """!Convert the double value representing days
  18. into a timedelta object.
  19. """
  20. days = int(value)
  21. seconds = value % 1
  22. seconds = round(seconds * DAY_IN_SECONDS)
  23. return timedelta(days, seconds)
  24. ###############################################################################
  25. def time_delta_to_relative_time(delta):
  26. """!Convert the time delta into a
  27. double value, representing days.
  28. """
  29. return float(delta.days) + float(delta.seconds * SECOND_AS_DAY)
  30. ###############################################################################
  31. def decrement_datetime_by_string(mydate, increment, mult=1):
  32. """!Return a new datetime object decremented with the provided
  33. relative dates specified as string.
  34. Additional a multiplier can be specified to multiply the increment
  35. before adding to the provided datetime object.
  36. Usage:
  37. @code
  38. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  39. >>> string = "31 days"
  40. >>> decrement_datetime_by_string(dt, string)
  41. datetime.datetime(2000, 12, 1, 0, 0)
  42. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  43. >>> string = "1 month"
  44. >>> decrement_datetime_by_string(dt, string)
  45. datetime.datetime(2000, 12, 1, 0, 0)
  46. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  47. >>> string = "2 month"
  48. >>> decrement_datetime_by_string(dt, string)
  49. datetime.datetime(2000, 11, 1, 0, 0)
  50. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  51. >>> string = "24 months"
  52. >>> decrement_datetime_by_string(dt, string)
  53. datetime.datetime(1999, 1, 1, 0, 0)
  54. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  55. >>> string = "48 months"
  56. >>> decrement_datetime_by_string(dt, string)
  57. datetime.datetime(1997, 1, 1, 0, 0)
  58. >>> dt = datetime(2001, 6, 1, 0, 0, 0)
  59. >>> string = "5 months"
  60. >>> decrement_datetime_by_string(dt, string)
  61. datetime.datetime(2001, 1, 1, 0, 0)
  62. >>> dt = datetime(2001, 6, 1, 0, 0, 0)
  63. >>> string = "7 months"
  64. >>> decrement_datetime_by_string(dt, string)
  65. datetime.datetime(2000, 11, 1, 0, 0)
  66. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  67. >>> string = "1 year"
  68. >>> decrement_datetime_by_string(dt, string)
  69. datetime.datetime(2000, 1, 1, 0, 0)
  70. @endcode
  71. @param mydate A datetime object to incremented
  72. @param increment A string providing increment information:
  73. The string may include comma separated values of type seconds,
  74. minutes, hours, days, weeks, months and years
  75. Example: Increment the datetime 2001-01-01 00:00:00
  76. with "60 seconds, 4 minutes, 12 hours, 10 days, 1 weeks, 5 months, 1 years"
  77. will result in the datetime 2003-02-18 12:05:00
  78. @param mult A multiplier, default is 1
  79. @return The new datetime object or none in case of an error
  80. """
  81. return modify_datetime_by_string(mydate, increment, mult, sign=int(-1))
  82. ###############################################################################
  83. def increment_datetime_by_string(mydate, increment, mult=1):
  84. """!Return a new datetime object incremented with the provided
  85. relative dates specified as string.
  86. Additional a multiplier can be specified to multiply the increment
  87. before adding to the provided datetime object.
  88. Usage:
  89. @code
  90. >>> dt = datetime(2001, 9, 1, 0, 0, 0)
  91. >>> string = "60 seconds, 4 minutes, 12 hours, 10 days, 1 weeks, 5 months, 1 years"
  92. >>> increment_datetime_by_string(dt, string)
  93. datetime.datetime(2003, 2, 18, 12, 5)
  94. >>> dt = datetime(2001, 11, 1, 0, 0, 0)
  95. >>> string = "1 months"
  96. >>> increment_datetime_by_string(dt, string)
  97. datetime.datetime(2001, 12, 1, 0, 0)
  98. >>> dt = datetime(2001, 11, 1, 0, 0, 0)
  99. >>> string = "13 months"
  100. >>> increment_datetime_by_string(dt, string)
  101. datetime.datetime(2002, 12, 1, 0, 0)
  102. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  103. >>> string = "72 months"
  104. >>> increment_datetime_by_string(dt, string)
  105. datetime.datetime(2007, 1, 1, 0, 0)
  106. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  107. >>> string = "72 months"
  108. >>> increment_datetime_by_string(dt, string)
  109. datetime.datetime(2007, 1, 1, 0, 0)
  110. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  111. >>> string = "5 minutes"
  112. >>> increment_datetime_by_string(dt, string)
  113. datetime.datetime(2001, 1, 1, 0, 5)
  114. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  115. >>> string = "49 hours"
  116. >>> increment_datetime_by_string(dt, string)
  117. datetime.datetime(2001, 1, 3, 1, 0)
  118. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  119. >>> string = "3600 seconds"
  120. >>> increment_datetime_by_string(dt, string)
  121. datetime.datetime(2001, 1, 1, 1, 0)
  122. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  123. >>> string = "30 days"
  124. >>> increment_datetime_by_string(dt, string)
  125. datetime.datetime(2001, 1, 31, 0, 0)
  126. @endcode
  127. @param mydate A datetime object to incremented
  128. @param increment A string providing increment information:
  129. The string may include comma separated values of type seconds,
  130. minutes, hours, days, weeks, months and years
  131. Example: Increment the datetime 2001-01-01 00:00:00
  132. with "60 seconds, 4 minutes, 12 hours, 10 days, 1 weeks, 5 months, 1 years"
  133. will result in the datetime 2003-02-18 12:05:00
  134. @param mult A multiplier, default is 1
  135. @return The new datetime object or none in case of an error
  136. """
  137. return modify_datetime_by_string(mydate, increment, mult, sign=int(1))
  138. ###############################################################################
  139. def modify_datetime_by_string(mydate, increment, mult=1, sign=1):
  140. """!Return a new datetime object incremented with the provided
  141. relative dates specified as string.
  142. Additional a multiplier can be specified to multiply the increment
  143. before adding to the provided datetime object.
  144. @param mydate A datetime object to incremented
  145. @param increment A string providing increment information:
  146. The string may include comma separated values of type seconds,
  147. minutes, hours, days, weeks, months and years
  148. Example: Increment the datetime 2001-01-01 00:00:00
  149. with "60 seconds, 4 minutes, 12 hours, 10 days, 1 weeks, 5 months, 1 years"
  150. will result in the datetime 2003-02-18 12:05:00
  151. @param mult A multiplier, default is 1
  152. @param sign Choose 1 for positive sign (incrementing) or -1 for negative
  153. sign (decrementing).
  154. @return The new datetime object or none in case of an error
  155. """
  156. sign = int(sign)
  157. if sign != 1 and sign != -1:
  158. return None
  159. if increment:
  160. seconds = 0
  161. minutes = 0
  162. hours = 0
  163. days = 0
  164. weeks = 0
  165. months = 0
  166. years = 0
  167. inclist = []
  168. # Split the increment string
  169. incparts = increment.split(",")
  170. for incpart in incparts:
  171. inclist.append(incpart.strip().split(" "))
  172. for inc in inclist:
  173. if len(inc) < 2:
  174. core.error(_("Wrong increment format: %s") % (increment))
  175. return None
  176. if inc[1].find("seconds") >= 0 or inc[1].find("second") >= 0:
  177. seconds = sign * mult * int(inc[0])
  178. elif inc[1].find("minutes") >= 0 or inc[1].find("minute") >= 0:
  179. minutes = sign * mult * int(inc[0])
  180. elif inc[1].find("hours") >= 0 or inc[1].find("hour") >= 0:
  181. hours = sign * mult * int(inc[0])
  182. elif inc[1].find("days") >= 0 or inc[1].find("day") >= 0:
  183. days = sign * mult * int(inc[0])
  184. elif inc[1].find("weeks") >= 0 or inc[1].find("week") >= 0:
  185. weeks = sign * mult * int(inc[0])
  186. elif inc[1].find("months") >= 0 or inc[1].find("month") >= 0:
  187. months = sign * mult * int(inc[0])
  188. elif inc[1].find("years") >= 0 or inc[1].find("year") >= 0:
  189. years = sign * mult * int(inc[0])
  190. else:
  191. core.error(_("Wrong increment format: %s") % (increment))
  192. return None
  193. return modify_datetime(mydate, years, months, weeks, days, hours, minutes, seconds)
  194. return mydate
  195. ###############################################################################
  196. def modify_datetime(mydate, years=0, months=0, weeks=0, days=0, hours=0,
  197. minutes=0, seconds=0):
  198. """!Return a new datetime object incremented with the provided
  199. relative dates and times"""
  200. tdelta_seconds = timedelta(seconds=seconds)
  201. tdelta_minutes = timedelta(minutes=minutes)
  202. tdelta_hours = timedelta(hours=hours)
  203. tdelta_days = timedelta(days=days)
  204. tdelta_weeks = timedelta(weeks=weeks)
  205. tdelta_months = timedelta(0)
  206. tdelta_years = timedelta(0)
  207. if months > 0:
  208. # Compute the actual number of days in the month to add as timedelta
  209. year = mydate.year
  210. month = mydate.month
  211. all_months = int(months) + int(month)
  212. years_to_add = int(all_months / 12.001)
  213. residual_months = all_months - (years_to_add * 12)
  214. # Make a deep copy of the datetime object
  215. dt1 = copy.copy(mydate)
  216. # Make sure the month starts with a 1
  217. if residual_months == 0:
  218. residual_months = 1
  219. try:
  220. dt1 = dt1.replace(year=year + years_to_add, month=residual_months)
  221. except:
  222. raise
  223. tdelta_months = dt1 - mydate
  224. elif months < 0:
  225. # Compute the actual number of days in the month to add as timedelta
  226. year = mydate.year
  227. month = mydate.month
  228. years_to_remove = 0
  229. all_months = int(months) + int(month)
  230. if all_months <= 0:
  231. years_to_remove = abs(int(all_months / 12.001))
  232. residual_months = all_months + (years_to_remove * 12)
  233. years_to_remove += 1
  234. else:
  235. residual_months = all_months
  236. # Make a deep copy of the datetime object
  237. dt1 = copy.copy(mydate)
  238. # Correct the months
  239. if residual_months <= 0:
  240. residual_months += 12
  241. try:
  242. dt1 = dt1.replace(year=year - years_to_remove, month=residual_months)
  243. except:
  244. raise
  245. tdelta_months = dt1 - mydate
  246. if years != 0:
  247. # Make a deep copy of the datetime object
  248. dt1 = copy.copy(mydate)
  249. # Compute the number of days
  250. dt1 = dt1.replace(year=mydate.year + int(years))
  251. tdelta_years = dt1 - mydate
  252. return mydate + tdelta_seconds + tdelta_minutes + tdelta_hours + \
  253. tdelta_days + tdelta_weeks + tdelta_months + tdelta_years
  254. ###############################################################################
  255. def adjust_datetime_to_granularity(mydate, granularity):
  256. """!Modify the datetime object to fit the given granularity
  257. - Years will start at the first of Januar
  258. - Months will start at the first day of the month
  259. - Days will start at the first Hour of the day
  260. - Hours will start at the first minute of an hour
  261. - Minutes will start at the first second of a minute
  262. Usage:
  263. @code
  264. >>> dt = datetime(2001, 8, 8, 12,30,30)
  265. >>> adjust_datetime_to_granularity(dt, "5 seconds")
  266. datetime.datetime(2001, 8, 8, 12, 30, 30)
  267. >>> adjust_datetime_to_granularity(dt, "20 minutes")
  268. datetime.datetime(2001, 8, 8, 12, 30)
  269. >>> adjust_datetime_to_granularity(dt, "20 minutes")
  270. datetime.datetime(2001, 8, 8, 12, 30)
  271. >>> adjust_datetime_to_granularity(dt, "3 hours")
  272. datetime.datetime(2001, 8, 8, 12, 0)
  273. >>> adjust_datetime_to_granularity(dt, "5 days")
  274. datetime.datetime(2001, 8, 8, 0, 0)
  275. >>> adjust_datetime_to_granularity(dt, "2 weeks")
  276. datetime.datetime(2001, 8, 6, 0, 0)
  277. >>> adjust_datetime_to_granularity(dt, "6 months")
  278. datetime.datetime(2001, 8, 1, 0, 0)
  279. >>> adjust_datetime_to_granularity(dt, "2 years")
  280. datetime.datetime(2001, 1, 1, 0, 0)
  281. >>> adjust_datetime_to_granularity(dt, "2 years, 3 months, 5 days, 3 hours, 3 minutes, 2 seconds")
  282. datetime.datetime(2001, 8, 8, 12, 30, 30)
  283. >>> adjust_datetime_to_granularity(dt, "3 months, 5 days, 3 minutes")
  284. datetime.datetime(2001, 8, 8, 12, 30)
  285. >>> adjust_datetime_to_granularity(dt, "3 weeks, 5 days")
  286. datetime.datetime(2001, 8, 8, 0, 0)
  287. @endcode
  288. """
  289. if granularity:
  290. has_seconds = False
  291. has_minutes = False
  292. has_hours = False
  293. has_days = False
  294. has_weeks = False
  295. has_months = False
  296. has_years = False
  297. seconds = mydate.second
  298. minutes = mydate.minute
  299. hours = mydate.hour
  300. days = mydate.day
  301. weekday = mydate.weekday()
  302. months = mydate.month
  303. years = mydate.year
  304. granlist = []
  305. # Split the increment string
  306. granparts = granularity.split(",")
  307. for granpart in granparts:
  308. granlist.append(granpart.strip().split(" "))
  309. for inc in granlist:
  310. if inc[1].find("seconds") >= 0 or inc[1].find("second") >= 0:
  311. has_seconds = True
  312. elif inc[1].find("minutes") >= 0 or inc[1].find("minute") >= 0:
  313. has_minutes = True
  314. elif inc[1].find("hours") >= 0 or inc[1].find("hour") >= 0:
  315. has_hours = True
  316. elif inc[1].find("days") >= 0 or inc[1].find("day") >= 0:
  317. has_days = True
  318. elif inc[1].find("weeks") >= 0 or inc[1].find("week") >= 0:
  319. has_weeks = True
  320. elif inc[1].find("months") >= 0 or inc[1].find("month") >= 0:
  321. has_months = True
  322. elif inc[1].find("years") >= 0 or inc[1].find("year") >= 0:
  323. has_years = True
  324. else:
  325. core.error(_("Wrong granularity format: %s") % (granularity))
  326. return None
  327. if has_seconds:
  328. pass
  329. elif has_minutes: # Start at 0 seconds
  330. seconds = 0
  331. elif has_hours: # Start at 0 minutes and seconds
  332. seconds = 0
  333. minutes = 0
  334. elif has_days: # Start at 0 hours, minutes and seconds
  335. seconds = 0
  336. minutes = 0
  337. hours = 0
  338. elif has_weeks: # Start at the first day of the week (Monday) at 00:00:00
  339. seconds = 0
  340. minutes = 0
  341. hours = 0
  342. if days > weekday:
  343. days = days - weekday # this needs to be fixed
  344. else:
  345. days = days + weekday # this needs to be fixed
  346. elif has_months: # Start at the first day of the month at 00:00:00
  347. seconds = 0
  348. minutes = 0
  349. hours = 0
  350. days = 1
  351. elif has_years: # Start at the first day of the first month at 00:00:00
  352. seconds = 0
  353. minutes = 0
  354. hours = 0
  355. days = 1
  356. months = 1
  357. dt = copy.copy(mydate)
  358. return dt.replace(year=years, month=months, day=days,
  359. hour=hours, minute=minutes, second=seconds)
  360. ###############################################################################
  361. def compute_datetime_delta(start, end):
  362. """!Return a dictionary with the accumulated delta in year, month, day,
  363. hour, minute and second
  364. Usage:
  365. @code
  366. >>> start = datetime(2001, 1, 1, 00,00,00)
  367. >>> end = datetime(2001, 1, 1, 00,00,00)
  368. >>> compute_datetime_delta(start, end)
  369. {'hour': 0, 'month': 0, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 0}
  370. >>> start = datetime(2001, 1, 1, 00,00,14)
  371. >>> end = datetime(2001, 1, 1, 00,00,44)
  372. >>> compute_datetime_delta(start, end)
  373. {'hour': 0, 'month': 0, 'second': 30, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 0}
  374. >>> start = datetime(2001, 1, 1, 00,00,44)
  375. >>> end = datetime(2001, 1, 1, 00,01,14)
  376. >>> compute_datetime_delta(start, end)
  377. {'hour': 0, 'month': 0, 'second': 30, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 1}
  378. >>> start = datetime(2001, 1, 1, 00,00,30)
  379. >>> end = datetime(2001, 1, 1, 00,05,30)
  380. >>> compute_datetime_delta(start, end)
  381. {'hour': 0, 'month': 0, 'second': 300, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 5}
  382. >>> start = datetime(2001, 1, 1, 00,00,00)
  383. >>> end = datetime(2001, 1, 1, 00,01,00)
  384. >>> compute_datetime_delta(start, end)
  385. {'hour': 0, 'month': 0, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 1}
  386. >>> start = datetime(2011,10,31, 00,45,00)
  387. >>> end = datetime(2011,10,31, 01,45,00)
  388. >>> compute_datetime_delta(start, end)
  389. {'hour': 1, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 60}
  390. >>> start = datetime(2011,10,31, 00,45,00)
  391. >>> end = datetime(2011,10,31, 01,15,00)
  392. >>> compute_datetime_delta(start, end)
  393. {'hour': 1, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 30}
  394. >>> start = datetime(2011,10,31, 00,45,00)
  395. >>> end = datetime(2011,10,31, 12,15,00)
  396. >>> compute_datetime_delta(start, end)
  397. {'hour': 12, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 690}
  398. >>> start = datetime(2011,10,31, 00,00,00)
  399. >>> end = datetime(2011,10,31, 01,00,00)
  400. >>> compute_datetime_delta(start, end)
  401. {'hour': 1, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 0}
  402. >>> start = datetime(2011,10,31, 00,00,00)
  403. >>> end = datetime(2011,11,01, 01,00,00)
  404. >>> compute_datetime_delta(start, end)
  405. {'hour': 25, 'second': 0, 'max_days': 1, 'year': 0, 'day': 1, 'minute': 0}
  406. >>> start = datetime(2011,10,31, 12,00,00)
  407. >>> end = datetime(2011,11,01, 06,00,00)
  408. >>> compute_datetime_delta(start, end)
  409. {'hour': 18, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 0}
  410. >>> start = datetime(2011,11,01, 00,00,00)
  411. >>> end = datetime(2011,12,01, 01,00,00)
  412. >>> compute_datetime_delta(start, end)
  413. {'hour': 721, 'month': 1, 'second': 0, 'max_days': 30, 'year': 0, 'day': 0, 'minute': 0}
  414. >>> start = datetime(2011,11,01, 00,00,00)
  415. >>> end = datetime(2011,11,05, 00,00,00)
  416. >>> compute_datetime_delta(start, end)
  417. {'hour': 0, 'second': 0, 'max_days': 4, 'year': 0, 'day': 4, 'minute': 0}
  418. >>> start = datetime(2011,10,06, 00,00,00)
  419. >>> end = datetime(2011,11,05, 00,00,00)
  420. >>> compute_datetime_delta(start, end)
  421. {'hour': 0, 'second': 0, 'max_days': 30, 'year': 0, 'day': 30, 'minute': 0}
  422. >>> start = datetime(2011,12,02, 00,00,00)
  423. >>> end = datetime(2012,01,01, 00,00,00)
  424. >>> compute_datetime_delta(start, end)
  425. {'hour': 0, 'second': 0, 'max_days': 30, 'year': 1, 'day': 30, 'minute': 0}
  426. >>> start = datetime(2011,01,01, 00,00,00)
  427. >>> end = datetime(2011,02,01, 00,00,00)
  428. >>> compute_datetime_delta(start, end)
  429. {'hour': 0, 'month': 1, 'second': 0, 'max_days': 31, 'year': 0, 'day': 0, 'minute': 0}
  430. >>> start = datetime(2011,12,01, 00,00,00)
  431. >>> end = datetime(2012,01,01, 00,00,00)
  432. >>> compute_datetime_delta(start, end)
  433. {'hour': 0, 'month': 1, 'second': 0, 'max_days': 31, 'year': 1, 'day': 0, 'minute': 0}
  434. >>> start = datetime(2011,12,01, 00,00,00)
  435. >>> end = datetime(2012,06,01, 00,00,00)
  436. >>> compute_datetime_delta(start, end)
  437. {'hour': 0, 'month': 6, 'second': 0, 'max_days': 183, 'year': 1, 'day': 0, 'minute': 0}
  438. >>> start = datetime(2011,06,01, 00,00,00)
  439. >>> end = datetime(2021,06,01, 00,00,00)
  440. >>> compute_datetime_delta(start, end)
  441. {'hour': 0, 'month': 120, 'second': 0, 'max_days': 3653, 'year': 10, 'day': 0, 'minute': 0}
  442. >>> start = datetime(2011,06,01, 00,00,00)
  443. >>> end = datetime(2012,06,01, 12,00,00)
  444. >>> compute_datetime_delta(start, end)
  445. {'hour': 8796, 'month': 12, 'second': 0, 'max_days': 366, 'year': 1, 'day': 0, 'minute': 0}
  446. >>> start = datetime(2011,06,01, 00,00,00)
  447. >>> end = datetime(2012,06,01, 12,30,00)
  448. >>> compute_datetime_delta(start, end)
  449. {'hour': 8796, 'month': 12, 'second': 0, 'max_days': 366, 'year': 1, 'day': 0, 'minute': 527790}
  450. >>> start = datetime(2011,06,01, 00,00,00)
  451. >>> end = datetime(2012,06,01, 12,00,05)
  452. >>> compute_datetime_delta(start, end)
  453. {'hour': 8796, 'month': 12, 'second': 31665605, 'max_days': 366, 'year': 1, 'day': 0, 'minute': 0}
  454. >>> start = datetime(2011,06,01, 00,00,00)
  455. >>> end = datetime(2012,06,01, 00,30,00)
  456. >>> compute_datetime_delta(start, end)
  457. {'hour': 0, 'month': 12, 'second': 0, 'max_days': 366, 'year': 1, 'day': 0, 'minute': 527070}
  458. >>> start = datetime(2011,06,01, 00,00,00)
  459. >>> end = datetime(2012,06,01, 00,00,05)
  460. >>> compute_datetime_delta(start, end)
  461. {'hour': 0, 'month': 12, 'second': 31622405, 'max_days': 366, 'year': 1, 'day': 0, 'minute': 0}
  462. @endcode
  463. @return A dictionary with year, month, day, hour, minute and second as keys()
  464. """
  465. comp = {}
  466. day_diff = (end - start).days
  467. comp["max_days"] = day_diff
  468. # Date
  469. # Count full years
  470. d = end.year - start.year
  471. comp["year"] = d
  472. # Count full months
  473. if start.month == 1 and end.month == 1:
  474. comp["month"] = 0
  475. elif start.day == 1 and end.day == 1:
  476. d = end.month - start.month
  477. if d < 0:
  478. d = d + 12 * comp["year"]
  479. elif d == 0:
  480. d = 12 * comp["year"]
  481. comp["month"] = d
  482. # Count full days
  483. if start.day == 1 and end.day == 1:
  484. comp["day"] = 0
  485. else:
  486. comp["day"] = day_diff
  487. # Time
  488. # Hours
  489. if start.hour == 0 and end.hour == 0:
  490. comp["hour"] = 0
  491. else:
  492. d = end.hour - start.hour
  493. if d < 0:
  494. d = d + 24 + 24 * day_diff
  495. else:
  496. d = d + 24 * day_diff
  497. comp["hour"] = d
  498. # Minutes
  499. if start.minute == 0 and end.minute == 0:
  500. comp["minute"] = 0
  501. else:
  502. d = end.minute - start.minute
  503. if d != 0:
  504. if comp["hour"]:
  505. d = d + 60 * comp["hour"]
  506. else:
  507. d = d + 24 * 60 * day_diff
  508. elif d == 0:
  509. if comp["hour"]:
  510. d = 60 * comp["hour"]
  511. else:
  512. d = 24 * 60 * day_diff
  513. comp["minute"] = d
  514. # Seconds
  515. if start.second == 0 and end.second == 0:
  516. comp["second"] = 0
  517. else:
  518. d = end.second - start.second
  519. if d != 0:
  520. if comp["minute"]:
  521. d = d + 60 * comp["minute"]
  522. elif comp["hour"]:
  523. d = d + 3600 * comp["hour"]
  524. else:
  525. d = d + 24 * 60 * 60 * day_diff
  526. elif d == 0:
  527. if comp["minute"]:
  528. d = 60 * comp["minute"]
  529. elif comp["hour"]:
  530. d = 3600 * comp["hour"]
  531. else:
  532. d = 24 * 60 * 60 * day_diff
  533. comp["second"] = d
  534. return comp
  535. ###############################################################################
  536. def string_to_datetime(time_string):
  537. """!Convert a string into a datetime object
  538. Supported ISO string formats are:
  539. - YYYY-mm-dd
  540. - YYYY-mm-dd HH:MM:SS
  541. Time zones are not supported
  542. @param time_string The time string to convert
  543. @return datetime object or None in case of an error
  544. """
  545. # BC is not supported
  546. if time_string.find("bc") > 0:
  547. core.error("Dates Before Christ are not supported "
  548. "in the temporal database")
  549. return None
  550. # BC is not supported
  551. if time_string.find("+") > 0:
  552. core.error("Time zones are not supported "
  553. "in the temporal database")
  554. return None
  555. if time_string.find(":") > 0:
  556. time_format = "%Y-%m-%d %H:%M:%S"
  557. else:
  558. time_format = "%Y-%m-%d"
  559. try:
  560. return datetime.strptime(time_string, time_format)
  561. except:
  562. core.error("Unable to parse time string: %s"%time_string)
  563. return None
  564. ###############################################################################
  565. def datetime_to_grass_datetime_string(dt):
  566. """!Convert a python datetime object into a GRASS datetime string"""
  567. # GRASS datetime month names
  568. month_names = ["", "jan", "feb", "mar", "apr", "may", "jun",
  569. "jul", "aug", "sep", "oct", "nov", "dec"]
  570. # Check for time zone info in the datetime object
  571. if dt.tzinfo is not None:
  572. string = "%.2i %s %.2i %.2i:%.2i:%.2i %+.4i" % (dt.day,
  573. month_names[dt.month], dt.year,
  574. dt.hour, dt.minute, dt.second, dt.tzinfo._offset.seconds / 60)
  575. else:
  576. string = "%.2i %s %.4i %.2i:%.2i:%.2i" % (dt.day, month_names[
  577. dt.month], dt.year, dt.hour, dt.minute, dt.second)
  578. return string
  579. ###############################################################################
  580. if __name__ == "__main__":
  581. import doctest
  582. doctest.testmod()