# Get Video Duration with FFMPEG and Python

For this to work, you’ll need FFMPEG and Python on your machine or server already. Configuration of this is beyond the scope of this post, but installation through yum or apt-get should be sufficient (or equivalent on a Windows or Mac). To pull the duration of a video from any machine with FFMPEG and Python installed, run the following script. Take care to replace PATH_TO_YOUR_VIDEO_FILE with the path to your video and check to ensure your ffmpeg binary is located at /usr/bin/ffmpeg (you can do this by executing ‘which ffmpeg’ in your shell). The result is a dictionary with hours, minutes and seconds as the keys.

import subprocess
import re

process = subprocess.Popen(['/usr/bin/ffmpeg',  '-i', PATH_TO_YOUR_VIDEO_FILE], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout, stderr = process.communicate()
matches = re.search(r"Duration:\s{1}(?P\d+?):(?P\d+?):(?P\d+\.\d+?),", stdout, re.DOTALL).groupdict()

print matches['hours']
print matches['minutes']
print matches['seconds']


Update:

Cal Leeming was kind enough to put this in a function that’ll return the number of seconds as a Decimal. Thanks again, Cal!

import subprocess
import re
from decimal import Decimal

def get_video_length(path):
process = subprocess.Popen(['/usr/bin/ffmpeg', '-i', path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout, stderr = process.communicate()
matches = re.search(r"Duration:\s{1}(?P\d+?):(?P\d+?):(?P\d+\.\d+?),", stdout, re.DOTALL).groupdict()

hours = Decimal(matches['hours'])
minutes = Decimal(matches['minutes'])
seconds = Decimal(matches['seconds'])

total = 0
total += 60 * 60 * hours
total += 60 * minutes
total += seconds