2 回答

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超6個(gè)贊
我做了一個(gè)遞歸函數(shù)來解決你的問題:
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
我不知道你的字典的內(nèi)容是什么,但下面的例子應(yīng)該向你展示它是如何工作的:
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貢獻(xiàn)1869條經(jīng)驗(yàn) 獲得超4個(gè)贊
您正在尋找的可能是一個(gè) while 循環(huán),但要小心,因?yàn)槿绻也坏饺掌冢鼘⑦\(yùn)行到無限。也許您想定義一個(gè)嘗試限制,直到腳本放棄?
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)
添加回答
舉報(bào)