“更通用、更稳健”的实现:兼容 HH:MM:SS(.ff)MM:SS(.ff)SS(.ff),允许不补零(如 1:2:3.5)、小数用逗号或点(01:23,45),并对 : 形式做了合理校验(SS<60,三段式时 MM<60)。

import re
from typing import Any

def enhanced_parse_time_to_seconds(time_str: Any) -> float:
    """
    将时间字符串解析为秒(float)

    支持格式:
      - SS / SS.ff / SS,ff
      - MM:SS / MM:SS.ff / M:SS / M:SS.ff
      - HH:MM:SS / HH:MM:SS.ff(不补零也可,如 1:2:3.5)
      - 兼容前导/尾随空格,兼容小数逗号

    规则校验:
      - 含冒号时:seconds 必须 < 60
      - 三段式(HH:MM:SS[.ff]) 时:minutes 必须 < 60
      - 两段式(MM:SS[.ff]) 时:minutes 允许任意非负整数(通常MV时长分钟数可>=60也合规)
    """
    if time_str is None:
        return 0.0

    s = str(time_str).strip()
    if not s or s == '0':
        return 0.0

    # 统一小数点
    s = s.replace(',', '.')
    s = re.sub(r'^\+', '', s)  # 允许前导+

    try:
        if ':' not in s:
            # 纯秒(可带小数)
            return float(s)

        parts = s.split(':')
        if len(parts) > 3:
            raise ValueError("too many ':' segments")

        # 解析秒(最后一段可带小数)
        sec_part_str = parts[-1]
        sec_part = float(sec_part_str)

        # 冒号形式必须保证秒 < 60
        if not (0.0 <= sec_part < 60.0):
            raise ValueError("seconds must be in [0,60) when ':' is present")

        total = sec_part

        if len(parts) == 2:
            # MM:SS(.ff) —— 分钟不强制 < 60
            mm_str = parts[-2]
            if not re.fullmatch(r'\d+', mm_str):
                raise ValueError("minutes must be integer")
            mm = int(mm_str)
            if mm < 0:
                raise ValueError("minutes must be non-negative")
            total += mm * 60
            return total

        # len(parts) == 3 -> HH:MM:SS(.ff)
        hh_str, mm_str = parts[0], parts[1]
        if not (re.fullmatch(r'\d+', hh_str) and re.fullmatch(r'\d+', mm_str)):
            raise ValueError("hours/minutes must be integer")

        hh, mm = int(hh_str), int(mm_str)
        if hh < 0 or mm < 0:
            raise ValueError("hours/minutes must be non-negative")

        # 三段式要求 minutes < 60
        if not (0 <= mm < 60):
            raise ValueError("minutes must be in [0,60) for HH:MM:SS")

        total += mm * 60 + hh * 3600
        return total

    except (ValueError, TypeError) as e:
        print(f"⚠️ enhanced_parse_time_to_seconds 时间解析失败: '{time_str}' -> {e}")
        return 0.0

要点说明

  • 两段式(MM:SS)不强制 MM<60,更宽松,适合长素材(但秒仍需 <60)。
  • 三段式(HH:MM:SS)对 MM<60SS<60 严格校验,避免非法时间。
  • 支持 00:00:50.0600:01:23.791:2:3.502:45.1250.0601:23,45 等常见变体。

更多推荐