background gradient
s2 - IT photo №27610

How do PT3M21S YouTube API convert to 03:21 time?

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
PHPCopy

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
JavaScriptCopy

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
PythonCopy

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.

Leave a Reply

Navigation:

Similar

1727598643_ms_ChatGPT_-_Google_Chrome-min - IT photo №28606
8
29 Sept 2024

OpenAI will increase the cost of ChatGPT from $22 to $44.

OpenAI is rapidly shifting toward commercial operations. According to The New York Times, the subscription cost for ChatGPT will rise by 120% over the next five years. The current subscription price is $20, but it will increase to $22 by the end of the month, and within five years, the price will reach $44 per […]

AIНовости
og_og_1556109592271718992-min - IT photo №28058
161 7
28 Sept 2024

How do I create a Google account 2024?

Creating a Google account is the first step towards personal recommendations on YouTube and using Google API. In this article, we will look at how to easily and quickly create your Google account and ensure its security. Why do I need a Google account? A personal Google account provides access to various services, including Gmail, […]

Google
imgpreview - IT photo №28122
26 3
14 Dec 2023

How do I make a ruble icon on CSS?

In 2013, the Russian ruble received its own unique symbol, becoming one of the last major currencies to have its own symbols. How do I make a ruble sign in HTML? The ruble icon has already been added to many pins and HTML codes. To display the ruble sign in html, use one of the […]

CSSHTMLТексты и символы
ascii-min - IT photo №28032
4 4
26 Nov 2023

ASCII: Full table of codes 2024

ASCII (American Standard Code for Information Interchange) is a standard character encoding system designed to represent text on a computer. This standard includes various tables reflecting a variety of character categories. In this article, we will look at three important ASCII tables: Control Characters, Printable Characters, and Extended Characters encoded in Win-1251 Cyrillic. Control characters […]

HTMLТексты и символы