Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Recursive mp4 duration counter
When you have lots of mp4 files in a folder recursively (lots of subfolders and mp4s residing inside),
You can use this script to measure total duration of all mp4 files.
Useful in estimating the total course duration.
Run this script in folder where you want to start counting from.
import subprocess
import os
# Return duration of mp4 file in seconds (float)
def getLength(filename):
result = subprocess.Popen(["ffprobe", filename],
stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
duration = [x for x in result.stdout.readlines() if "Duration" in x]
hour, minute, second = duration[0].strip().split(",")[0].split(": ")[-1].split(":")
return float(hour) * 3600.0 + float(minute) * 60.0 + float(second)
# Find all mp4 files, searching recursively.
files = []
for root, directories, filenames in os.walk('.'):
for filename in filenames:
if filename.endswith(".mp4"):
# Now measure and count total duration of all mp4 files.
total = 0.0
for filepath in files:
seconds = getLength(filepath)
total += seconds
# Now print total duration
print "%s hours (%s minutes)" % (total / 3600, total / 60.0 )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment