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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With