jezhuz jezhuz - 1 year ago 64
Python Question

Python: change "- hrs - min - sec' string into minutes decimal

I am currently working on a project in Python (had to self-teach myself Python, still currently learning) that takes data from a csv file given to me.

I am currently stuck on how I would loop through the list to translate a string from a list such as "2 hrs 5 min 15 sec" into a decimal and saves it as another list/array.

I know about H:M:S, but in some areas of the list, it is just "8 min 4 sec", so it varies from having an hour count to just having minutes and seconds.


Answer Source

There are multiple options to parse these time strings. Here is one way to do it (probably not the most short one, but an easy to understand) - using time.strptime() to load the time string by trial and error using 3 different formats:

import time
from datetime import timedelta

def get_seconds(item):
        x = time.strptime(item, '%H hrs %M min %S sec')
    except ValueError:
            x = time.strptime(item, '%M min %S sec')
        except ValueError:
            x = time.strptime(item, '%S sec')
    return timedelta(hours=x.tm_hour, minutes=x.tm_min, seconds=x.tm_sec).total_seconds()

l = [
    "2 hrs 5 min 15 sec",
    "8 min 4 sec",
    "2 sec"

for item in l:

Prints the total number of seconds for every time string: