Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How would I parse a time string to seconds in python?

Here are some examples of what the time strings would look like:

parse_time_string("20s") # 20
parse_time_string("30sec") # 30
parse_time_string("3m") # 180
parse_time_string("2min") # 120
parse_time_string("5h") # 18000
parse_time_string("1d") # 86400

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

A simple approach using a regexp to split the string to the number and unit parts, and a bit of multiplication:

import re

multipliers = {
    "s": 1,
    "sec": 1,
    "m": 60,
    "min": 60,
    "h": 60 * 60,
    "d": 86400,
}


def parse_time_string(param):
    value, unit = re.match(r"^(\d+)([a-z]+)$", param).groups()
    return int(value) * multipliers[unit]


for example in ("20s", "30sec", "3m", "2min", "5h", "1d"):
    print(example, parse_time_string(example))
20s 20
30sec 30
3m 180
2min 120
5h 18000
1d 86400
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading