enter time-1 // eg 01:12
enter time-2 // eg 18:59
calculate: time-1 to time-2 / 12
// i.e time between 01:12 to 18:59 divided by 12
How can it be don
Here's a timer for timing code execution. Maybe you can use it for what you want. time() returns the current time in seconds and microseconds since 1970-01-01 00:00:00.
from time import time
t0 = time()
# do stuff that takes time
print time() - t0
Simplest and most direct may be something like:
def getime(prom):
"""Prompt for input, return minutes since midnight"""
s = raw_input('Enter time-%s (hh:mm): ' % prom)
sh, sm = s.split(':')
return int(sm) + 60 * int(sh)
time1 = getime('1')
time2 = getime('2')
diff = time2 - time1
print "Difference: %d hours and %d minutes" % (diff//60, diff%60)
E.g., a typical run might be:
$ python ti.py
Enter time-1 (hh:mm): 01:12
Enter time-2 (hh:mm): 18:59
Difference: 17 hours and 47 minutes
The datetime
and timedelta
class from the built-in datetime
module is what you need.
from datetime import datetime
# Parse the time strings
t1 = datetime.strptime('01:12','%H:%M')
t2 = datetime.strptime('18:59','%H:%M')
# Do the math, the result is a timedelta object
delta = (t2 - t1) / 12
print(delta.seconds)
Assuming that the user is entering strings like "01:12"
, you need to convert (as well as validate) those strings into the number of minutes since 00:00
(e.g., "01:12"
is 1*60+12
, or 72 minutes), then subtract one from the other. You can then convert the difference in minutes back into a string of the form hh:mm
.