I have a list of six-hour time slots ['00:00','06:00','12:00','18:00']
. I need to build a function that returns one of the time slots if the current time falls under:
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.
Here is the code:
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.
Can someone tell me what I need to do in order to solve the problem?