To change a character to a time form in Python

Asked 2 years ago, Updated 2 years ago, 113 views

Hello.

Python used an external api to call up the time "3m 32s" and "1h 23m 6s" are written like this. How do I change it to separate it into a colon by two digits like "00:03:32" and "01:23:06"?

It's kind of vague to do it with split or slicing, and it' I'm asking if there's a good way!

python time date split slice

2022-09-20 17:56

1 Answers

>>> def hms2iso(s): 
    t = { e[-1]:int(e[:-1]) for e in s.split() }
    return "%02d:%02d:%02d"%( t.get('h', 0), t.get('m', 0), t.get('s', 0) )

>>> for e in s:
    print(e, hms2iso(e))


3m 32s 00:03:32
1h 23m 6s 01:23:06
>>> s = ["3m32s", "1h23m6s"]
>>> def hms2iso(f):
    num = ''
    t = {}
    for c in f:
        if c.isalpha():
            t[c] = int(num)
            num = ''
            continue
        num += c
    return "%02d:%02d:%02d"%( t.get('h', 0), t.get('m', 0), t.get('s', 0) )

>>> for f in s:
    print(f"{f} -> {hms2iso(f)}")


3m32s -> 00:03:32
1h23m6s -> 01:23:06


2022-09-20 17:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.