简体   繁体   中英

Best approach to calculate mph in 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
eg 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 (eg, distance[i]/times[i] ), which would give you the speeds in km/hr.

import datetime
import time

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

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

# turn times into hours
hours = [float(timeduration.split(":")[0]) + float(timeduration.split(":")[1]) / 60 + float(timeduration.split(":")[2]) / 3600 for timeduration in timedurations]

# divide each distance by its respective time
speeds = [float(distance) / hour for distance, hour in zip(distances, hours)]


for speed in speeds:
    print(str(speed) + " mph")
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

You could use an auxiliary method to convert the times to hours and then create a well named list for each sub step in the conversion:

def get_hours(time_duration):
  h, m, s = time_duration.split(':')
  return float(h) + float(m) / 60 + float(s) / 3600

KM_TO_MI_CONVERSION_FACTOR = 1.609344

time_duration = ['0:07:11', '0:15:16', '0:18:17', '0:23:15']
km_distances = ['0.6', '0.4', '1.3', '1.7']
mi_distances = [float(x)/KM_TO_MI_CONVERSION_FACTOR for x in km_distances]
time_in_hours = [get_hours(x) for x in time_duration]
mi_per_hour = [round(x/y, 7) for x, y in zip(mi_distances, time_in_hours)]
km_per_hour = [round(float(x)/y, 7) for x, y in zip(km_distances, time_in_hours)]
print(mi_per_hour) #[3.1140644, 0.9768281, 2.6508817, 2.7260156]
print(km_per_hour) #[5.0116009, 1.5720524, 4.2661805, 4.3870968]

You can use enumerate keyword for this task to store current "index" for time calculations or position in your lists, like this:

timeduration = ['0:07:11', '0:15:16', '0:18:17', '0:23:15']
distances = ['0.6', '0.4', '1.3', '1.7']
speed = []

for i, t in enumerate(timeduration):
    t = [float(hms)/60**power for power, hms in enumerate(t.split(':'))]
    d = float(distances[i])
    v = d / sum(t)
    speed.append(v)

print(speed)

If you are happy to use a 3rd party library, you can use vectorised operations via Pandas . This solution should be efficient for larger inputs.

import pandas as pd

timeduration = ['0:07:11', '0:15:16', '0:18:17', '0:23:15']
distances = ['0.6', '0.4', '1.3', '1.7']

times = pd.to_timedelta(timeduration)  # convert strings to timedeltas
dists = pd.to_numeric(distances)       # convert strings to floats

miles_per_km = 0.621371

res = dists / (times / pd.Timedelta('1 hour')) * miles_per_km

# Float64Index([3.11406348028, 0.976827772926, 2.65088083865, 2.72601470968],
#              dtype='float64')

Solution with the python brackets:

timeduration = ['0:07:11', '0:15:16', '0:18:17', '0:23:15']
distances = ['0.6', '0.4', '1.3', '1.7']

temp = [ii.split(':') for ii in timeduration]
timeduration = [(int(ii[0])*3600+int(ii[1])*60+int(ii[2]))/3600 for ii in temp]
distances = [float(ii) for ii in distances]

kmtomile = 0.621371

speed = [kmtomile*distances[ii]/timeduration[ii] for ii in range(len(distances))]

Value of speed :

[3.1140634802784226, 0.9768277729257643, 2.650880838650866, 2.726014709677419]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM