Skip to content

Instantly share code, notes, and snippets.

@md-redwan-hossain
Last active April 18, 2023 06:55
Show Gist options
  • Save md-redwan-hossain/35f3e0c13344810d3602c29f448cf243 to your computer and use it in GitHub Desktop.
Save md-redwan-hossain/35f3e0c13344810d3602c29f448cf243 to your computer and use it in GitHub Desktop.
calculate total duration of a youtube playlist by python
# pip install pytube
from pytube import Playlist
from pytube import YouTube
import sys
def convert_sec_to_readable(seconds):
minute, second = divmod(seconds, 60)
hour, minute = divmod(minute, 60)
return "%d:%02d:%02d" % (hour, minute, second)
try:
playlist_link = sys.argv[1]
except IndexError:
playlist_link = input("enter playlist link: ")
print("Loading...")
total_secs = 0
playlist_obj = Playlist(playlist_link)
all_video_urls: list = list(playlist_obj.video_urls)
failed_video_urls: list = []
total_secs = 0
def calculate_duration(urls):
for url in urls:
try:
single_video_obj = YouTube(url).length
except:
failed_video_urls.append(url)
else:
global total_secs
total_secs += single_video_obj
while True:
calculate_duration(all_video_urls)
if len(failed_video_urls) > 0:
calculate_duration(failed_video_urls)
break
break
print("Approx Total Duration: ", convert_sec_to_readable(total_secs))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment