How to find the duration of a video file in Python
In this article, we will discuss how to find the duration of a video file with the help of Python. You may need this for your project or experimental scripting purposes.
The solution is extremely simple and can be done just within a few lines.
Installation of the package: moviepy
Handling the video file in its raw binary format will make things complicated instead, we will use an external library based on Python called moviepy.
The first step is to install moviepy and for that, we will use the package manager, pip. To install moviepy, run the following command in your command prompt.
pip3 install moviepy
This is all you need to proceed with the actual code. The package moviepy is based on ffmpeg, which will be installed as one of the dependencies so you need not worry about it. The library supports most of the common video formats that are currently in use.
To test if the package installed correctly, run the following code on the Python shell.
If you have no errors, you are good to proceed.
Python program to find the duration of a video file
Once we are done with the installation of the packages, we are already done with most of the work. The actual code required for this is extremely short and simple which will be discussed now.
We need to import the moviepy library or specifically the editor class of the moviepy module.
Now, create an object of the VideoFileClip class by referencing the location of the video file as a parameter.
video = moviepy.editor.VideoFileClip("D:\path\to\video.mp4")
We can now access the duration member of the class which will contain the duration of the video file in seconds which can be formatted into our desired format.
video_duration = int(video.duration)
The complete code which only consists of a few lines is mentioned below
import moviepy.editor # Converts into more readable format def convert(seconds): hours = seconds // 3600 seconds %= 3600 mins = seconds // 60 seconds %= 60 return hours, mins, seconds # Create an object by passing the location as a string video = moviepy.editor.VideoFileClip("D:\path\to\video.mp4") # Contains the duration of the video in terms of seconds video_duration = int(video.duration) hours, mins, secs = convert(video_duration) print("Hours:", hours) print("Minutes:", mins) print("Seconds:", secs)
I hope this article was useful in helping you to find the duration of a video file. In case you need to discover more functionalities of the moviepy library, you can refer to its documentation here.
You may also read: