convert.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. from datetime import datetime, timedelta
  2. def str2bool(string):
  3. string = string.lower()
  4. str2val = {"true": True, "false": False}
  5. if string in str2val:
  6. return str2val[string]
  7. else:
  8. raise ValueError(
  9. f"Expected one of {set(str2val.keys())}, got {string}")
  10. def str2timeinterval(string):
  11. if string is None:
  12. return None
  13. if '-' not in string:
  14. raise ValueError(
  15. f"Expected time interval HH:mm:ss-HH:mm:ss or HH:mm-HH:mm or ss-ss, got {string}")
  16. intervals = string.split('-')
  17. if len(intervals) != 2:
  18. raise ValueError(
  19. f"Expected time interval HH:mm:ss-HH:mm:ss or HH:mm-HH:mm or ss-ss, got {string}")
  20. start = try_parse_timestamp(intervals[0])
  21. end = try_parse_timestamp(intervals[1])
  22. if start >= end:
  23. raise ValueError(
  24. f"Expected time interval end to be higher than start, got {start} >= {end}")
  25. return [start, end]
  26. def time_to_timestamp(string):
  27. split_time = string.split(':')
  28. if len(split_time) == 0 or len(split_time) > 3 or not all([ x.isdigit() for x in split_time ]):
  29. raise ValueError(
  30. f"Expected HH:mm:ss or HH:mm or ss, got {string}")
  31. if len(split_time) == 1:
  32. return int(split_time[0])
  33. if len(split_time) == 2:
  34. return int(split_time[0]) * 60 * 60 + int(split_time[1]) * 60
  35. return int(split_time[0]) * 60 * 60 + int(split_time[1]) * 60 + int(split_time[2])
  36. def try_parse_timestamp(string):
  37. timestamp = parse_timestamp(string, '%H:%M:%S')
  38. if timestamp is not None:
  39. return timestamp
  40. timestamp = parse_timestamp(string, '%H:%M')
  41. if timestamp is not None:
  42. return timestamp
  43. return parse_timestamp(string, '%S')
  44. def parse_timestamp(string, pattern):
  45. try:
  46. date = datetime.strptime(string, pattern)
  47. delta = timedelta(hours=date.hour, minutes=date.minute, seconds=date.second)
  48. return int(delta.total_seconds())
  49. 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}"