You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何转换%H:%M:%S.%f格式类时间字符串为毫秒并解决出现负值问题

问题解答

核心问题原因

你使用datetime.strptime解析仅包含时分秒微秒的字符串时,Python会自动补全缺失的年月日为1900年1月1日。而datetime.timestamp()返回的是当前时间距离1970年1月1日0点(UTC时区)的秒数,1900年早于1970年,因此计算结果为负数。

你遗漏的关键要点

%H:%M:%S.%f格式仅表示一天内的时间偏移,属于相对时间范畴,而timestamp()是用于计算绝对公历时间和Unix纪元差值的方法,二者适用场景完全不匹配。你拿到的时间字符串本身就是视频从开头计算的时长偏移,直接转成总秒数即可满足ffmpeg_extract_subclip的参数要求,不需要调用timestamp()方法。

正确实现代码

方案1:基于datetime计算时间差

from datetime import datetime
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip

def time_str_to_sec(time_str: str) -> float:
    dt = datetime.strptime(time_str, '%H:%M:%S.%f')
    # 计算与基准0点的时间差,返回总秒数
    return (dt - datetime(1900, 1, 1)).total_seconds()

time_1, time_2 = return_times("file.json")
start_sec = time_str_to_sec(time_1)
end_sec = time_str_to_sec(time_2)

ffmpeg_extract_subclip("long_video.mp4", start_sec, end_sec, targetname="video_trimmed.mp4")

方案2:手动拆分字符串计算(更轻量化,无日期依赖坑)

def time_str_to_sec(time_str: str) -> float:
    h_part, m_part, s_part = time_str.split(':')
    sec, ms = s_part.split('.')
    return int(h_part) * 3600 + int(m_part) * 60 + int(sec) + int(ms) / 1000

内容的提问来源于stack exchange,提问作者bit_scientist

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 20:54:08