如何检查字典中是否存在某个日期,如果没有,则返回最接近的日期?

问题描述 投票:0回答:2

我有一个带有许多排序日期的词典。我怎么能在Python中编写一个循环来检查某个日期是否在dictionnary中,如果没有,它会返回最接近的日期?我希望它工作,如果在将一天减去日期之后再次检查它是否现在存在于字典中,如果不存在,它会再次减去直到找到现有日期为止。

提前致谢

from datetime import timedelta

def function(date):
    if date not in dictio:
        date -= timedelta(days=1)
    return date
python loops datetime
2个回答
0
投票

我已经做了一个递归函数来解决你的问题:

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)))

0
投票

您正在寻找的可能是一个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)
© www.soinside.com 2019 - 2024. All rights reserved.