| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- """
- General utility functions.
- """
- import re
- from datetime import timedelta
-
- def parse_timedelta(s: str) -> timedelta:
- """
- Parses a timespan. Format examples:
- "30m"
- "10s"
- "90d"
- "1h30m"
- "73d18h22m52s"
- """
- p = re.compile('^(?:[0-9]+[dhms])+$')
- if p.match(s) is None:
- raise ValueError("Illegal timespan value '{s}'.")
- p = re.compile('([0-9]+)([dhms])')
- days = 0
- hours = 0
- minutes = 0
- seconds = 0
- for m in p.finditer(s):
- scalar = int(m.group(1))
- unit = m.group(2)
- if unit == 'd':
- days = scalar
- elif unit == 'h':
- hours = scalar
- elif unit == 'm':
- minutes = scalar
- elif unit == 's':
- seconds = scalar
- return timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
-
- def describe_timedelta(td: timedelta, max_components: int = 2) -> str:
- """
- Formats a human-readable description of a time span. E.g. "3 days 2 hours".
- """
- d = td.days
- h = td.seconds // 3600
- m = (td.seconds // 60) % 60
- s = td.seconds % 60
- components = []
- if d != 0:
- components.append('1 day' if d == 1 else f'{d} days')
- if h != 0:
- components.append('1 hour' if h == 1 else f'{h} hours')
- if m != 0:
- components.append('1 minute' if m == 1 else f'{m} minutes')
- if s != 0 or len(components) == 0:
- components.append('1 second' if s == 1 else f'{s} seconds')
- if len(components) > max_components:
- components = components[0:max_components]
- return ' '.join(components)
|