So I'll admit that this is a homework assignment, but I'm not asking you all to do it for me, I'm just looking for some guidance. We need to make a Python program to accept a time in Hours:Minutes (2:30) format in a single string, and output the amount of time in minutes. (i.e. 2 hours and 30 minutes = 150 minutes)
I still need to work out some limitations for the string input:
I'll work on that later — for now I decided to work on the math I would get from the input.
It made sense to me to slice the string into two parts: hours and minutes. I then multiplied the amount of hours by 60 and added them to the pre-existing minutes to get a total amount of minutes. However, right now, entering a time like 02:45 is outputting a minute amount of 02020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020245.
Any idea what might be going wrong here? Just to be clear, this is homework and I want to work out the input limitations on my own, I just need help moving past this math issue.
#Henry Quinn - Python Advanced 4.0 Hours and Minutes
import re
print "This program takes an input of time in hours and minutes and outputs the amount of minutes."
count = 0
#I still need to work out while loop
#Supposed to make sure that a time is entered correctly, or error out
while (count <1):
time = raw_input("Please enter the duration of time (ex: 2:15 or 12:30): ")
if not re.match("^[0-9, :]*$", time):
print "Sorry, you're only allowed to use the numbers 0-9."
elif len(time) > 5:
print "Sorry, only five characters max allowed."
#MAKE THIS CHECK FOR A COLON
#elif
#elif
else:
count = count + 1
#If time = 12:45, hours should be equal to 12, and minutes should be equal to 45
hours = time[:2]
minutes = time[3:]
#Should convert hours to minutes
newhours = hours * 60
#Should make total amount of minutes
totalminutes = newhours + minutes
print "The total amount of elapsed minutes is %s" % (totalminutes)
raw_input("Please press Enter to terminate the program.")
Right now, hours and minutes are string variables, not ints. Thus, you can't multiply them as you would a number.
Change lines 20 and 21 to
hours = int(time[:2])
minutes = int(time[3:])
And putting in 02:45 should work. However, you will still run into problems if you don't have that leading 0 (like if you put in 2:45), so might I suggest you instead split it around the ":", like so:
hours = int(time.split(":")[0])
minutes = int(time.split(":")[1])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With