first of all let's create datetime.date
objects from strings using datetime.datetime.strptime
and datetime.datetime.date
methods since datetime.date
objects are ordered and easier to work with:
date_format = '%Y-%m-%d'
dates = [datetime.datetime.strptime(date_string,
date_format).date()
then let's filter out dates that take place in future (after today)
today = datetime.date.today()
future_dates = [date
for date in dates
if date >= today]
then we can simply find next closest date using min
next_closest_date = min(future_dates)
which gives us
>>>next_closest_date
2017-09-01
for given example
WARNING
If there is no dates going after today this will cause error like
ValueError: min() arg is an empty sequence
if it's ok then we can leave it, but if we don't want to get errors – we can specify default value for min
in case of empty sequence like
next_closest_date = min(future_dates, default=None)
Finally we can write a function as follows
import datetime
# `default` value is returned when there is no future date strings found
def get_next_closest_date(date_strings, date_format, default=None):
today = datetime.date.today()
dates = [datetime.datetime.strptime(date_string,
date_format).date()
for date_string in date_strings]
future_dates = [date
for date in dates
if date >= today]
return min(future_dates, default)
and use it like
scheduledatelist = ['2017-09-01', '2017-09-09', '2017-09-16', '2017-09-23',
'2017-09-30', '2017-10-07', '2017-10-14', '2017-10-21',
'2017-10-27', '2017-11-11', '2017-11-18', '2017-11-25']
next_closest_date = get_next_closest_date(date_strings=scheduledatelist,
date_format='%Y-%m-%d')
print(next_closest_date)