我正在尝试学习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)
答案 0 :(得分:1)
您的问题是回路控制错误
for rider in riders:
if rider[5] >= "05:00:00" and rider[5] <= "11:30:00":
ans.insert(len(ans), rider)
return ans;
您检查一名骑手并返回,无论比赛结果如何。试试这个:
def getRiderDate(riders):
ans = []
for rider in riders:
if rider[5] >= "05:00:00" and rider[5] <= "11:30:00":
ans.append(rider)
return ans;
return
会在循环后 而不是内部循环。
输出:
[['rider_1879', 37.775222, 122.47109, 37.80808, -122.410002, '06:25:08', '$22.25', 'UberX']]
答案 1 :(得分:0)
我将使用datetime模块,主要是时间。还有以前的答案指出了什么(循环内返回ans等)
import datetime
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 = []
t1 = datetime.time(hour=5)
t2 = datetime.time(hour=11, minute=30)
for rider in riders:
t = datetime.datetime.strptime(rider[5], '%H:%M:%S').time()
if t1 <= t <= t2: # using chained comparison
ans.insert(len(ans), rider)
return ans
print(getRiderDate(riders))