Get video duration in Python

In this content, we will learn how to duration of video in python

Introduction

To get the duration of video, you can use methods for handling files like moviepy and openCV which provides a simple interface retrieving metadata like duration. By measuring your video duration, you can track metrices such as watch time or retention rate and ensure that you are meeting the requirements.

Methods to get the duration of video

you can get the duration of video by using following libraries:

#method 1:’moviepy’

  1. Install moviepy: First you need to install moviepy.
  2. retrieve video duration: use the following python code to get the duration of a video.
from moviepy.editor import VideoFileClip
video = videoFileClip("my_video.mp4")
print(video.duration/60)

make sure to replace my_video.mp4 with your actual video file.

#method 2:’openCV’

In openCV to calculate the duration using the frame count and the frame rate of the video.this is how you do that:

  1. Get the total number of frames using cv2.CAP_PROP_FRAME_COUNT.
  2. get the frame per second(FPS) using cv2.CAP_PROP_FPS.
  3. the video duration in seconds is equal to the total number of frames divided by the FPS.
    import cv2
    def get_video_duration(video_path):
    cap = cv2.VideoCapture(video_path)
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    fps=int(cap.get(cv2.CAP_PROP_FPS))
    duration_seconds = total_frames/fps
    cap.release()
    return duration_seconds
    video_path = "path_to_your_video.mp4"
    duration = get_video_duration(video_path)
    print(f"Video duration : {duration:.2f} seconds")
    seconds = int(duration % 60)
    print(f"Video duration: {seconds} seconds")
    
    

make sure to replace path_to_your_video.mp4 with actual path to your actual video file.

This openCV library gives you a rough estimate of the video duration. To get the more accurate method consider using library like moviepy. This methods helps us to get the duration of video and you can choose the one that fits your requirements and coding style.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top