views:

347

answers:

4
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 done in Python. I'm a beginner so I really have no clue where to start.

Edited to add: I don't want a timer. Both time-1 and time-2 are entered by the user manually.

Thanks in advance for your help.

+3  A: 

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
Tor Valamo
Nah, I want to calculate time between time-1 and time-2, both entered manually.
Nimbuz
@Tor Valamo : Exactly what I had in mind ! .... cheers to that !
Arkapravo
A: 

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.

Loadmaster
+7  A: 

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)
Iamamac
delta = (t2 - t1) / 12TypeError: unsupported operand type(s) for /: 'datetime.timedelta' and 'int'
Nimbuz
It is OK in python 2.6But you can always convert the timedelta object to an integer and do the math, like this: delta.seconds/12
Iamamac
+4  A: 

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
Alex Martelli
+1 because this is a better way for someone learning python compared to using datetime and timedelta. I would prefer more expressive variable names than 's', 'sh' and 'sm'. Alex, why use the variable 'prom'? Why not call the function without arguments?
Raja
@Raja, heh, I meant to give different prompts on the two occasions but then I had forgotten to use `prom` in the prompting -- fixed. As for variable names, for extremely tiny-scoped variables, tiny names are appropriate -- those who have been taught to name such 2-lines-scope variables `stringAsInputByTheUser`, `hours_in_string_form`, and the like, and never exposed to this important distinction about scoping, should start getting exposed to this issue.
Alex Martelli