When working with the YouTube API v3, there is a list method for the Video category (https://www.googleapis.com/youtube/v3/videos ).
When using it, you get an array with a video inside which objects contain data about each video, one of these parameters is “duration” which contains time in PT3M21S format.
How do I convert this time to a more readable format of hours, minutes and seconds? Let’s look at examples in PHP, JavaScript and Python.
How to convert PT3M21S to PHP?
function convertYouTubeDuration($video_duration = '', $format = "H:i:s") {
if(!$video_duration) return false;
$start = new DateTime('@0'); // Unix epoch
$start->add(new DateInterval($video_duration));
return $start->format($format);
}
// Пример использования функции
$video_duration = 'PT2H30M45S'; // Пример длительности в формате YouTube
$video_duration_seconds = convertYouTubeDuration($video_duration);
var_dump($video_duration_seconds); // Выводит преобразованную длительность 2:30:45
How do I convert PT3M21S to JavaScript?
function convertYouTubeDuration(video_duration, format = "HH:mm:ss") {
if (!video_duration) return false;
const start = new Date(0);
const durationArray = video_duration.match(/\d+/g);
if (!duration Array) return false;
const [hours, minutes, seconds] = durationArray.map(Number);
start.setHours(hours);
start.setMinutes(minutes);
start.setSeconds(seconds);
const options = { hour12: false, timeZone: 'UTC' };
const formattedDuration = start.toLocaleTimeString('en-US', options);
return formattedDuration;
}
// Example of using the function
const video_duration = 'PT2H30M45S'; // Example of duration in YouTube format
const video_duration_formatted = convertYouTubeDuration(video_duration);
console.log(video_duration_formatted); // Outputs the converted duration 2:30:45
How do I convert PT3M21S to Python?
from datetime import datetime, timedelta
def convert_youtube_duration(video_duration, format="%H:%M:%S"):
if not video_duration:
return None
duration_parts = video_duration[2:].split('M')
hours, minutes = divmod(int(duration_parts[0]), 60)
minutes, seconds = map(int, duration_parts[1][:-1].split('S'))
start = datetime(1, 1, 1, hours, minutes, seconds)
formatted_duration = start.strftime(format)
return formatted_duration
# Пример использования функции
video_duration = 'PT2H30M45S' # Пример длительности в формате YouTube
video_duration_formatted = convert_youtube_duration(video_duration)
print(video_duration_formatted) # Выводит преобразованную длительность 02:30:45
Now you can easily integrate the YouTube video duration conversion function into your JavaScript, Python or PHP code when working with the YouTube API v3 and provide users with an understandable video time format.