You can convert the string data into datetime using datetime.strptime
, then sort them in ascending order, then check if the value is greater than the input value. If you have a value, then you can return it using datetime.strftime
. For more details on using datetime, please refer to this Stack Overflow thread Converting Strings into datetime. You can also see additional inputs in this link on Converting between datetime and strings
Here's how I would do it:
from datetime import datetime
my_dates_list = ['2019-01-31', '2019-02-28', '2019-03-31', '2019-04-30', '2019-05-31', '2019-06-30']
my_sorted_dates = [datetime.strptime(i,'%Y-%m-%d') for i in my_dates_list]
my_sorted_dates.sort()
def find_next(x):
y = [a for a in my_sorted_dates if a > datetime.strptime(x,'%Y-%m-%d')]
return y[0].strftime('%Y-%m-%d') if y else None
print (find_next('2019-03-12'))
print (find_next('2019-03-31'))
print (find_next('2019-04-30'))
print (find_next('2019-08-30'))
Results will be:
2019-03-31 # for find_next('2019-03-12')
2019-04-30 # for find_next('2019-03-31')
2019-05-31 # for find_next('2019-04-30')
None # for find_next('2019-08-30')