How to Get the Duration of a Video in Python?

Rate this post

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 =["ffprobe", "-v", "error", "-show_entries",
                             "format=duration", "-of",
                             "default=noprint_wrappers=1:nokey=1", filename],
    return float(result.stdout)

The code is obtained from here and here.

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 moviepy module.

from moviepy.editor import VideoFileClip
clip = VideoFileClip("my_video.mp4")

This code is obtained from here. However, it is reported that method 1 with ffprobe is 10x faster than the method with moviepy.

Method 3: Using the pymediainfo Module

An alternative to the previous method is provided by the pymediainfo library:

from pymediainfo import MediaInfo
clip_info = MediaInfo.parse('')
duration_ms = clip_info.tracks[0].duration

This code is obtained from here and here.

Method 4: Using the opencv Module

One of the fastest method to retrieve the duration of a video is provided by the opencv module:

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!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. 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?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

๐Ÿš€ If your answer is YES!, consider becoming 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.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar โ€œHow to Build Your High-Income Skill Pythonโ€ and learn how I grew my coding business online and how you can, tooโ€”from the comfort of your own home.

Join the free webinar now!