datetime_math.py 27 KB

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