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

Фото инструкция по отключению ECH в Cloudflare (TLS v3)
7 6
06 Nov 2024

How to Disable ECH (TLS 1.3) in Cloudflare

Internet Blocked: How Cloudflare and ECH Clashed with Roskomnadzor The internet in Russia has faced a massive blockade—thousands of websites using ECH have stopped opening in Russia. What is ECH and Why is it Needed? ECH (Encrypted Client Hello) is a technology that encrypts traffic and hides domain names from ISPs. Enabling ECH on Cloudflare […]

SEOНовости
21437004-cf3d-4d35-aa13-82183efb2955_11zon - IT photo №28679
122 5
02 Oct 2024

The $_GET does not contain utm_source. How to Retrieve UTM Tags in PHP?

Many encounter the issue when UTM tags are not fully transmitted through $_GET or $_SERVER. Why does this happen? The issue lies in the specifics of URL parsing. “I can’t get all UTM tags from the address. `utm_source` and `utm_medium` are being cut off.” Solutions Check the URL. Ensure that all parameters are properly encoded. […]

PHPSEO
1727598643_ms_ChatGPT_-_Google_Chrome-min - IT photo №28606
19
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
193 7
28 Sept 2024

How do I create a Google account 2025?

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
41 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
40 4
26 Nov 2023

ASCII: Full table of codes 2025

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Тексты и символы