utils.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import datetime
  2. from django.utils import timezone
  3. ANGLES = {
  4. 'N': (-23, 22),
  5. 'NO': (292, 337),
  6. 'O': (247, 292),
  7. 'SO': (202, 247),
  8. 'S': (157, 202),
  9. 'SE': (112, 157),
  10. 'E': (67, 112),
  11. 'NE': (22, 67)
  12. }
  13. ORIENTATIONS = ANGLES.keys()
  14. def merge_intervals(l, wrap=360):
  15. """Merge a list of intervals, assuming the space is cyclic. The
  16. intervals should already by sorted by start value."""
  17. if l == []:
  18. return []
  19. result = list()
  20. # Transform the 2-tuple into a 2-list to be able to modify it
  21. result.append(list(l[0]))
  22. for (start, stop) in l:
  23. current = result[-1]
  24. if start > current[1]:
  25. result.append([start, stop])
  26. else:
  27. result[-1][1] = max(result[-1][1], stop)
  28. if len(result) == 1:
  29. return result
  30. # Handle the cyclicity by merging the ends if necessary
  31. last = result[-1]
  32. first = result[0]
  33. if first[0] <= last[1] - wrap:
  34. result[-1][1] = max(result[-1][1], first[1] + wrap)
  35. result.pop(0)
  36. return result
  37. def add_one_year(date):
  38. new_day, new_month, new_year = date.day, date.month, date.year + 1
  39. try:
  40. new_date = timezone.make_aware(
  41. datetime.datetime(new_year, new_month, new_day))
  42. except ValueError: # Hello 29/3
  43. new_day -= 1
  44. new_date = timezone.make_aware(
  45. datetime.datetime(new_year, new_month, new_day))
  46. return new_date