基于时间和距离的平均速度 - Python



我试图弄清楚如何解决我的问题,但它一直失败。

所以我目前有这个代码:

@staticmethod
def avg_speed():
# Speed = Distance ÷ Time
cur_time = datetime.datetime.now().replace(microsecond=0)
db_time_record = DB().start_time()
time_diff = cur_time - db_time_record
# print(str(time_diff).split(":"))
total_distance = DB().get_total_distance()
result = (total_distance / (float(time_diff.total_seconds()))) * 60
return round(result, 2)

但问题是,平均速度如此之高,速度不可能是正确的......现在,DB()记录有一个MySQL DATETIME object.

看起来像:datetime.now().strftime("%Y-%m-%d %H:%M:%S")(2017-08-22 15:28:19(

现在,正如代码中所述,我想要的是基于行进距离和时间的平均速度。距离以米为单位,时间应该以秒为单位?

我在这里做错了什么?

我没有可用于测试代码的MySQL数据库,但是如果您可以从数据库中读取start_time作为字符串,格式为"2017-08-22 15:28:19",那么以下示例显示了如何进行速度计算:

import datetime
# (simulate reading time from database as string)
time_string_from_db = "2017-08-22 15:28:19"
dbtime              = datetime.datetime.strptime(time_string_from_db, "%Y-%m-%d %H:%M:%S")
cur_time            = datetime.datetime.now().replace(microsecond=0)
print ("dbtime:      " + repr(dbtime))
print ("cur_time:    " + repr(cur_time))
elapsed = cur_time - dbtime
seconds = elapsed.total_seconds()
print ("elapsed:     " + repr(elapsed))
print ("seconds:     " + repr(seconds))
distance = 500
speed = distance / seconds
print ("speed:       " + repr(speed))

希望其中一些可能有用。

最新更新