我有一张六小时的时段表。我需要构建一个函数,如果当前时间在以下情况下,该函数将返回其中一个时隙:
From 00:00 - to 05:59 -> # should return -> 00:00
From 06:00 - to 11:59 -> # should return -> 06:00
From 12:00 - to 17:59 -> # should return -> 12:00
From 18:00 - to 23:59 -> # should return -> 18:00
I asked for a similar function that returns the closest and furthest time to the current time at: https://stackoverflow.com/a/68240328/14712981. I used the same code from @RJ Adriaansen for my current question but it didn't work as expected.
代码如下:
current_time = '10:00'
time = ['00:00','06:00','12:00','18:00']
def get_time(time):
return datetime.strptime(time, '%H:%M')
current_time = get_time(current_time)
time = [get_time(i) for i in time]
print(min(time,key=lambda x : abs(current_time-x)).strftime('%H:%M'))
# It returns 12:00, while it should return 06:00 in my case.
有人能告诉我解决这个问题需要做什么吗
这实际上是一个字符串操作问题,而不是日期/时间问题(例如,
datetime
不需要参与)这里有一个函数(包括测试工具),它将执行您需要的操作(注意,我已将您的
6:00
更改为06:00
,因此它与问题的其余部分匹配,并且与其他时间的格式相同,特别是00:00
,它指示前导零):输出显示各种输入的值:
它的工作方式是为小于所需项的每个插槽构造一个
1
值列表,然后对该列表求和这将为您提供一个反向位置(较早时间的较高总和),您可以将其操纵到索引中。然后,该索引用于返回插槽的正确时间
abs(current_time)
忽略x
是在current_time
之前还是之后,因此它返回最近的时隙,而不是从current_time
之前开始的最近的时隙如果时间段已排序,只需循环,直到找到一个小于或等于当前时间的时间段
如果它们尚未排序,请使用
for slot in sorted(time):
相关问题 更多 >
编程相关推荐