1

I have a list of dates. And given a specific input date, want to find the next date in the list. Example is:

my_dates_list = ['2019-01-31', '2019-02-28', '2019-03-31', '2019-04-30', '2019-05-31', '2019-06-30'].
InputDate = '2019-03-31'

the output should be '2019-04-30' because it is the next date of the InputDate found in the list.

Another example: if InputDate is '2019-03-31', the output should be '2019-04-30'.

mhhabib
  • 2,975
  • 1
  • 15
  • 29
soiledboy
  • 19
  • 5

2 Answers2

3

Joe's answer works, but because your dates are zfilled and are ordered year to day, you don't need a parser. Here's a two-line solution.

my_dates_list = ['2019-01-31', '2019-07-13', '2019-02-28', '2019-03-31',
                 '2019-04-30', '2019-05-31', '2019-06-30']
input_date = '2019-03-31'

results = [d for d in sorted(my_dates_list) if d > input_date]
output = results[0] if results else None
print(output)

result = '2019-04-30'

Michael Lee
  • 698
  • 5
  • 13
0

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')
Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33