eozzy
eozzy

Reputation: 68650

Calculate time between time-1 to time-2?

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.

Upvotes: 11

Views: 24211

Answers (4)

Alex Martelli
Alex Martelli

Reputation: 881557

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

Upvotes: 6

iamamac
iamamac

Reputation: 10106

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)

Upvotes: 17

David R Tribble
David R Tribble

Reputation: 12204

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.

Upvotes: 0

Tor Valamo
Tor Valamo

Reputation: 33749

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

Upvotes: 4

Related Questions