convert.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. from datetime import datetime, timedelta
  2. def str2bool(string: str):
  3. string = string.lower()
  4. str2val = {"true": True, "false": False}
  5. if string in str2val:
  6. return str2val[string]
  7. raise ValueError(
  8. f"Expected one of {set(str2val.keys())}, got {string}")
  9. def str2timeinterval(string: str):
  10. if string is None:
  11. return None
  12. if '-' not in string:
  13. raise ValueError(
  14. f"Expected time interval HH:mm:ss-HH:mm:ss or HH:mm-HH:mm or ss-ss, got {string}")
  15. intervals = string.split('-')
  16. if len(intervals) != 2:
  17. raise ValueError(
  18. f"Expected time interval HH:mm:ss-HH:mm:ss or HH:mm-HH:mm or ss-ss, got {string}")
  19. start = try_parse_timestamp(intervals[0])
  20. end = try_parse_timestamp(intervals[1])
  21. if start >= end:
  22. raise ValueError(
  23. f"Expected time interval end to be higher than start, got {start} >= {end}")
  24. return [start, end]
  25. def time_to_timestamp(string: str):
  26. split_time = string.split(':')
  27. if len(split_time) == 0 or len(split_time) > 3 or not all(x.isdigit() for x in split_time):
  28. raise ValueError(
  29. f"Expected HH:mm:ss or HH:mm or ss, got {string}")
  30. if len(split_time) == 1:
  31. return int(split_time[0])
  32. if len(split_time) == 2:
  33. return int(split_time[0]) * 60 * 60 + int(split_time[1]) * 60
  34. return int(split_time[0]) * 60 * 60 + int(split_time[1]) * 60 + int(split_time[2])
  35. def try_parse_timestamp(string: str):
  36. timestamp = parse_timestamp(string, '%H:%M:%S')
  37. if timestamp is not None:
  38. return timestamp
  39. timestamp = parse_timestamp(string, '%H:%M')
  40. if timestamp is not None:
  41. return timestamp
  42. return parse_timestamp(string, '%S')
  43. def parse_timestamp(string: str, pattern: str):
  44. try:
  45. date = datetime.strptime(string, pattern)
  46. delta = timedelta(
  47. hours=date.hour, minutes=date.minute, seconds=date.second)
  48. return int(delta.total_seconds())
  49. except: # pylint: disable=bare-except
  50. return None
  51. def format_timestamp(seconds: float, always_include_hours: bool = False):
  52. assert seconds >= 0, "non-negative timestamp expected"
  53. milliseconds = round(seconds * 1000.0)
  54. hours = milliseconds // 3_600_000
  55. milliseconds -= hours * 3_600_000
  56. minutes = milliseconds // 60_000
  57. milliseconds -= minutes * 60_000
  58. seconds = milliseconds // 1_000
  59. milliseconds -= seconds * 1_000
  60. hours_marker = f"{hours:02d}:" if always_include_hours or hours > 0 else ""
  61. return f"{hours_marker}{minutes:02d}:{seconds:02d},{milliseconds:03d}"