Experimental Discord bot written in Python
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

utils.py 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """
  2. General utility functions.
  3. """
  4. import re
  5. from datetime import timedelta
  6. def parse_timedelta(s: str) -> timedelta:
  7. """
  8. Parses a timespan. Format examples:
  9. "30m"
  10. "10s"
  11. "90d"
  12. "1h30m"
  13. "73d18h22m52s"
  14. """
  15. p = re.compile('^(?:[0-9]+[dhms])+$')
  16. if p.match(s) is None:
  17. raise ValueError("Illegal timespan value '{s}'.")
  18. p = re.compile('([0-9]+)([dhms])')
  19. days = 0
  20. hours = 0
  21. minutes = 0
  22. seconds = 0
  23. for m in p.finditer(s):
  24. scalar = int(m.group(1))
  25. unit = m.group(2)
  26. if unit == 'd':
  27. days = scalar
  28. elif unit == 'h':
  29. hours = scalar
  30. elif unit == 'm':
  31. minutes = scalar
  32. elif unit == 's':
  33. seconds = scalar
  34. return timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
  35. def describe_timedelta(td: timedelta, max_components: int = 2) -> str:
  36. """
  37. Formats a human-readable description of a time span. E.g. "3 days 2 hours".
  38. """
  39. d = td.days
  40. h = td.seconds // 3600
  41. m = (td.seconds // 60) % 60
  42. s = td.seconds % 60
  43. components = []
  44. if d != 0:
  45. components.append('1 day' if d == 1 else f'{d} days')
  46. if h != 0:
  47. components.append('1 hour' if h == 1 else f'{h} hours')
  48. if m != 0:
  49. components.append('1 minute' if m == 1 else f'{m} minutes')
  50. if s != 0 or len(components) == 0:
  51. components.append('1 second' if s == 1 else f'{s} seconds')
  52. if len(components) > max_components:
  53. components = components[0:max_components]
  54. return ' '.join(components)