Skip to content

Instantly share code, notes, and snippets.

@stoufa
Last active August 25, 2023 09:57
Show Gist options
  • Save stoufa/f5ecaa34a3cb5aacec6f3dd82de7bfa1 to your computer and use it in GitHub Desktop.
Save stoufa/f5ecaa34a3cb5aacec6f3dd82de7bfa1 to your computer and use it in GitHub Desktop.
compute the sum of a YouTube videos playlist
// a JS script to compute the sum of a YouTube videos playlist
function unify_format(duration) {
// sum_durations assumes the format 'h:m:s' which is not the case for videos less than an hour
// this function will append missing values to fit into the expected format.
// count number of ':' in duration
const count = duration.split(":").length - 1;
if (count == 0) // e.g. '27'
return `0:0:${duration}`;
if (count == 1) // e.g. '2:27'
return `0:${duration}`;
// count == 2 // e.g. '1:2:27'
return duration;
}
function sum_durations(durations) {
let total_seconds = 0;
for (let duration of durations) {
duration = unify_format(duration);
const [hours, minutes, seconds] = duration.split(":").map(part => parseInt(part));
total_seconds += hours * 3600 + minutes * 60 + seconds;
}
const total_hours = Math.floor(total_seconds / 3600);
const remaining_minutes = Math.floor((total_seconds % 3600) / 60);
const remaining_seconds = total_seconds % 60;
return `${total_hours}:${remaining_minutes}:${remaining_seconds}`;
}
let durations = [...document.querySelectorAll('.playlist-items span.ytd-thumbnail-overlay-time-status-renderer')].map(x => x.innerText.trim());
console.log(`playlist total length: ${sum_durations(durations)}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment