Menu

Python – Get Total Length of Video Files

March 11, 2016 - Programming, Python

Previously, I wrote about Counting Lines of Code in a given directory. Recently, I had a similar curiousity- “how long are all the video files in this folder?” This seemed to be a good fit for a Python script.

The main question, then, is how do we determine the length of a video file in Python? Once we have that problem solved, we can effectively use the same code as the CodeCount and “sum” all the lengths together in much the same way that the Code Count script sums all the line counts.

The most straightforward approach I discovered was using ffmpeg to retrieve video information, redirecting the output to a temp file, and then finding the listed Duration in that temp file. We then take that determined duration and parse it, and create a Python TimeDelta. We can use that TimeDelta, and sum all the TimeDelta’s of the files in question to determine the total run time of all the videos in the specified folders.

A bit of checking code to allow for the use of *.* to total all ffmpeg compatible video files rounds this out- the syntax is the same as the Code Counter- VidLength.py <FileMask> <directory< and it will display all the files it analyzes and then a total duration.

Have something to say about this post? Comment!