Sunday, December 7, 2025
HomeLanguagesGet video duration using Python – OpenCV

Get video duration using Python – OpenCV

OpenCV is one of the most popular cross-platform libraries and it is widely used in Deep Learning, image processing, video capturing, and many more. In this article, we will learn how to get the duration of a given video using python and computer vision. 

Prerequisites: 

Installation

Opencv can be downloaded by running the given command on the terminal:

pip install Opencv

Approach

To get the duration of a video, the following steps has to be followed:

  • Import required modules.
  • Create a VideoCapture object  by providing video URL to VideoCapture() method.

Syntax:

VideoCapture("url")
  • Count the total numbers of frames and frames per second of a given video by providing  cv2.CAP_PROP_FRAME_COUNT and cv2.CAP_PROP_FPS to get() method.
  • Calculate the duration of the video in seconds by dividing frames and fps.
  • Also, calculate video time using timedelta() method.

Syntax:

timedelta(time)

Implementation:

Python3




# import module
import cv2
import datetime
  
# create video capture object
data = cv2.VideoCapture('C:/Users/Asus/Documents/videoDuration.mp4')
  
# count the number of frames
frames = data.get(cv2.CAP_PROP_FRAME_COUNT)
fps = data.get(cv2.CAP_PROP_FPS)
  
# calculate duration of the video
seconds = round(frames / fps)
video_time = datetime.timedelta(seconds=seconds)
print(f"duration in seconds: {seconds}")
print(f"video time: {video_time}")


Output :

duration in seconds: 28
video time: 0:00:28
RELATED ARTICLES

Most Popular

Dominic
32429 POSTS0 COMMENTS
Milvus
103 POSTS0 COMMENTS
Nango Kala
6803 POSTS0 COMMENTS
Nicole Veronica
11945 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12015 POSTS0 COMMENTS
Shaida Kate Naidoo
6934 POSTS0 COMMENTS
Ted Musemwa
7189 POSTS0 COMMENTS
Thapelo Manthata
6883 POSTS0 COMMENTS
Umr Jansen
6867 POSTS0 COMMENTS