import numpy as np
a = ['2020-07-30', '2020-07-31', '2020-07-31', '2020-07-31', '2020-08-04', '2020-08-05', '2020-08-06', '2020-08-06', '2020-08-08', '2020-08-08']
b = '2020-07-27'
c = '2020-08-07'
d = '2020-08-02'
date = np.array(a, dtype=np.datetime64)
b1=a[np.argmin(np.abs(date-np.array(b,dtype=np.datetime64)))]
c1=a[np.argmin(np.abs(date-np.array(c,dtype=np.datetime64)))]
d1=a[np.argmin(np.abs(date-np.array(d,dtype=np.datetime64)))]
print (b,'->',b1)
print (c,'->',c1)
print (d,'->',d1)
2020-07-27 -> 2020-07-30
2020-08-07 -> 2020-08-06
2020-08-02 -> 2020-07-31
import datetime
def convert_string_to_date(string: str):
return datetime.datetime.strptime(string, '%Y-%m-%d').date()
def get_near_date(date, date_list):
date_list_desc = sorted(date_list, reverse=True)
first_try = [date > i for i in date_list_desc]
if True in first_try:
return date_list_desc[first_try.index(True)]
date_list_asc = sorted(date_list, reverse=False)
second_try = [date < i for i in date_list_asc]
if True in second_try:
return date_list_asc[second_try.index(True)]
a = ['2020-07-30', '2020-07-31', '2020-07-31', '2020-07-31', '2020-08-04', '2020-08-05', '2020-08-06', '2020-08-06', '2020-08-08', '2020-08-08']
a = [convert_string_to_date(i) for i in a]
b = convert_string_to_date('2020-07-27')
c = convert_string_to_date('2020-08-07')
print(get_near_date(b, a))
# 2020-07-30
print(get_near_date(c, a))
# 2020-08-06