Josh Kidd
Josh Kidd

Reputation: 870

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

Upvotes: 0

Views: 2626

Answers (3)

Mohammad Athar
Mohammad Athar

Reputation: 1980

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

Upvotes: 0

nigel222
nigel222

Reputation: 8202

Use distance / ( time.total_seconds() / 3600.0 ) (assuming distance is already in km).

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

First of all, you have to initialize your timedelta with the proper arguments:

time = timedelta(days=0,hours=0,minutes=1,seconds=4)

timedelta has a method total_seconds() so you fetch:

total_seconds = time.total_seconds()

By dividing by 3600, you get the number of hours:

hours = total_seconds/3600.0

(in it is sufficient to divide by 3600 (int)).

and next you calculate the speed by dividing the distance (km) by the time (hours):

speed = distance/hours # unit: kmph

Upvotes: 0

Related Questions