计算范围内的时间

我正在尝试学习 Python,但我陷入了日期/时间例程中,我需要查找 05:00 到 11:30 之间发生的数据,但无论我如何处理,我都会遇到错误。我认为我需要解码时间,进行数学运算,然后对时间进行编码。我确信这是一件简单的事情,但我似乎无法完成它。


例子:


riders = [

    ["rider_2391", 37_775370, -122.417571, 37_808601, -122.409807, "17:02:35", "$17.23", "UberX"],

    ["rider_1879", 37.775222, 122.47109, 37.808080, -122.410002, "06:25:08",  "$22.25", "UberX"],

    ["rider_98233", 37.784125, -122.471891, 37.763025, 122.478749, "11:48:55", "$6.28",  "Pool"]

]


def getRiderDate(riders):

    ans = []

    for rider in riders:

        if rider[5] >= "05:00:00" and rider[5] <= "11:30:00":

            ans.insert(len(ans), rider)

    return ans


print(getRiderDate(riders)


慕仙森
浏览 122回答 2
2回答

慕盖茨4494581

您的问题是循环控制错误:&nbsp; &nbsp;for rider in riders:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if rider[5] >= "05:00:00" and rider[5] <= "11:30:00":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ans.insert(len(ans), rider)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return ans;无论比赛结束,您检查一名骑手并返回。尝试这个:def getRiderDate(riders):&nbsp; &nbsp; ans = []&nbsp; &nbsp; for rider in riders:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if rider[5] >= "05:00:00" and rider[5] <= "11:30:00":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ans.append(rider)&nbsp; &nbsp; return ans;return在循环之后,而不是在里面。输出:[['rider_1879', 37.775222, 122.47109, 37.80808, -122.410002, '06:25:08', '$22.25', 'UberX']]

蝴蝶刀刀

我会使用 datetime 模块,主要是时间。还有以前的答案指出了什么(在循环内返回 ans 等)import datetimeriders = [["rider_2391", 37_775370, -122.417571, 37_808601, -122_409807, "17:02:35", "$17.23", "UberX"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["rider_1879", 37.775222, 122.47109, 37.808080, -122.410002, "06:25:08", "$22.25", "UberX"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["rider_98233", 37.784125, -122.471891, 37.763025, 122.478749, "11:48:55", "$6.28", "Pool"]]def getRiderDate(riders):&nbsp; &nbsp; ans = []&nbsp; &nbsp; t1 = datetime.time(hour=5)&nbsp; &nbsp; t2 = datetime.time(hour=11, minute=30)&nbsp; &nbsp; for rider in riders:&nbsp; &nbsp; &nbsp; &nbsp; t = datetime.datetime.strptime(rider[5], '%H:%M:%S').time()&nbsp; &nbsp; &nbsp; &nbsp; if t1 <= t <= t2:&nbsp; # using chained comparison&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ans.insert(len(ans), rider)&nbsp; &nbsp; return ansprint(getRiderDate(riders))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python