Solus
Solus

Reputation: 25

How to convert A "hours and minutes and seconds" string to HH:MM:SS format?

In python, I am trying to make an alarm system where it converts "x Hours y Minutes and z Seconds" to the x:y:z format For example:

5 hours 20 minutes 6 seconds
05:20:06

1 hour 25 seconds
01:00:25

This is my code, but it seems scuffed:

time_string = '1 hour and 25 seconds'

correction = time_string.replace('and ', '')
duration = correction.replace(' hour', ':').replace(' minute', ':').replace(' second', ':').replace(' ','').replace('s', '')
    if 'minute' not in correction and 'second' not in correction:
        duration = duration + '00:00'
    elif 'minute' not in correction and 'second' in correction:
        duration = duration.replace(':',':00:')
    elif 'second' not in correction:
        duration = duration + '00' 
    secs = sum(int(x) * 60 ** i for i, x in enumerate(reversed(duration.split(':'))))

How do I improve it?

Upvotes: 1

Views: 2006

Answers (3)

JL Peyret
JL Peyret

Reputation: 12174

from collections import defaultdict

dataexp = [
("5 hours 20 minutes 6 seconds","05:20:06"),
("1 hour 25 seconds","01:00:25")
]

def convert(input_):
    words = input_.replace('and','').split()
    di = defaultdict(lambda:0)
    while words:
        num = int(words.pop(0))
        unit = words.pop(0)[0]
        di[unit] = num

    return f"{di['h']:02}:{di['m']:02}:{di['s']:02}"

for inp, exp in dataexp:

    got = convert(inp)
    msg = "\nfor %-100.100s \nexp :%s:\ngot :%s:\n" % (inp, exp, got)
    if exp == got:
        print("✅! %s" % msg)
    else:
        print("❌! %s" % msg)

which outputs:

✅!
for 5 hours 20 minutes 6 seconds
exp :05:20:06:
got :05:20:06:

✅!
for 1 hour 25 seconds
exp :01:00:25:
got :01:00:25:

Upvotes: 0

Dinesh Jinjala
Dinesh Jinjala

Reputation: 29

You can use datetime library to convert this type of string to proper formatted string.

from datetime import datetime

def format_time(string):
    format_string = ''
    if 'hour' in string:
        if 'hours' in string:
            format_string += '%H hours '
        else:
            format_string += '%H hour '
    if 'minute' in string:
        if 'minutes' in string:
            format_string += '%M minutes '
        else:
            format_string += '%M minute '
    if 'second' in string:
        if 'seconds' in string:
            format_string += '%S seconds'
        else:
            format_string += '%S second'
    value = datetime.strptime(string, format_string)
    return value.strftime('%H:%M:%S')

string = '5 hours 20 minutes 6 seconds'
print(format_time(string))

string = '1 hour 25 seconds'
print(format_time(string))

string = '1 minute 25 seconds'
print(format_time(string))

Output

05:20:06
01:00:25
00:01:25

Upvotes: 1

Tim Roberts
Tim Roberts

Reputation: 54726

This returns total number of seconds, which seems to be what you wanted:

def parsex(s):
    hh = mm = ss = 0
    for word in s.split():
        word = word.lower()
        if word.isdigit():
            save = word
        elif word.startswith('hour'):
            hh = int(save)
        elif word.startswith('minute'):
            mm = int(save)
        elif word.startswith('second'):
            ss = int(save)
    return (hh*60+mm)*60+ss

print(parsex('1 hour and 30 seconds'))
print(parsex('2 hours 15 minutes 45 seconds'))

Upvotes: 1

Related Questions