datetime_math.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. """
  2. Functions for mathematical datetime operations
  3. (C) 2011-2013 by the GRASS Development Team
  4. This program is free software under the GNU General Public
  5. License (>=v2). Read the file COPYING that comes with GRASS
  6. for details.
  7. :authors: Soeren Gebbert
  8. """
  9. from datetime import datetime, date, time, timedelta
  10. from core import *
  11. import copy
  12. try:
  13. import dateutil.parser as parser
  14. has_dateutil = True
  15. except:
  16. has_dateutil = False
  17. DAY_IN_SECONDS = 86400
  18. SECOND_AS_DAY = 1.1574074074074073e-05
  19. ###############################################################################
  20. def relative_time_to_time_delta(value):
  21. """Convert the double value representing days
  22. into a timedelta object.
  23. """
  24. days = int(value)
  25. seconds = value % 1
  26. seconds = round(seconds * DAY_IN_SECONDS)
  27. return timedelta(days, seconds)
  28. ###############################################################################
  29. def time_delta_to_relative_time(delta):
  30. """Convert the time delta into a
  31. double value, representing days.
  32. """
  33. return float(delta.days) + float(delta.seconds * SECOND_AS_DAY)
  34. ###############################################################################
  35. def relative_time_to_time_delta_seconds(value):
  36. """Convert the double value representing seconds
  37. into a timedelta object.
  38. """
  39. days = (value / 86400)
  40. seconds = int(value % 86400)
  41. return timedelta(days, seconds)
  42. ###############################################################################
  43. def time_delta_to_relative_time_seconds(delta):
  44. """Convert the time delta into a
  45. double value, representing seconds.
  46. """
  47. return float(delta.days * DAY_IN_SECONDS) + float(delta.seconds)
  48. ###############################################################################
  49. def decrement_datetime_by_string(mydate, increment, mult=1):
  50. """Return a new datetime object decremented with the provided
  51. relative dates specified as string.
  52. Additional a multiplier can be specified to multiply the increment
  53. before adding to the provided datetime object.
  54. Usage:
  55. .. code-block:: python
  56. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  57. >>> string = "31 days"
  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 = "1 month"
  62. >>> decrement_datetime_by_string(dt, string)
  63. datetime.datetime(2000, 12, 1, 0, 0)
  64. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  65. >>> string = "2 month"
  66. >>> decrement_datetime_by_string(dt, string)
  67. datetime.datetime(2000, 11, 1, 0, 0)
  68. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  69. >>> string = "24 months"
  70. >>> decrement_datetime_by_string(dt, string)
  71. datetime.datetime(1999, 1, 1, 0, 0)
  72. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  73. >>> string = "48 months"
  74. >>> decrement_datetime_by_string(dt, string)
  75. datetime.datetime(1997, 1, 1, 0, 0)
  76. >>> dt = datetime(2001, 6, 1, 0, 0, 0)
  77. >>> string = "5 months"
  78. >>> decrement_datetime_by_string(dt, string)
  79. datetime.datetime(2001, 1, 1, 0, 0)
  80. >>> dt = datetime(2001, 6, 1, 0, 0, 0)
  81. >>> string = "7 months"
  82. >>> decrement_datetime_by_string(dt, string)
  83. datetime.datetime(2000, 11, 1, 0, 0)
  84. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  85. >>> string = "1 year"
  86. >>> decrement_datetime_by_string(dt, string)
  87. datetime.datetime(2000, 1, 1, 0, 0)
  88. :param mydate: A datetime object to incremented
  89. :param increment: A string providing increment information:
  90. The string may include comma separated values of type seconds,
  91. minutes, hours, days, weeks, months and years
  92. Example: Increment the datetime 2001-01-01 00:00:00
  93. with "60 seconds, 4 minutes, 12 hours, 10 days, 1 weeks, 5 months, 1 years"
  94. will result in the datetime 2003-02-18 12:05:00
  95. :param mult: A multiplier, default is 1
  96. :return: The new datetime object or none in case of an error
  97. """
  98. return modify_datetime_by_string(mydate, increment, mult, sign=int(-1))
  99. ###############################################################################
  100. def increment_datetime_by_string(mydate, increment, mult=1):
  101. """Return a new datetime object incremented with the provided
  102. relative dates specified as string.
  103. Additional a multiplier can be specified to multiply the increment
  104. before adding to the provided datetime object.
  105. Usage:
  106. .. code-block:: python
  107. >>> dt = datetime(2001, 9, 1, 0, 0, 0)
  108. >>> string = "60 seconds, 4 minutes, 12 hours, 10 days, 1 weeks, 5 months, 1 years"
  109. >>> increment_datetime_by_string(dt, string)
  110. datetime.datetime(2003, 2, 18, 12, 5)
  111. >>> dt = datetime(2001, 11, 1, 0, 0, 0)
  112. >>> string = "1 months"
  113. >>> increment_datetime_by_string(dt, string)
  114. datetime.datetime(2001, 12, 1, 0, 0)
  115. >>> dt = datetime(2001, 11, 1, 0, 0, 0)
  116. >>> string = "13 months"
  117. >>> increment_datetime_by_string(dt, string)
  118. datetime.datetime(2002, 12, 1, 0, 0)
  119. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  120. >>> string = "72 months"
  121. >>> increment_datetime_by_string(dt, string)
  122. datetime.datetime(2007, 1, 1, 0, 0)
  123. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  124. >>> string = "72 months"
  125. >>> increment_datetime_by_string(dt, string)
  126. datetime.datetime(2007, 1, 1, 0, 0)
  127. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  128. >>> string = "5 minutes"
  129. >>> increment_datetime_by_string(dt, string)
  130. datetime.datetime(2001, 1, 1, 0, 5)
  131. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  132. >>> string = "49 hours"
  133. >>> increment_datetime_by_string(dt, string)
  134. datetime.datetime(2001, 1, 3, 1, 0)
  135. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  136. >>> string = "3600 seconds"
  137. >>> increment_datetime_by_string(dt, string)
  138. datetime.datetime(2001, 1, 1, 1, 0)
  139. >>> dt = datetime(2001, 1, 1, 0, 0, 0)
  140. >>> string = "30 days"
  141. >>> increment_datetime_by_string(dt, string)
  142. datetime.datetime(2001, 1, 31, 0, 0)
  143. :param mydate: A datetime object to incremented
  144. :param increment: A string providing increment information:
  145. The string may include comma separated values of type seconds,
  146. minutes, hours, days, weeks, months and years
  147. Example: Increment the datetime 2001-01-01 00:00:00
  148. with "60 seconds, 4 minutes, 12 hours, 10 days, 1 weeks, 5 months, 1 years"
  149. will result in the datetime 2003-02-18 12:05:00
  150. :param mult: A multiplier, default is 1
  151. :return: The new datetime object or none in case of an error
  152. """
  153. return modify_datetime_by_string(mydate, increment, mult, sign=int(1))
  154. ###############################################################################
  155. def modify_datetime_by_string(mydate, increment, mult=1, sign=1):
  156. """Return a new datetime object incremented with the provided
  157. relative dates specified as string.
  158. Additional a multiplier can be specified to multiply the increment
  159. before adding to the provided datetime object.
  160. :param mydate: A datetime object to incremented
  161. :param increment: A string providing increment information:
  162. The string may include comma separated values of type seconds,
  163. minutes, hours, days, weeks, months and years
  164. Example: Increment the datetime 2001-01-01 00:00:00
  165. with "60 seconds, 4 minutes, 12 hours, 10 days, 1 weeks, 5 months, 1 years"
  166. will result in the datetime 2003-02-18 12:05:00
  167. :param mult: A multiplier, default is 1
  168. :param sign: Choose 1 for positive sign (incrementing) or -1 for negative
  169. sign (decrementing).
  170. :return: The new datetime object or none in case of an error
  171. """
  172. sign = int(sign)
  173. if sign != 1 and sign != -1:
  174. return None
  175. if increment:
  176. seconds = 0
  177. minutes = 0
  178. hours = 0
  179. days = 0
  180. weeks = 0
  181. months = 0
  182. years = 0
  183. inclist = []
  184. # Split the increment string
  185. incparts = increment.split(",")
  186. for incpart in incparts:
  187. inclist.append(incpart.strip().split(" "))
  188. for inc in inclist:
  189. msgr = get_tgis_message_interface()
  190. if len(inc) < 2:
  191. msgr.error(_("Wrong increment format: %s") % (increment))
  192. return None
  193. if inc[1].find("seconds") >= 0 or inc[1].find("second") >= 0:
  194. seconds = sign * mult * int(inc[0])
  195. elif inc[1].find("minutes") >= 0 or inc[1].find("minute") >= 0:
  196. minutes = sign * mult * int(inc[0])
  197. elif inc[1].find("hours") >= 0 or inc[1].find("hour") >= 0:
  198. hours = sign * mult * int(inc[0])
  199. elif inc[1].find("days") >= 0 or inc[1].find("day") >= 0:
  200. days = sign * mult * int(inc[0])
  201. elif inc[1].find("weeks") >= 0 or inc[1].find("week") >= 0:
  202. weeks = sign * mult * int(inc[0])
  203. elif inc[1].find("months") >= 0 or inc[1].find("month") >= 0:
  204. months = sign * mult * int(inc[0])
  205. elif inc[1].find("years") >= 0 or inc[1].find("year") >= 0:
  206. years = sign * mult * int(inc[0])
  207. else:
  208. msgr.error(_("Wrong increment format: %s") % (increment))
  209. return None
  210. return modify_datetime(mydate, years, months, weeks, days, hours, minutes, seconds)
  211. return mydate
  212. ###############################################################################
  213. def modify_datetime(mydate, years=0, months=0, weeks=0, days=0, hours=0,
  214. minutes=0, seconds=0):
  215. """Return a new datetime object incremented with the provided
  216. relative dates and times"""
  217. tdelta_seconds = timedelta(seconds=seconds)
  218. tdelta_minutes = timedelta(minutes=minutes)
  219. tdelta_hours = timedelta(hours=hours)
  220. tdelta_days = timedelta(days=days)
  221. tdelta_weeks = timedelta(weeks=weeks)
  222. tdelta_months = timedelta(0)
  223. tdelta_years = timedelta(0)
  224. if 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. all_months = int(months) + int(month)
  229. years_to_add = int(all_months / 12.001)
  230. residual_months = all_months - (years_to_add * 12)
  231. # Make a deep copy of the datetime object
  232. dt1 = copy.copy(mydate)
  233. # Make sure the month starts with a 1
  234. if residual_months == 0:
  235. residual_months = 1
  236. try:
  237. dt1 = dt1.replace(year=year + years_to_add, month=residual_months)
  238. except:
  239. raise
  240. tdelta_months = dt1 - mydate
  241. elif months < 0:
  242. # Compute the actual number of days in the month to add as timedelta
  243. year = mydate.year
  244. month = mydate.month
  245. years_to_remove = 0
  246. all_months = int(months) + int(month)
  247. if all_months <= 0:
  248. years_to_remove = abs(int(all_months / 12.001))
  249. residual_months = all_months + (years_to_remove * 12)
  250. years_to_remove += 1
  251. else:
  252. residual_months = all_months
  253. # Make a deep copy of the datetime object
  254. dt1 = copy.copy(mydate)
  255. # Correct the months
  256. if residual_months <= 0:
  257. residual_months += 12
  258. try:
  259. dt1 = dt1.replace(year=year - years_to_remove, month=residual_months)
  260. except:
  261. raise
  262. tdelta_months = dt1 - mydate
  263. if years != 0:
  264. # Make a deep copy of the datetime object
  265. dt1 = copy.copy(mydate)
  266. # Compute the number of days
  267. dt1 = dt1.replace(year=mydate.year + int(years))
  268. tdelta_years = dt1 - mydate
  269. return mydate + tdelta_seconds + tdelta_minutes + tdelta_hours + \
  270. tdelta_days + tdelta_weeks + tdelta_months + tdelta_years
  271. ###############################################################################
  272. def adjust_datetime_to_granularity(mydate, granularity):
  273. """Modify the datetime object to fit the given granularity
  274. - Years will start at the first of Januar
  275. - Months will start at the first day of the month
  276. - Days will start at the first Hour of the day
  277. - Hours will start at the first minute of an hour
  278. - Minutes will start at the first second of a minute
  279. Usage:
  280. .. code-block:: python
  281. >>> dt = datetime(2001, 8, 8, 12,30,30)
  282. >>> adjust_datetime_to_granularity(dt, "5 seconds")
  283. datetime.datetime(2001, 8, 8, 12, 30, 30)
  284. >>> adjust_datetime_to_granularity(dt, "20 minutes")
  285. datetime.datetime(2001, 8, 8, 12, 30)
  286. >>> adjust_datetime_to_granularity(dt, "20 minutes")
  287. datetime.datetime(2001, 8, 8, 12, 30)
  288. >>> adjust_datetime_to_granularity(dt, "3 hours")
  289. datetime.datetime(2001, 8, 8, 12, 0)
  290. >>> adjust_datetime_to_granularity(dt, "5 days")
  291. datetime.datetime(2001, 8, 8, 0, 0)
  292. >>> adjust_datetime_to_granularity(dt, "2 weeks")
  293. datetime.datetime(2001, 8, 6, 0, 0)
  294. >>> adjust_datetime_to_granularity(dt, "6 months")
  295. datetime.datetime(2001, 8, 1, 0, 0)
  296. >>> adjust_datetime_to_granularity(dt, "2 years")
  297. datetime.datetime(2001, 1, 1, 0, 0)
  298. >>> adjust_datetime_to_granularity(dt, "2 years, 3 months, 5 days, 3 hours, 3 minutes, 2 seconds")
  299. datetime.datetime(2001, 8, 8, 12, 30, 30)
  300. >>> adjust_datetime_to_granularity(dt, "3 months, 5 days, 3 minutes")
  301. datetime.datetime(2001, 8, 8, 12, 30)
  302. >>> adjust_datetime_to_granularity(dt, "3 weeks, 5 days")
  303. datetime.datetime(2001, 8, 8, 0, 0)
  304. """
  305. if granularity:
  306. has_seconds = False
  307. has_minutes = False
  308. has_hours = False
  309. has_days = False
  310. has_weeks = False
  311. has_months = False
  312. has_years = False
  313. seconds = mydate.second
  314. minutes = mydate.minute
  315. hours = mydate.hour
  316. days = mydate.day
  317. weekday = mydate.weekday()
  318. months = mydate.month
  319. years = mydate.year
  320. granlist = []
  321. # Split the increment string
  322. granparts = granularity.split(",")
  323. for granpart in granparts:
  324. granlist.append(granpart.strip().split(" "))
  325. for inc in granlist:
  326. if inc[1].find("seconds") >= 0 or inc[1].find("second") >= 0:
  327. has_seconds = True
  328. elif inc[1].find("minutes") >= 0 or inc[1].find("minute") >= 0:
  329. has_minutes = True
  330. elif inc[1].find("hours") >= 0 or inc[1].find("hour") >= 0:
  331. has_hours = True
  332. elif inc[1].find("days") >= 0 or inc[1].find("day") >= 0:
  333. has_days = True
  334. elif inc[1].find("weeks") >= 0 or inc[1].find("week") >= 0:
  335. has_weeks = True
  336. elif inc[1].find("months") >= 0 or inc[1].find("month") >= 0:
  337. has_months = True
  338. elif inc[1].find("years") >= 0 or inc[1].find("year") >= 0:
  339. has_years = True
  340. else:
  341. msgr = get_tgis_message_interface()
  342. msgr.error(_("Wrong granularity format: %s") % (granularity))
  343. return None
  344. if has_seconds:
  345. pass
  346. elif has_minutes: # Start at 0 seconds
  347. seconds = 0
  348. elif has_hours: # Start at 0 minutes and seconds
  349. seconds = 0
  350. minutes = 0
  351. elif has_days: # Start at 0 hours, minutes and seconds
  352. seconds = 0
  353. minutes = 0
  354. hours = 0
  355. elif has_weeks: # Start at the first day of the week (Monday) at 00:00:00
  356. seconds = 0
  357. minutes = 0
  358. hours = 0
  359. if days > weekday:
  360. days = days - weekday # this needs to be fixed
  361. else:
  362. days = days + weekday # this needs to be fixed
  363. elif has_months: # Start at the first day of the month at 00:00:00
  364. seconds = 0
  365. minutes = 0
  366. hours = 0
  367. days = 1
  368. elif has_years: # Start at the first day of the first month at 00:00:00
  369. seconds = 0
  370. minutes = 0
  371. hours = 0
  372. days = 1
  373. months = 1
  374. dt = copy.copy(mydate)
  375. return dt.replace(year=years, month=months, day=days,
  376. hour=hours, minute=minutes, second=seconds)
  377. ###############################################################################
  378. def compute_datetime_delta(start, end):
  379. """Return a dictionary with the accumulated delta in year, month, day,
  380. hour, minute and second
  381. Usage:
  382. .. code-block:: python
  383. >>> start = datetime(2001, 1, 1, 00,00,00)
  384. >>> end = datetime(2001, 1, 1, 00,00,00)
  385. >>> compute_datetime_delta(start, end)
  386. {'hour': 0, 'month': 0, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 0}
  387. >>> start = datetime(2001, 1, 1, 00,00,14)
  388. >>> end = datetime(2001, 1, 1, 00,00,44)
  389. >>> compute_datetime_delta(start, end)
  390. {'hour': 0, 'month': 0, 'second': 30, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 0}
  391. >>> start = datetime(2001, 1, 1, 00,00,44)
  392. >>> end = datetime(2001, 1, 1, 00,01,14)
  393. >>> compute_datetime_delta(start, end)
  394. {'hour': 0, 'month': 0, 'second': 30, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 1}
  395. >>> start = datetime(2001, 1, 1, 00,00,30)
  396. >>> end = datetime(2001, 1, 1, 00,05,30)
  397. >>> compute_datetime_delta(start, end)
  398. {'hour': 0, 'month': 0, 'second': 300, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 5}
  399. >>> start = datetime(2001, 1, 1, 00,00,00)
  400. >>> end = datetime(2001, 1, 1, 00,01,00)
  401. >>> compute_datetime_delta(start, end)
  402. {'hour': 0, 'month': 0, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 1}
  403. >>> start = datetime(2011,10,31, 00,45,00)
  404. >>> end = datetime(2011,10,31, 01,45,00)
  405. >>> compute_datetime_delta(start, end)
  406. {'hour': 1, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 60}
  407. >>> start = datetime(2011,10,31, 00,45,00)
  408. >>> end = datetime(2011,10,31, 01,15,00)
  409. >>> compute_datetime_delta(start, end)
  410. {'hour': 1, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 30}
  411. >>> start = datetime(2011,10,31, 00,45,00)
  412. >>> end = datetime(2011,10,31, 12,15,00)
  413. >>> compute_datetime_delta(start, end)
  414. {'hour': 12, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 690}
  415. >>> start = datetime(2011,10,31, 00,00,00)
  416. >>> end = datetime(2011,10,31, 01,00,00)
  417. >>> compute_datetime_delta(start, end)
  418. {'hour': 1, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 0}
  419. >>> start = datetime(2011,10,31, 00,00,00)
  420. >>> end = datetime(2011,11,01, 01,00,00)
  421. >>> compute_datetime_delta(start, end)
  422. {'hour': 25, 'second': 0, 'max_days': 1, 'year': 0, 'day': 1, 'minute': 0}
  423. >>> start = datetime(2011,10,31, 12,00,00)
  424. >>> end = datetime(2011,11,01, 06,00,00)
  425. >>> compute_datetime_delta(start, end)
  426. {'hour': 18, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 0}
  427. >>> start = datetime(2011,11,01, 00,00,00)
  428. >>> end = datetime(2011,12,01, 01,00,00)
  429. >>> compute_datetime_delta(start, end)
  430. {'hour': 721, 'month': 1, 'second': 0, 'max_days': 30, 'year': 0, 'day': 0, 'minute': 0}
  431. >>> start = datetime(2011,11,01, 00,00,00)
  432. >>> end = datetime(2011,11,05, 00,00,00)
  433. >>> compute_datetime_delta(start, end)
  434. {'hour': 0, 'second': 0, 'max_days': 4, 'year': 0, 'day': 4, 'minute': 0}
  435. >>> start = datetime(2011,10,06, 00,00,00)
  436. >>> end = datetime(2011,11,05, 00,00,00)
  437. >>> compute_datetime_delta(start, end)
  438. {'hour': 0, 'second': 0, 'max_days': 30, 'year': 0, 'day': 30, 'minute': 0}
  439. >>> start = datetime(2011,12,02, 00,00,00)
  440. >>> end = datetime(2012,01,01, 00,00,00)
  441. >>> compute_datetime_delta(start, end)
  442. {'hour': 0, 'second': 0, 'max_days': 30, 'year': 1, 'day': 30, 'minute': 0}
  443. >>> start = datetime(2011,01,01, 00,00,00)
  444. >>> end = datetime(2011,02,01, 00,00,00)
  445. >>> compute_datetime_delta(start, end)
  446. {'hour': 0, 'month': 1, 'second': 0, 'max_days': 31, 'year': 0, 'day': 0, 'minute': 0}
  447. >>> start = datetime(2011,12,01, 00,00,00)
  448. >>> end = datetime(2012,01,01, 00,00,00)
  449. >>> compute_datetime_delta(start, end)
  450. {'hour': 0, 'month': 1, 'second': 0, 'max_days': 31, 'year': 1, 'day': 0, 'minute': 0}
  451. >>> start = datetime(2011,12,01, 00,00,00)
  452. >>> end = datetime(2012,06,01, 00,00,00)
  453. >>> compute_datetime_delta(start, end)
  454. {'hour': 0, 'month': 6, 'second': 0, 'max_days': 183, 'year': 1, 'day': 0, 'minute': 0}
  455. >>> start = datetime(2011,06,01, 00,00,00)
  456. >>> end = datetime(2021,06,01, 00,00,00)
  457. >>> compute_datetime_delta(start, end)
  458. {'hour': 0, 'month': 120, 'second': 0, 'max_days': 3653, 'year': 10, 'day': 0, 'minute': 0}
  459. >>> start = datetime(2011,06,01, 00,00,00)
  460. >>> end = datetime(2012,06,01, 12,00,00)
  461. >>> compute_datetime_delta(start, end)
  462. {'hour': 8796, 'month': 12, 'second': 0, 'max_days': 366, 'year': 1, 'day': 0, 'minute': 0}
  463. >>> start = datetime(2011,06,01, 00,00,00)
  464. >>> end = datetime(2012,06,01, 12,30,00)
  465. >>> compute_datetime_delta(start, end)
  466. {'hour': 8796, 'month': 12, 'second': 0, 'max_days': 366, 'year': 1, 'day': 0, 'minute': 527790}
  467. >>> start = datetime(2011,06,01, 00,00,00)
  468. >>> end = datetime(2012,06,01, 12,00,05)
  469. >>> compute_datetime_delta(start, end)
  470. {'hour': 8796, 'month': 12, 'second': 31665605, 'max_days': 366, 'year': 1, 'day': 0, 'minute': 0}
  471. >>> start = datetime(2011,06,01, 00,00,00)
  472. >>> end = datetime(2012,06,01, 00,30,00)
  473. >>> compute_datetime_delta(start, end)
  474. {'hour': 0, 'month': 12, 'second': 0, 'max_days': 366, 'year': 1, 'day': 0, 'minute': 527070}
  475. >>> start = datetime(2011,06,01, 00,00,00)
  476. >>> end = datetime(2012,06,01, 00,00,05)
  477. >>> compute_datetime_delta(start, end)
  478. {'hour': 0, 'month': 12, 'second': 31622405, 'max_days': 366, 'year': 1, 'day': 0, 'minute': 0}
  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. global has_dateutil
  562. if has_dateutil:
  563. # First check if there is only a single number, which specifies relative time.
  564. # dateutil will interprete a single number as a valid time string, so we have
  565. # to catch this case beforehand
  566. try:
  567. value = int(time_string)
  568. return _("Time string seems to specify relative time")
  569. except ValueError:
  570. pass
  571. try:
  572. time_object = parser.parse(time_string)
  573. except Exception as inst:
  574. time_object = str(inst)
  575. return time_object
  576. # BC is not supported
  577. if time_string.find("bc") > 0:
  578. return _("Dates Before Christ (BC) are not supported")
  579. # BC is not supported
  580. if time_string.find("+") > 0:
  581. return _("Time zones are not supported")
  582. if time_string.find(":") > 0:
  583. time_format = "%Y-%m-%d %H:%M:%S"
  584. else:
  585. time_format = "%Y-%m-%d"
  586. try:
  587. return datetime.strptime(time_string, time_format)
  588. except:
  589. return _("Unable to parse time string: %s"%time_string)
  590. ###############################################################################
  591. def string_to_datetime(time_string):
  592. """Convert a string into a datetime object
  593. In case datutil is not installed the supported ISO string formats are:
  594. - YYYY-mm-dd
  595. - YYYY-mm-dd HH:MM:SS
  596. - Time zones are not supported
  597. If dateutil is installed, all string formats of the dateutil module
  598. are supported, as well as time zones
  599. :param time_string: The time string to convert
  600. :return: datetime: object or None in case the string
  601. could not be converted
  602. """
  603. if not isinstance(time_string, str):
  604. return None
  605. time_object = check_datetime_string(time_string)
  606. if not isinstance(time_object, datetime):
  607. msgr = get_tgis_message_interface()
  608. msgr.error(str(time_object))
  609. return None
  610. return time_object
  611. ###############################################################################
  612. def datetime_to_grass_datetime_string(dt):
  613. """Convert a python datetime object into a GRASS datetime string
  614. .. code-block:: python
  615. >>> import grass.temporal as tgis
  616. >>> import dateutil.parser as parser
  617. >>> dt = parser.parse("2011-01-01 10:00:00 +01:30")
  618. >>> tgis.datetime_to_grass_datetime_string(dt)
  619. '01 jan 2011 10:00:00 +0090'
  620. >>> dt = parser.parse("2011-01-01 10:00:00 +02:30")
  621. >>> tgis.datetime_to_grass_datetime_string(dt)
  622. '01 jan 2011 10:00:00 +0150'
  623. >>> dt = parser.parse("2011-01-01 10:00:00 +12:00")
  624. >>> tgis.datetime_to_grass_datetime_string(dt)
  625. '01 jan 2011 10:00:00 +0720'
  626. >>> dt = parser.parse("2011-01-01 10:00:00 -01:30")
  627. >>> tgis.datetime_to_grass_datetime_string(dt)
  628. '01 jan 2011 10:00:00 -0090'
  629. """
  630. # GRASS datetime month names
  631. month_names = ["", "jan", "feb", "mar", "apr", "may", "jun",
  632. "jul", "aug", "sep", "oct", "nov", "dec"]
  633. # Check for time zone info in the datetime object
  634. if dt.tzinfo is not None:
  635. tz = dt.tzinfo.utcoffset(0)
  636. if tz.seconds > 86400 / 2:
  637. tz = (tz.seconds - 86400) / 60
  638. else:
  639. tz = tz.seconds/60
  640. string = "%.2i %s %.2i %.2i:%.2i:%.2i %+.4i" % (dt.day,
  641. month_names[dt.month], dt.year,
  642. dt.hour, dt.minute, dt.second, tz)
  643. else:
  644. string = "%.2i %s %.4i %.2i:%.2i:%.2i" % (dt.day, month_names[
  645. dt.month], dt.year, dt.hour, dt.minute, dt.second)
  646. return string
  647. ###############################################################################
  648. suffix_units = {"years" : "%Y",
  649. "year" : "%Y",
  650. "months" : "%Y_%m",
  651. "month" : "%Y_%m",
  652. "weeks" : "%Y_%m_%d",
  653. "week" : "%Y_%m_%d",
  654. "days" : "%Y_%m_%d",
  655. "day" : "%Y_%m_%d",
  656. "hours" : "%Y_%m_%d_%H",
  657. "hour" : "%Y_%m_%d_%H",
  658. "minutes" : "%Y_%m_%d_%H_%M",
  659. "minute" : "%Y_%m_%d_%H_%M",}
  660. def create_suffix_from_datetime(start_time, granularity):
  661. """Create a datetime string based on a datetime object and a provided
  662. granularity that can be used as suffix for map names.
  663. dateteime=2001-01-01 00:00:00, granularity="1 month" returns "2001_01"
  664. :param start_time: The datetime object
  665. :param granularity: The granularity for example "1 month" or "100 seconds"
  666. :return: A string
  667. """
  668. global suffix_units
  669. return start_time.strftime(suffix_units[granularity.split(' ')[1]])
  670. if __name__ == "__main__":
  671. import doctest
  672. doctest.testmod()