'how can i convert multiple strings like ("1 hour, 48 minute, 32 seconds") to seconds(number) then add them together in python?

I am using python rn, the context is that I have a playlist on youtube that I want to know how long is it, so I used selenium to automate it to get all the texts from the videos and now I have a list that has like 200 different strings like(1 hour, 42 minutes, 12 seconds) not 1:42:12 and some of them are only minutes and seconds(54 minutes, 23 seconds) and some of them have the value("None") what function or method can I use to deal with all these so I can add them and get the result in seconds

this is how I got the texts from the videos

table = []
elements = driver.find_elements(By.XPATH, '//*[@id="text"]')

for element in elements:
    table.append(element.get_attribute('aria-label'))
print(table)

now my table variable have different values like[None, '3 minutes, 16 seconds', None, '41 minutes, 45 seconds', None, '1 hour, 50 minutes, 29 seconds']

how can I convert them all to seconds, specifically integers without the phrase"seconds" so I can add them together?



Solution 1:[1]

Write a function that splits the string into parts and adds up the number of total seconds:

>>> def string_to_seconds(time: str) -> int:
...     seconds = 0
...     for x in time.split(", "):
...         if x == "None":
...             continue
...         num, units = x.split()
...         if units.startswith("hour"):
...             seconds += int(num) * 3600
...         elif units.startswith("minute"):
...             seconds += int(num) * 60
...         elif units.startswith("second"):
...             seconds += int(num)
...     return seconds
...
>>> string_to_seconds("1 hour, 42 minutes, 12 seconds")
6132

Then you can use that to sum your list of strings:

>>> sum(string_to_seconds(x) for x in [
...     "1 hour, 42 minutes, 12 seconds",
...     "54 minutes, 23 seconds",
...     "None"
... ])
9395

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Samwise