如何使用Python从YouTube时间戳提取秒级开始与结束时间
问题描述
我有一个YouTube视频的时间戳列表,示例如下:
timestamps = ['0:02-0:35', '0:50-1:18', '2:53-3:08', '3:12-3:14', '3:16-3:22', '3:25-3:28', '1:09-1:35', '1:38-1:48', '2:04-2:14', '2:30-2:40', '2:45-2:50', '3:35-4:07', '4:16-4:22', '4:48-4:54', '5:00-5:12', '5:34-5:54', '8:58-9:19', '']
需要提取每个时间戳对应的starttime和endtime(以秒为单位),作为ffmpeg_extract_subclip方法的参数来切割视频。示例:
# 时间戳为0:02-0:35时: timestamp = '0:02-0:35' starttime = 2 endtime = 35 # 时间戳为3:02-3:35时: timestamp = '3:02-3:35' starttime = 182 # 计算逻辑:3*60 + 2 endtime = 215 # 计算逻辑:3*60 + 35
请问是否可以通过正则表达式实现?或者有其他可行方案?
解决方案
两种方案都可行,具体实现如下:
一、正则表达式方案
通过正则匹配捕获时间戳里的分钟和秒数值,再转换为总秒数,适合需要严格格式校验的场景。
实现代码
import re def convert_timestamp_to_seconds(timestamp): # 跳过空字符串 if not timestamp.strip(): return None, None # 正则匹配格式:分钟:秒-分钟:秒,捕获四个数值组 pattern = r'(\d+):(\d+)-(\d+):(\d+)' match_result = re.match(pattern, timestamp) if not match_result: return None, None # 提取各组值并转换为整数 start_min, start_sec, end_min, end_sec = map(int, match_result.groups()) starttime = start_min * 60 + start_sec endtime = end_min * 60 + end_sec return starttime, endtime # 批量处理时间戳列表 timestamps = ['0:02-0:35', '0:50-1:18', '2:53-3:08', '3:12-3:14', '3:16-3:22', '3:25-3:28', '1:09-1:35', '1:38-1:48', '2:04-2:14', '2:30-2:40', '2:45-2:50', '3:35-4:07', '4:16-4:22', '4:48-4:54', '5:00-5:12', '5:34-5:54', '8:58-9:19', ''] for ts in timestamps: start, end = convert_timestamp_to_seconds(ts) if start is not None and end is not None: print(f"时间戳 {ts}: starttime={start}, endtime={end}") # 此处可直接调用ffmpeg切割方法 # ffmpeg_extract_subclip("输入视频路径", start, end, targetname=f"输出片段_{start}_{end}.mp4")
二、字符串分割方案
通过字符串分割逐步拆分时间戳,逻辑直观易懂,适合格式规范的时间戳列表。
实现代码
def convert_timestamp_to_seconds(timestamp): # 跳过空字符串 if not timestamp.strip(): return None, None # 按'-'分割起止时间 start_str, end_str = timestamp.split('-') # 定义单个时间字符串转秒数的辅助函数 def time_to_sec(time_str): min_part, sec_part = time_str.split(':') return int(min_part) * 60 + int(sec_part) # 转换起止时间为秒数 starttime = time_to_sec(start_str) endtime = time_to_sec(end_str) return starttime, endtime # 批量处理时间戳列表 timestamps = ['0:02-0:35', '0:50-1:18', '2:53-3:08', '3:12-3:14', '3:16-3:22', '3:25-3:28', '1:09-1:35', '1:38-1:48', '2:04-2:14', '2:30-2:40', '2:45-2:50', '3:35-4:07', '4:16-4:22', '4:48-4:54', '5:00-5:12', '5:34-5:54', '8:58-9:19', ''] for ts in timestamps: start, end = convert_timestamp_to_seconds(ts) if start is not None and end is not None: print(f"时间戳 {ts}: starttime={start}, endtime={end}") # 此处可直接调用ffmpeg切割方法 # ffmpeg_extract_subclip("输入视频路径", start, end, targetname=f"输出片段_{start}_{end}.mp4")
内容的提问来源于stack exchange,提问作者rangarajan
相关产品推荐
相关产品推荐

