2 回答

TA貢獻1862條經驗 獲得超6個贊
我做了一個遞歸函數來解決你的問題:
import datetime
def find_date(date, date_dict):
if date not in date_dict.keys():
return find_date(date-datetime.timedelta(days=1), date_dict)
else:
return date
我不知道你的字典的內容是什么,但下面的例子應該向你展示它是如何工作的:
import numpy as np
# creates a casual dates dictionary
months = np.random.randint(3,5,20)
days = np.random.randint(1,30,20)
dates = {
datetime.date(2019,m,d): '{}_{:02}_{:02}'.format(2019,m,d)
for m,d in zip(months,days)}
# select the date to find
target_date = datetime.date(2019, np.random.randint(3,5), np.random.randint(1,30))
# print the result
print("The date I wanted: {}".format(target_date))
print("The date I got: {}".format(find_date(target_date, dates)))

TA貢獻1869條經驗 獲得超4個贊
您正在尋找的可能是一個 while 循環,但要小心,因為如果它找不到日期,它將運行到無限。也許您想定義一個嘗試限制,直到腳本放棄?
from datetime import timedelta, date
d1 = {
date(2019, 4, 1): None
}
def function(date, dictio):
while date not in dictio:
date -= timedelta(days=1)
return date
res_date = function(date.today(), d1)
print(res_date)
添加回答
舉報