【发布时间】:2020-11-16 22:57:06
【问题描述】:
让我们有两个变量:
- 开始日期
- days_of_months::list(例如:[1,2,10,31])
输出:一个日期>=start_date which ("%d") = 列表成员之一。 输出日期必须尽可能接近 start_date。
示例
开始日期:2020-11-17
days_of_month:[5,10,20]
输出:2020-11-20
开始日期:2020-11-17
days_of_month:[5,10]
输出:2020-12-05
开始日期:2020-12-17
days_of_month:[5,10]
输出:2021-01-05
开始日期:2021-02-17
days_of_month:[5,10,31]
输出:2021-03-05
开始日期:2021-04-17
days_of_month:[31]
输出:2021-05-31(2021年4月还没有31天)
建议答案:
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))
上面的代码似乎按预期工作。
【问题讨论】: