Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate time between time-1 to time-2?

Tags:

python

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.

like image 637
eozzy Avatar asked Dec 27 '09 04:12

eozzy


People also ask

How do I use the calculator to calculate time?

To use the calculator, simply enter a start time, for instance 8:05am, then enter an end time such as 12:45pm. The calculator will automatically generate the time duration in decimal hours (e.g. 4.67 hours) and in hours and minutes (e.g. 4 hours and 40 minutes)

How to calculate the hours between two times in a day?

In the screen below, start and end values contain both dates and times, and the formula is simply: = C5 - B5 // end-start. The result is formatted with the custom number format: [ h] :mm. to display elapsed hours. This formula will correctly calculate the hours between two times in a single day, or over multiple days.

How do you find the time between two dates?

Time Between Two Dates. Use this time and date duration calculator to find out the number of days, hours, minutes, and seconds between the times on two different dates. To add or subtract time from a date, use the Time Calculator. .

How do you calculate the duration of a day?

Simple duration calculation When start time and end time occur in the same day, calculating duration in hours is straightforward. For example, with start time of 9:00 AM and an end time of 5:00 PM, you can simply use this formula: = end - start = 5 :00PM - 8 :00AM = 0.375 - 0.708 =.333 // 8 hours


2 Answers

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)
like image 58
iamamac Avatar answered Sep 28 '22 17:09

iamamac


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
like image 23
Alex Martelli Avatar answered Sep 28 '22 16:09

Alex Martelli