parse_time.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import datetime
  2. import re
  3. # 2023-05-16_11-45-00
  4. def parse_time(text: str):
  5. try:
  6. # extract date and time
  7. date, time = text.split("_")
  8. # extract year, month, day
  9. year, month, day = date.split("-")
  10. # extract hour, minute, second
  11. hour, minute, second = time.split("-")
  12. # create a native date
  13. return datetime.datetime(
  14. int(year), int(month), int(day), int(hour), int(minute), int(second)
  15. )
  16. except Exception:
  17. print("Error parsing time")
  18. print(text)
  19. return None
  20. # audio__bark__None__2023-05-16_11-45-00_long.wav
  21. # audio__tortoise__random__2023-05-31_14-19-13__n0.wav
  22. # Matches the time string in the filename and returns it
  23. def extract_time(filename: str):
  24. # only match the time string
  25. regex = r"([0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{2}-[0-9]{2}-[0-9]{2})"
  26. matches = re.finditer(regex, filename, re.MULTILINE)
  27. for matchNum, match in enumerate(matches, start=1):
  28. return match.group(1)
  29. def extract_and_parse_time(filename: str):
  30. return parse_time(extract_time(filename))