0

I need to figure out the simplest method of grabbing the length of a youtube video programmatically given the url of said video.

Is the youtube API the best method? It looks somewhat complicated and I've never used it before so it's likely to take me a bit to get accommodated, but I really just want the quickest solution. I took a glance through the source of a video page in the hopes it might list it there, but apparently it does not (though it lists recommended video times in a very nice list that would be easy to parse). If it is the best method, does anyone have a snippit?

Ideally I could get this done in Python, and I need it to ultimately be in the format of

00:00:00.000

but I'm completely open to any solutions anyone may have.

I'd appreciate any insight.

Velimir Mlaker
  • 10,664
  • 4
  • 46
  • 58
src
  • 115
  • 3
  • 7

5 Answers5

3

All you have to do is read the seconds attribute in the yt:duration element from the XML returned by Youtube API 2.0. You only end up with seconds resolution (no milliseconds yet). Here's an example:

from datetime import timedelta
from urllib2 import urlopen
from xml.dom.minidom import parseString
for vid in ('wJ4hPaNyHnY', 'dJ38nHlVE78', 'huXaL8qj2Vs'):
    url = 'https://gdata.youtube.com/feeds/api/videos/{0}?v=2'.format(vid)
    s = urlopen(url).read()
    d = parseString(s)
    e = d.getElementsByTagName('yt:duration')[0]
    a = e.attributes['seconds']
    v = int(a.value)
    t = timedelta(seconds=v)
    print(t)

And the output is:

0:00:59
0:02:24
0:04:49
Velimir Mlaker
  • 10,664
  • 4
  • 46
  • 58
  • That met all of my needs splendidly, thank you very much for that knowledge and example. – src Jun 21 '13 at 17:36
  • that url no longer returns anything. You have to use google apis with an api key as explained in Joan's answer https://stackoverflow.com/a/33725265/2205372 – Ambrose Leung Jun 16 '17 at 11:17
1

(I'm not sure what "pre-download" refers to.)

The simplest way to get the length of VIDEO_ID is to make an HTTP request for

http://gdata.youtube.com/feeds/api/videos/VIDEO_ID?v=2&alt=jsonc

and then look at the value of the data->duration element that's returned. It will be set to the video's duration in seconds.

Jeff Posnick
  • 53,580
  • 14
  • 141
  • 167
  • Ah, I see now how to go about doing it, thank you for that insight. I had been using ffmpeg to get the length of the video after I had already downloaded it, but I needed a different solution. – src Jun 21 '13 at 17:37
  • Does not seem to work anymore. I guess this 2013 suggestion is out of date – CPBL May 09 '21 at 13:44
1

With python and V3 youtube api this is the way for every videos. You need the API key, you can get it here: https://console.developers.google.com/

# -*- coding: utf-8 -*-
import json
import urllib

video_id="6_zn4WCeX0o"
api_key="Your API KEY replace it!"
searchUrl="https://www.googleapis.com/youtube/v3/videos?id="+video_id+"&key="+api_key+"&part=contentDetails"
response = urllib.urlopen(searchUrl).read()
data = json.loads(response)
all_data=data['items']
contentDetails=all_data[0]['contentDetails']
duration=contentDetails['duration']
print duration

Console response:

>>>PT6M22S

Corresponds to 6 minutes and 22 seconds.

Joan Triay
  • 1,518
  • 6
  • 20
  • 35
0

You can always utilize Data API v3 for this. Just do a videos->list call.

GET https://www.googleapis.com/youtube/v3/videos?part=contentDetails%2C+fileDetails&id={VIDEO_ID}&key={YOUR_API_KEY}

In response get the contentDetails.duration in ISO 8601 format.

Or you can get duration in ms from fileDetails.durationMs.

Ibrahim Ulukaya
  • 12,767
  • 1
  • 33
  • 36
0

If you're using Python 3 or newer you can perform a GET request against the YouTube v3 API URL. For this you will need the enable the YouTube v3 API in your Google Console and you'll need to create an API credential after you enable the YouTube v3 API.

Code examples below:

import json 
import requests 

YOUTUBE_ID = 'video_id_here'
API_KEY = 'your_youtube_v3_api_key'
url = f"https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id={YOUTUBE_ID}&key={API_KEY}"

response = requests.get(url) # Perform the GET request 
data = response.json() # Read the json response and convert it to a Python dictionary 

length = data['items'][0]['contentDetails']['duration']
print(length)

Or as a reusable function:

import json 
import requests 

API_KEY = 'your_youtube_v3_api_key'
def get_youtube_video_duration(video_id):
    url = f"https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id={video_id}&key={API_KEY}"

    response = requests.get(url) # Perform the GET request 
    data = response.json() # Read the json response and convert it to a Python dictionary 

    return data['items'][0]['contentDetails']['duration']

duration = get_youtube_video_duration('your_video_id')

Note: You can only get fileDetails from the API if you own the video, so you'll need to use the same Google account for your YouTube v3 API key as your YouTube account.

The response from Google will look something like this:

{
    "kind": "youtube#videoListResponse",
    "etag": "\"SJajsdhlkashdkahdkjahdskashd4/meCiVqMhpMVdDhIB-dj93JbqLBE\"",
    "pageInfo": {
        "totalResults": 1,
        "resultsPerPage": 1
    },
    "items": [
        {
            "kind": "youtube#video",
            "etag": "\"SJZWTasdasd12389ausdkhaF94/aklshdaksdASDASddjsa12-18FQ\"",
            "id": "your_video_id",
            "contentDetails": {
                "duration": "PT4M54S",
                "dimension": "2d",
                "definition": "hd",
                "caption": "false",
                "licensedContent": false,
                "projection": "rectangular"
            }
        }
    ]
}

Where your video duration is: PT4M54S which means 4 Minutes 54 Seconds

Edit: To convert the YouTube duration to seconds, see this answer: https://stackoverflow.com/a/49976787/2074077

Once you convert to time to seconds, you can convert seconds into your format with a timedelta.

from datetime import timedelta
time = timedelta(seconds=duration_in_seconds)
print(time)
Kalob Taulien
  • 1,817
  • 17
  • 22