You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
1.8 KiB

  1. from datetime import datetime as dt
  2. from django.utils import timezone
  3. class Unit(object):
  4. def __init__(self, name, nsecs):
  5. self.name = name
  6. self.plural = name + "s"
  7. self.nsecs = nsecs
  8. SECOND = Unit("second", 1)
  9. MINUTE = Unit("minute", 60)
  10. HOUR = Unit("hour", MINUTE.nsecs * 60)
  11. DAY = Unit("day", HOUR.nsecs * 24)
  12. WEEK = Unit("week", DAY.nsecs * 7)
  13. def format_duration(td):
  14. remaining_seconds = int(td.total_seconds())
  15. result = []
  16. for unit in (WEEK, DAY, HOUR, MINUTE):
  17. if unit == WEEK and remaining_seconds % unit.nsecs != 0:
  18. # Say "8 days" instead of "1 week 1 day"
  19. continue
  20. v, remaining_seconds = divmod(remaining_seconds, unit.nsecs)
  21. if v == 1:
  22. result.append("1 %s" % unit.name)
  23. elif v > 1:
  24. result.append("%d %s" % (v, unit.plural))
  25. return " ".join(result)
  26. def format_hms(td):
  27. total_seconds = int(td.total_seconds())
  28. result = []
  29. mins, secs = divmod(total_seconds, 60)
  30. h, mins = divmod(mins, 60)
  31. if h:
  32. result.append("%d h" % h)
  33. if h or mins:
  34. result.append("%d min" % mins)
  35. result.append("%s sec" % secs)
  36. return " ".join(result)
  37. def format_approx_duration(td):
  38. v = td.total_seconds()
  39. for unit in (DAY, HOUR, MINUTE, SECOND):
  40. if v >= unit.nsecs:
  41. vv = v // unit.nsecs
  42. if vv == 1:
  43. return "1 %s" % unit.name
  44. else:
  45. return "%d %s" % (vv, unit.plural)
  46. return ""
  47. def month_boundaries(months=2):
  48. result = []
  49. now = timezone.now()
  50. y, m = now.year, now.month
  51. for x in range(0, months):
  52. result.insert(0, dt(y, m, 1, tzinfo=timezone.utc))
  53. m -= 1
  54. if m == 0:
  55. m = 12
  56. y = y - 1
  57. return result