返回包含给定时间(当前时间)的时隙

2024-05-18 18:22:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张六小时的时段表。我需要构建一个函数,如果当前时间在以下情况下,该函数将返回其中一个时隙:

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.

有人能告诉我解决这个问题需要做什么吗


Tags: theto函数infromforgetreturn
2条回答

这实际上是一个字符串操作问题,而不是日期/时间问题(例如,datetime不需要参与)

这里有一个函数(包括测试工具),它将执行您需要的操作(注意,我已将您的6:00更改为06:00,因此它与问题的其余部分匹配,并且与其他时间的格式相同,特别是00:00,它指示前导零):

def which_slot(slots, value):
    if slots[0] != "00:00":
        raise Exception("first slot must be 00:00")
    return slots[len(slots) - sum([1 for item in slots[1:] if value < item]) - 1]

slots = ["00:00", "06:00", "12:00", "18:00"]

for test in ["00:00", "00:01"]:
    print(f"{test} : {which_slot(slots, test)}")

for hour in [3, 6, 12, 18, 21]:
    for test in [f"{hour-1:02}:59", f"{hour:02}:00", f"{hour:02}:01"]:
        print(f"{test} : {which_slot(slots, test)}")

for test in ["23:59"]:
    print(f"{test} : {which_slot(slots, test)}")

输出显示各种输入的值:

00:00 : 00:00
00:01 : 00:00
02:59 : 00:00
03:00 : 00:00
03:01 : 00:00
05:59 : 00:00
06:00 : 06:00
06:01 : 06:00
11:59 : 06:00
12:00 : 12:00
12:01 : 12:00
17:59 : 12:00
18:00 : 18:00
18:01 : 18:00
20:59 : 18:00
21:00 : 18:00
21:01 : 18:00
23:59 : 18:00

它的工作方式是为小于所需项的每个插槽构造一个1值列表,然后对该列表求和

这将为您提供一个反向位置(较早时间的较高总和),您可以将其操纵到索引中。然后,该索引用于返回插槽的正确时间

abs(current_time)忽略x是在current_time之前还是之后,因此它返回最近的时隙,而不是从current_time之前开始的最近的时隙

如果时间段已排序,只需循环,直到找到一个小于或等于当前时间的时间段

for slot in time:
    if slot <= current_time:
        print(slot.strftime('%H:%M'))
        break

如果它们尚未排序,请使用for slot in sorted(time):

相关问题 更多 >

    热门问题