Skip to content Skip to sidebar Skip to footer

Finding The Closest And Furthest Value To A List Of Strings

I've got a list of times and a current time. I'm trying to find the closest and furthest time to the current time. I find it difficult to solve such tasks in strings. However, I ca

Solution 1:

When you convert the dates to a datetime object you can get the closest time with min(time,key=lambda x : abs(current_time-x)):

from datetime import datetime

current_time='09:00'time= ['09:30','11:50','11:55','11:55','12:00','12:10','12:15','12:25','12:35','12:50','12:55', '13:00']

def get_time(time):
  return datetime.strptime(time, '%H:%M')

current_time= get_time(current_time)
time= [get_time(i) for i intime]

print(min(time,key=lambda x : abs(current_time-x)).strftime('%H:%M'))

Solution 2:

Convert the hh:mm format to a single integer, for the current time and the list of times. Then iterate through the integers, and track the times using the original list of time.

def hhmm2int(t):
    hour_min = t.split(':')
    hours_as_minutes =int(hour_min[0]) *60
    minutes =int(hour_min[1])
    return hours_as_minutes + minutes


current_time='09:00'time= ['09:30', '11:50', '11:55', '11:55', '12:00', '12:10', '12:15', '12:25', '12:35', '12:50', '12:55', '13:00']

current_time= hhmm2int(current_time)
time_as_int = [hhmm2int(t) for t intime]

min_delta =float('inf')
max_delta =0
closest_time =''
furthest_time =''for i inrange(len(time_as_int)):
    delta =abs(time_as_int[i] -current_time)
    if delta < min_delta:
        min_delta = delta
        closest_time =time[i]
    if delta > max_delta:
        max_delta = delta
        furthest_time =time[i]

print(closest_time, furthest_time)

Solution 3:

A simple solution:

diff_time = lambda t: abs(int(current_time.replace(':', '')) \
                        - int(t.replace(':', '')))

From 00:00 (int: 0) to 23:59 (int: 2359), time is already lexicographical ordered and the order is maintained while converting to integer.

>>> min(time, key=diff_time)
'09:30'

>>> max(time, key=diff_time)
'13:00'

Post a Comment for "Finding The Closest And Furthest Value To A List Of Strings"