Let's have two variables:
- start_date
- days_of_months::list (example: [1,2,10,31])
Output: a date>=start_date which ("%d") = one of the list members. The output date must be as close as possible to the start_date.
Examples
start_date: 2020-11-17
days_of_month: [5,10,20]
output: 2020-11-20
start_date: 2020-11-17
days_of_month: [5,10]
output: 2020-12-05
start_date: 2020-12-17
days_of_month: [5,10]
output: 2021-01-05
start_date: 2021-02-17
days_of_month: [5,10,31]
output: 2021-03-05
start_date: 2021-04-17
days_of_month: [31]
output: 2021-05-31 (April of 2021 has not 31 days)
Suggested answer:
from calendar import monthrange
from datetime import datetime
from datetime import timedelta
def find_condition_date(start_date,days_month_list):
year = int(start_date.strftime("%Y"))
month = int(start_date.strftime("%m"))
day = int(start_date.strftime("%d"))
current_month_days = monthrange(year, month)[1]
if(day in days_month_list):
return start_date
else:
for day_of_month_selected in days_month_list:
if(day_of_month_selected>day and day_of_month_selected<=current_month_days):
add_days = day_of_month_selected - day
start_date = start_date + timedelta(days=add_days)
return start_date
selected_index = 0
total_days_selected = len(days_month_list)
if(month==12):
year+=1
month = 1
else:
month +=1
current_month_days = monthrange(year,month)[1]
while(True):
if(selected_index<total_days_selected):
first_day_of_month_selected = int(days_month_list[selected_index])
if(current_month_days>=first_day_of_month_selected):
return datetime(year,month,first_day_of_month_selected).date()
else:
selected_index = 0
if(month==12):
year+=1
month = 1
else:
month +=1
current_month_days = monthrange(year,month)[1]
else:
selected_index = 0
if(month==12):
year+=1
month = 1
else:
month +=1
current_month_days = monthrange(year,month)[1]
#Example 1
start_date = datetime(2020,11,17)
days_month_list = [5,10,20]
print(find_condition_date(start_date,days_month_list))
#Example 2
start_date = datetime(2020,11,17)
days_month_list = [5,10]
print(find_condition_date(start_date,days_month_list))
#Example 3
start_date = datetime(2020,12,17)
days_month_list = [5,10]
print(find_condition_date(start_date,days_month_list))
#Example 4
start_date = datetime(2021,2,17)
days_month_list = [5,10,31]
print(find_condition_date(start_date,days_month_list))
#Example 5
start_date = datetime(2021,4,17)
days_month_list = [31]
print(find_condition_date(start_date,days_month_list))
The above code seems to work as expected.