1
from datetime import datetime
run = 1
list1 = []
for i in range(2):
     while run > 0:
          print("")
          reg_num = input('reg num')
          enter = input('time  enter in the form "HH:MM:SS" in 24 hours format')
          ext = input('time exit in the form "HH:MM:SS" in 24 hours format')
          total_time = '%H:%M:%S'
          if int(enter[0:1]) > int(ext[0:1]):
               total_time = enter[0:1] + 24
          t_diff = datetime.strptime(ext, total_time)- datetime.strptime(enter, total_time)
          t_diff1 = str(t_diff)
          print(t_diff)
          t_diff2 = int(t_diff1[4:5])
          t_diff3 = int(t_diff1[7:8])
          time = ((t_diff2/60)+(t_diff3/60/60))
          speed = run/time
          print("{:.2f}".format(speed), "mph")
          if speed > 70:
               list1.append(reg_num)
          break
for item in list1:
     print(item, "is over speeding")

This is code to work out the speed of something as it enters and exits a checkpoint that is set a mile apart.

What I am trying to do here is to find the difference in time when the time entered hour is greater than time exited hour. i.e. enter = 23:59:00 and ext = 00:00:00. I know that I have to add 24 to the %H but I don’t know how to do it and when I try to run it in the shell the message is:

total_time = enter[0:1] + 24
TypeError: Can't convert 'int' object to str implicitly

The problem I think comes from this part of the code:

if int(enter[0:1]) > int(ext[0:1]):
    total_time = enter[0:1] + 24

Can you help me find out a way to add 24 to the hour section and then store it into the same variable.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
Aj_Krish
  • 13
  • 4
  • 3
    See [What is the standard way to add N seconds to datetime.time in Python?](http://stackoverflow.com/q/100210/562769) – Martin Thoma Mar 25 '16 at 13:08

1 Answers1

-1

In the end you want the speed. This approach calculates it.

The best is to use datetime.datetime objects for all time calculations. Therefore, convert the strings first. You can use datetime.timedelta(hours=24) to create a timedelta object. You can add this to a datetime.datetime object:

from __future__ import division  # if you still work with Python 2
import datetime

run = 1
enter = '23:59:20'
ext = '00:00:00'
time_format = '%H:%M:%S'
enter_time = datetime.datetime.strptime(enter, time_format)
ext_time = datetime.datetime.strptime(ext, time_format)
if enter_time > ext_time:
    ext_time += datetime.timedelta(hours=24)
t_diff = ext_time - enter_time
elapsed_time = t_diff.total_seconds() / 3600
speed = run / elapsed_time
print(speed)

Output:

90.0
Mike Müller
  • 82,630
  • 20
  • 166
  • 161