Skip to content

Instantly share code, notes, and snippets.

@traveaston
Created November 7, 2019 21:17
Show Gist options
  • Save traveaston/da540765cb536bd73dea6f2cdf5e4648 to your computer and use it in GitHub Desktop.
Save traveaston/da540765cb536bd73dea6f2cdf5e4648 to your computer and use it in GitHub Desktop.
Get the total length or duration of a Youtube playlist
(() => {
const formatTime = (seconds) => {
const units = {
days: Math.floor(seconds / 60 / 60 / 24),
hours: Math.floor(seconds / 60 / 60 % 24),
minutes: Math.floor(seconds / 60 % 60),
seconds: seconds % 60
}
// remove empty units, singularize if necessary, and return a string
return Object.entries(units).filter(([unit, value]) => value !== 0)
.map(([unit, value]) => `${value} ${value === 1 ? unit.slice(0, -1) : unit}`)
.reduce((totalTime, x) => totalTime + ', ' + x)
}
const timestamps = [...document.querySelectorAll('span.ytd-thumbnail-overlay-time-status-renderer')]
.map(x => x.innerText.trim())
.map(x => {
const [min, sec] = x.split(':')
return min * 60 + sec * 1
})
const totalTime = formatTime(
timestamps.reduce((totalSeconds, x) => totalSeconds + x)
)
console.log('%c Playlist total: %s', 'font-size: 2.5em; color: cyan', totalTime)
})()
@traveaston
Copy link
Author

Navigate to a youtube playlist and paste into the Javascript console (⌥ ⌘ J on macOS)
You don't need to be logged in, so if the console makes you nervous, just open it in an incognito window.

@traveaston
Copy link
Author

Honestly, I probably wouldn't iterate an object in this way in a production application but for this case I thought it was interesting to be able to slice off the 's' to make the unit singular.
Also I will admit it doesn't look as hacky in python, which is where I took the code for the formatTime function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment