Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best approach to calculate mph in python

Tags:

python

I've returned to writing in python after a long break from the language, I'm currently writing a program which takes latitude and longitude values, calculates the distance between them in kilometres and miles per hour, and calculates the time to get from one coordinate to the other, now I've got my program already to calculate the distances between coordinates and the time durations, and as a result I've got two lists to work with:

The first is a list of time durations to get from one location to the other in the format HH:MM:SS currently. As below

timeduration = ['0:07:11', '0:15:16', '0:18:17', '0:23:15']

and also a list of distances in kilometres which I've calculated from latitude/longitude coordinates

distances = ['0.6', '0.4', '1.3', '1.7']

What I would now like to do, is to now calculate these in python, however I'm at a bit of a loss as to the formula or approach which would be best suited to this.

I know if we took both of the first two values from both lists
e.g. timeduration[0] and distances[0], this should give us the mph speed of 3.195623 mph or 5.14286 km/h. However I am at loss of how this would translate into python.

like image 820
ashwood23 Avatar asked Mar 04 '23 19:03

ashwood23


2 Answers

Given a time string, say timeduration[0], you can convert this into hours as follows:

h, m, s = timeduration[0].split(":")
hours = int(h) + int(m)/60 + int(s)/3600

That, for example, will give a value of 0.1197 hours. You could do this for each value in your list and create a new list with those values.

Then just take your distance values and divide them by the hours values (e.g., distance[i]/times[i]), which would give you the speeds in km/hr.

like image 133
JoshG Avatar answered Mar 30 '23 19:03

JoshG


import datetime,time 
timeduration = ['0:07:11', '0:15:16', '0:18:17', '0:23:15']
distances = ['0.6', '0.4', '1.3', '1.7']
speeds=[];y=0
for i in timeduration:
    x = time.strptime(i.split(',')[0],'%H:%M:%S')
    seconds=datetime.timedelta(hours=x.tm_hour,minutes=x.tm_min,seconds=x.tm_sec).total_seconds()
    hours=float(seconds)/3600
    speeds.append(float(distances[y])/hours)
    y+=1
print speeds
like image 24
wishmaster Avatar answered Mar 30 '23 19:03

wishmaster