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.

42 lines
1.0 KiB

  1. class Unit(object):
  2. def __init__(self, name, nsecs):
  3. self.name = name
  4. self.plural = name + "s"
  5. self.nsecs = nsecs
  6. MINUTE = Unit("minute", 60)
  7. HOUR = Unit("hour", MINUTE.nsecs * 60)
  8. DAY = Unit("day", HOUR.nsecs * 24)
  9. WEEK = Unit("week", DAY.nsecs * 7)
  10. def format_duration(td):
  11. remaining_seconds = int(td.total_seconds())
  12. result = []
  13. for unit in (WEEK, DAY, HOUR, MINUTE):
  14. if unit == WEEK and remaining_seconds % unit.nsecs != 0:
  15. # Say "8 days" instead of "1 week 1 day"
  16. continue
  17. v, remaining_seconds = divmod(remaining_seconds, unit.nsecs)
  18. if v == 1:
  19. result.append("1 %s" % unit.name)
  20. elif v > 1:
  21. result.append("%d %s" % (v, unit.plural))
  22. return " ".join(result)
  23. def format_mins_secs(td):
  24. total_seconds = int(td.total_seconds())
  25. result = []
  26. mins, secs = divmod(total_seconds, 60)
  27. if mins:
  28. result.append("%d min" % mins)
  29. result.append("%s sec" % secs)
  30. return " ".join(result)