我只想将当前时间(仅在小时和分钟内)与给定的时间列表进行比较,并从列表中获取最接近的时间(或列表中以前可用的时间)值。
list_of_times = ['5:00:00 AM', '5:10:00 AM', '5:20:00 AM', '5:30:00 AM', '5:40:00 AM', '5:50:00 AM', '6:00:00 AM', '6:05:00 AM', '6:10:00 AM', '6:15:00 AM', '6:25:00 AM']
current_time = '6:02:00 AM'
我想要的是什么:
def get_closes_time(current_time , list_of_times ):
# some logic here
return closest_time # In this case I want 6:00:00 AM
假设我的列表是按时间排序的,那么最快的方法是什么呢?
答案 0 :(得分:1)
在数组中二进制搜索current_time
。这是一个简单的部分。
更复杂的部分是在您的小时之间定义一些比较逻辑,以确定您的二进制搜索算法是否应该继续搜索剩余数组的左侧部分或右侧部分。
from datetime import datetime
list_of_times = ['5:00:00 AM', '5:10:00 AM', '5:20:00 AM', '5:30:00 AM', '5:40:00 AM', '5:50:00 AM', '6:00:00 AM', '6:05:00 AM', '6:10:00 AM', '6:15:00 AM', '6:25:00 AM']
current_time = '6:02:00 AM'
current = datetime.strptime(current_time, '%I:%M:%S %p')
def getClosestTime(current, list_of_times, left, right):
if right < 0:
return "Empty array"
if right == 0:
return list_of_times[right]
if right - 1 == left:
leftTime = datetime.strptime(list_of_times[left], '%I:%M:%S %p')
rightTime = datetime.strptime(list_of_times[right], '%I:%M:%S %p')
if leftTime < rightTime:
return leftTime
else:
return rightTime
mid = int((left + right) / 2)
midTime = datetime.strptime(list_of_times[mid], '%I:%M:%S %p')
if current < midTime:
return getClosestTime(current, list_of_times, left, mid - 1)
if current > midTime:
return getClosestTime(current, list_of_times, mid + 1, right)
这将保证O(log(n))复杂度时间和O(n)空间复杂度。
getClosestTime(currentTime, listOfTimes, 0, len(listOfTimes) - 1) //that's how you call it
答案 1 :(得分:-1)
我不确定这是否是最快的
import datetime
list_of_times = ['5:00:00 AM', '5:10:00 AM', '5:20:00 AM', '5:30:00 AM', '5:40:00 AM', '5:50:00 AM', '6:00:00 AM', '6:05:00 AM', '6:10:00 AM', '6:15:00 AM', '6:25:00 AM']
current_time = '6:02:00 AM'
format = '%I:%M:%S %p'
current_time = datetime.datetime.strptime(current_time, format)
print(sorted([[i,abs(current_time - datetime.datetime.strptime(i, format))] for i in list_of_times], key=lambda x: x[1])[0][0])
以上将于上午6:00:00结束。
答案 2 :(得分:-1)
试试这个
from datetime import datetime
def get_closes_time(current_time , list_of_times ):
closest_time=list_of_times[0]
FMT = '%I:%M:%S %p'
for each in list_of_times:
dif_1= abs(datetime.strptime(each, FMT) - datetime.strptime(current_time, FMT))
dif_2= abs(datetime.strptime(closest_time, FMT) - datetime.strptime(current_time, FMT))
if dif_1<dif_2:
closest_time=each
return closest_time