python获取视频时长方法

    技术2025-10-23  11

    1.使用subprocess和re

    import re import subprocess video = r"work/train/video/a8b96f016a28d8f3836f7cbb7734ecde.mp4" import subprocess def get_length(filename): result = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", filename], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return float(result.stdout) t=get_length(video) print(t)

    运行结果: 2.使用VideoFileClip

    from moviepy.editor import VideoFileClip clip=VideoFileClip(video) print(clip.duration)

    运行结果: 3.使用cv2

    import cv2 def get_video_duration(filename): cap = cv2.VideoCapture(filename) if cap.isOpened(): rate = cap.get(5) frame_num =cap.get(7) duration = frame_num/rate return duration return -1 t=get_video_duration(video) print(t)

    运行结果: 从结果可以看出,cv2的运行时长是最短的,推荐使用cv2

    Processed: 0.012, SQL: 9