Amr
Amr

Reputation: 115

How to convert time written in hours + minutes to minutes only with python

I extract a string that contains movie time

2h 28min

I want to convert the time to mins (2*60+28)

that's my approach but I am looking for an easier way

ar = time.split()
def split(word):
  return [char for char in word]
if 'h' in ar[0]:
  word = ar[0]
  sp = split(word)
  hours = int(sp[0]) * 60
  mins = re.findall(r'\d+', ar[1])
  time = hours + int(mins[0])
else:
  mins = re.findall(r'\d+', ar[0])
  time = int(mins[0])

Upvotes: 0

Views: 1017

Answers (2)

KarmaPenny
KarmaPenny

Reputation: 170

If you have a predetermined format, codotron's answer works. However, with Codtron's answer, the hour must be one digit, the minutes must be 2, and there must be a space between the hour and minte. But, if the input can be 2hr28min or 2h 28min or 2 hours and 28 minutes, or even 123 hours 1 minute, then we need to parse some tokens to extract the 2 numbers.

To do this, we can use regex:

import re
s = input("Time: ")
hm = re.findall("\d+", s) #returns list containing ['hr', 'min']
hm = [int(x) for x in hm]
print(hm[0]*60+hm[1])

Output

>>>Time: 3 hours 40 minutes
>>>220
>>>
>>>Time: 2hr5min
>>>125
>>>
>>>Time: 2h5
>>>125

Upvotes: 2

codotron
codotron

Reputation: 51

if it is a string as you say then you can do something like this

s = '2h 28min'
s = s.split()
a=int(s[0][:len(s[0])-1])
b=int(s[1][:len(s[1])-3])
time = (a*60)+b
ans = str(time)+'min'

Output

>>> 148min

Edit: Mistake in code

Upvotes: 0

Related Questions