Problem Formulation: Given a video file. How to get its duration in seconds using Python code?
The video can have any of the following video formats:
Method 1: Using Subprocess + ffprobe
Within your Python shell, you can run any external command with the module subprocess. The external tool ffprobe helps you determine many video statistics such as the length of the video.
“ffprobe gathers information from multimedia streams and prints it in human- and machine-readable fashion.”
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)
You can download ffprobe for Windows, macOS, and Linux here.
Method 2: Using the moviepy Module
This code is even more concise—and it retrieves the duration of a given video very quickly using the
from moviepy.editor import VideoFileClip clip = VideoFileClip("my_video.mp4") print(clip.duration)
This code is obtained from here. However, it is reported that method 1 with
ffprobe is 10x faster than the method with
Method 3: Using the pymediainfo Module
An alternative to the previous method is provided by the
from pymediainfo import MediaInfo clip_info = MediaInfo.parse('my_video.mov') duration_ms = clip_info.tracks.duration
Method 4: Using the opencv Module
One of the fastest method to retrieve the duration of a video is provided by the
import cv2 video = cv2.VideoCapture('my_video.webm') duration = video.get(cv2.CAP_PROP_POS_MSEC)
Where to Go From Here?
Enough theory, let’s get some practice!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.