Joshua Kidd Joshua Kidd - 1 year ago 75
Python Question

How to work out speed from distance as a float and time as a timedelta

If I have a distance in km float variable, and a timedelta variable of time, how can I work out speed in KM/H? I'm not sure how to change timedelta to hours as a float. An example would be:

distance = 0.966757
time = timedelta('0 days 00:01:04')


Having an output of around 54Kmh

Answer Source

convert that '1:04' to seconds

distance = 0.966757

time = datetime.timedelta(0,64)

distance/time.total_seconds()
>>0.015105578125

so you have speed in distance/second

per hour, you mulitply by 3600

3600*distance/time.total_seconds()
>>54.380081249999996

thanks for the 'total_seconds' tip guys. although , in this case i got

time.total_seconds() == time.seconds
>>True
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download