Home > OS >  convert times like these 1h30m/13h30m/1d5m into seconds
convert times like these 1h30m/13h30m/1d5m into seconds

Time:02-07

time_convert = {"s":1, "m":60, "h":3600,"d":86400}
converted = int(time[0]) * time_convert[time[-1]]

That code above only converts the first first number to the corresponding converted time so 12h would come back as 3600 instead of 43200, so that way no other times would work for what I'm trying to do. I'm wanting to convert any time the user says into seconds so, 1h5m,15h40m,1d55m ect

CodePudding user response:

A regex based approach could work well:

total = 0
time_convert = {"s": 1, "m": 60, "h": 3600, "d": 86400}
for quantity, unit in re.findall("(\d )([dhm])", "1h30m"):
    total  = time_convert[unit] * int(quantity)
print(total)

>>> 5400

re.findall returns all matches in a given string. We're matching for a number that's 1 or more digits long (\d ), then we're matching for one of d, h, or m. These first and second groups correspond to the quantity and the unit.

CodePudding user response:

You can use also strptime to convert the string to a time object and timedelta to calculate the total number of seconds:

import time
from datetime import timedelta

time_str = "1h30m"

time_obj = time.strptime(time_str, "%Hh%Mm")
seconds = timedelta(hours=time_obj.tm_hour, minutes=time_obj.tm_min).total_seconds()

print(seconds)

This will output:

5400.0

You can find more on how to configure expected time format and others here: strptime and timedelta

  •  Tags:  
  • Related