How to get length/duration of video file in Python using ffprobe
In our previous post How to get video metadata as JSON using ffmpeg/ffprobe we showed how to generate json-formatted output using ffprobe which comes bundled with ffmpeg.
Assuming ffprobe is installed, you can easily use this to obtain the duration of a video clip (say, in input.mp4) using Python:
ffprobe_duration.py
import subprocess
import json
input_filename = "input.mp4"
out = subprocess.check_output(["ffprobe", "-v", "quiet", "-show_format", "-print_format", "json", input_filename])
ffprobe_data = json.loads(out)
duration_seconds = float(ffprobe_data["format"]["duration"])
# Example: duration_seconds = 11.6685When writing such code, be aware of the risk of shell code injection if you don’t using subprocess correctly!
Check out similar posts by category:
Audio/Video, Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow