How to build a simple youtube playlist length calculator using Python
Have you ever stumbled upon an amazing YouTube playlist—maybe a tutorial series or a collection of your favorite songs—and wondered, "Just how long will this take to watch?" I've been there. It's a simple question, but YouTube doesn't always give you a simple answer. Let's see how we can solve this little puzzle ourselves by calculating the length of any YouTube or YouTube Music playlist using Python.
Python is a wonderfully versatile programming language known for its simple, English-like syntax, which makes it a great choice for beginners and experts alike. It's used for everything from web development to data science, and today, we're going to use it to build a handy little tool.
If you're curious about what sparked this whole idea, you can read the full story of my accidental project here.
What We're Going to Build
Our goal is to write a Python script that takes a YouTube playlist URL and tells us the total duration in a clean "Hours:Minutes:Seconds" format. We'll be using the official YouTube Data API and the popular requests library in Python to make this happen.
Step 1: Getting Your YouTube API Key
Before we can ask YouTube for any information, we need to get a special key that lets us talk to its data servers. Think of it as a library card for Google's vast collection of data. This key is completely free for personal use, but Google uses it to keep track of who is making requests.
Here's how you can get one:
- Go to the Google Cloud Console: You'll need a Google account for this. Head over to the Google Cloud Console.
- Create a New Project: If you don't have one already, create a new project. Give it a simple name like "YouTube Calculator."
- Enable the YouTube Data API: In the dashboard, search for "YouTube Data API v3" in the API library and enable it for your project. This tells Google that you intend to use this specific API.
- Create Credentials: Go to the "Credentials" page, click "Create Credentials," and select "API key." Google will generate a long string of characters for you.
Important: Copy this API key and save it somewhere safe. We'll need it in our script. Treat this key like a password; don't share it publicly.
Step 2: Setting Up Your Python Environment
Now, let's get our coding environment ready. We only need one external library for this project: requests. This library makes it incredibly simple to send HTTP requests to servers, like the YouTube API.
If you don't have it installed, open your terminal or command prompt and type:
pip install requests
And that's it! We're ready to start coding.
Step 3: The Plan - How Will This Work?
Our logic is straightforward and involves a few calls to the YouTube API:
- Get All Video IDs from the Playlist: The first API call will take our playlist ID and give us a list of all the video IDs within that playlist.
- Get the Duration of Each Video: The YouTube API doesn't give us the duration in the first call. So, we'll make a second API call, feeding it the video IDs we just collected to get the duration of each one.
- Add It All Up: Finally, we'll parse the durations, sum them up, and format the total time nicely.
Step 4: Let's Write Some Code!
Create a new Python file, maybe named playlist_calculator.py, and let's start building this step by step.
A. Getting the Video IDs
First, we need to get all the video IDs from our playlist. The YouTube API has a specific endpoint for this called playlistItems.
We'll send a GET request to this URL:
https://www.googleapis.com/youtube/v3/playlistItems
This request needs a few parameters to work:
- part: We'll set this to contentDetails to get the video ID.
- playlistId: This is where the ID of the YouTube playlist goes.
- maxResults: The API can return a maximum of 50 items at a time. We'll set this to 50.
- key: Your API key.
Here's what the initial Python code looks like:
import requests
API_KEY = 'YOUR_API_KEY' # Paste your API key here
playlist_id = 'YOUR_PLAYLIST_ID' # The ID of the playlist you want to analyze
url = f"https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails&playlistId={playlist_id}&maxResults=50&key={API_KEY}"
response = requests.get(url)
data = response.json()
# Let's see what we got
print(data)
Before running this, you'll need to find the playlist_id. If your playlist URL is https://www.youtube.com/playlist?list=PL-J2q3Ga50oN_Po-s3-1Vl_k3gLaXvOPD, the ID is the part after list=, which is PL-J2q3Ga50oN_Po-s3-1Vl_k3gLaXvOPD.
B. Handling More Than 50 Videos (Pagination)
What if the playlist has more than 50 videos? The API response will include a nextPageToken. We need to grab this token and make another request to get the next batch of 50 videos, and so on, until there are no more pages left.
Let's modify our code to loop through all the pages:
import requests
API_KEY = 'YOUR_API_KEY'
playlist_id = 'YOUR_PLAYLIST_ID'
video_ids = []
next_page_token = None
while True:
url = f"https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails&playlistId={playlist_id}&maxResults=50&key={API_KEY}"
if next_page_token:
url += f"&pageToken={next_page_token}"
response = requests.get(url)
data = response.json()
for item in data.get('items', []):
video_ids.append(item['contentDetails']['videoId'])
next_page_token = data.get('nextPageToken')
if not next_page_token:
break
print(f"Collected {len(video_ids)} video IDs.")
This loop will continue fetching video IDs until all of them are collected in our video_ids list.
C. Getting the Video Durations
Now that we have all the video IDs, we need to get their durations. We'll use the videos endpoint for this. A great thing about this endpoint is that we can pass it a comma-separated list of up to 50 video IDs at once, which is much more efficient than asking for them one by one.
The URL looks like this:
https://www.googleapis.com/youtube/v3/videos
And the parameters:
- part: We'll set this to contentDetails as it contains the duration.
- id: A comma-separated string of video IDs.
- key: Your API key.
Here's how we can get the durations:
# (Continuing from the previous code block)
total_seconds = 0
# The API allows fetching details for 50 videos at a time
for i in range(0, len(video_ids), 50):
video_ids_batch = video_ids[i:i+50]
ids_string = ','.join(video_ids_batch)
videos_url = f"https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id={ids_string}&key={API_KEY}"
videos_response = requests.get(videos_url)
videos_data = videos_response.json()
# Now we need to parse the duration from each video
for item in videos_data.get('items', []):
duration_str = item['contentDetails']['duration']
# The duration is in a format like 'PT1H5M23S'
# We'll need a helper function to parse this
D. Parsing the "Weird" Duration Format
The duration from the API comes in the ISO 8601 format (e.g., PT1H5M23S means 1 hour, 5 minutes, and 23 seconds). We need to convert this into a total number of seconds. We can do this with a bit of regular expression magic.
Let's write a helper function for this:
import re
def parse_duration(duration_str):
# This regex will find numbers associated with H, M, and S
match = re.match(r'PT(\d+H)?(\d+M)?(\d+S)?', duration_str).groups()
hours = int(match[0][:-1]) if match[0] else 0
minutes = int(match[1][:-1]) if match[1] else 0
seconds = int(match[2][:-1]) if match[2] else 0
return hours * 3600 + minutes * 60 + seconds
Now, let's plug this into our loop:
# (Continuing inside the video fetching loop)
for item in videos_data.get('items', []):
duration_str = item['contentDetails']['duration']
total_seconds += parse_duration(duration_str)
E. Making the Final Result Look Good
After the loop finishes, total_seconds will hold the entire duration of the playlist in seconds. Let's convert this into a more human-readable format.
# (After all loops are done)
minutes, seconds = divmod(total_seconds, 60)
hours, minutes = divmod(minutes, 60)
print(f"Total Playlist Duration: {hours} hours, {minutes} minutes, {seconds} seconds")
The Complete Script
Here is the full, final script all put together. Just paste in your API key and a playlist ID, and you're good to go!
import requests
import re
def get_playlist_duration(api_key, playlist_id):
video_ids = []
next_page_token = None
# Step 1: Get all video IDs from the playlist
while True:
url = f"https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails&playlistId={playlist_id}&maxResults=50&key={api_key}"
if next_page_token:
url += f"&pageToken={next_page_token}"
response = requests.get(url)
data = response.json()
for item in data.get('items', []):
video_ids.append(item['contentDetails']['videoId'])
next_page_token = data.get('nextPageToken')
if not next_page_token:
break
# Step 2: Get the duration for each video
total_seconds = 0
for i in range(0, len(video_ids), 50):
video_ids_batch = video_ids[i:i+50]
ids_string = ','.join(video_ids_batch)
videos_url = f"https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id={ids_string}&key={api_key}"
videos_response = requests.get(videos_url)
videos_data = videos_response.json()
for item in videos_data.get('items', []):
duration_str = item['contentDetails']['duration']
total_seconds += parse_duration_str(duration_str)
# Step 3: Format the duration
minutes, seconds = divmod(total_seconds, 60)
hours, minutes = divmod(minutes, 60)
return hours, minutes, seconds
def parse_duration_str(duration_str):
match = re.match(r'PT(\d+H)?(\d+M)?(\d+S)?', duration_str).groups()
hours = int(match[0][:-1]) if match[0] else 0
minutes = int(match[1][:-1]) if match[1] else 0
seconds = int(match[2][:-1]) if match[2] else 0
return hours * 3600 + minutes * 60 + seconds
if __name__ == '__main__':
API_KEY = 'YOUR_API_KEY'
PLAYLIST_ID = 'PL-J2q3Ga50oN_Po-s3-1Vl_k3gLaXvOPD' # Example: Namaste Javascript Playlist
h, m, s = get_playlist_duration(API_KEY, PLAYLIST_ID)
print(f"Total Playlist Duration:")
print(f"{h} hours, {m} minutes, {s} seconds")
And There You Have It!
We just went from a simple idea to a working Python script. It's amazing how a small personal frustration can lead to building something genuinely useful. This script is just the beginning. You could expand it to calculate durations at different playback speeds, sort videos, or even build a full web application around it.
Happy coding