我想在日期字典中找到今天和下一个日期之间的天数。首先,我试图在字典中找到与当前日期最接近的日期。
current_date = datetime.today()
date_schedule = {
"1": "2019-7-29",
"2": "2019-8-27",
"3": "2019-9-27",
"4": "2019-10-28",
"5": "2019-11-27",
"6": "2019-12-27",
"7": "2020-1-27",
"8": "2020-2-27",
"9": "2020-3-27",
"10": "2020-4-27",
"11": "2020-5-27",
"12": "2020-6-29",
}
def days_till_payment(date_schedule, current_date):
days_left = min(date_schedule, key=lambda x: abs(x - current_date))
return days_left
但是,当我尝试运行它时,出现以下错误:
TypeError: unsupported operand type(s) for -: 'str' and 'datetime.datetime'
我非常感谢有人向我解释一下如何解决这个问题,并找出当前日期与字典中下一个最接近的日期之间有多少天。
编辑:如果它返回下一个即将到来的日期,而不是仅返回最近的日期(包括已经消失的日期),则此函数会更好。 我想输出下一个即将到来的日期,以及从今天起直到这个日期还有多少天。
答案 0 :(得分:2)
您需要将str
转换为datetime
对象。然后,
1。从date_schedules中查找“ mindate”,其中“ mindate”>“当前日期”
2。找到“头脑”与“当前日期”之间的天差
from datetime import datetime
date_schedule = {
"1": "2019-7-29",
"2": "2019-8-27",
"3": "2019-9-27",
"4": "2019-10-28",
"5": "2019-11-27",
"6": "2019-12-27",
"7": "2020-1-27",
"8": "2020-2-27",
"9": "2020-3-27",
"10": "2020-4-27",
"11": "2020-5-27",
"12": "2020-6-29",
}
def keyfunc(date):
return (date - datetime.today()).days
def days_till_payment(date_schedule, today):
dates = [datetime.strptime(v, '%Y-%m-%d') for v in date_schedule.values()]
search_dates = [date for date in dates if date >= today]
date = min(search_dates, key=keyfunc)
return (date - today).days, date.strftime('%Y-%m-%d')
>>> days, date = days_till_payment(date_schedule, datetime.today())
>>> days
19
>>> date
'2019-10-28'
答案 1 :(得分:1)
使用map, filter, min
的好处,日期仅转换一次,我们仅循环一次日期列表:
from datetime import datetime
date_schedule = {
"1": "2019-7-29",
"2": "2019-8-27",
"3": "2019-9-27",
"4": "2019-10-28",
"5": "2019-11-27",
"6": "2019-12-27",
"7": "2020-1-27",
"8": "2020-2-27",
"9": "2020-3-27",
"10": "2020-4-27",
"11": "2020-5-27",
"12": "2020-6-29",
}
def days_till_payment(date_schedule, current_date):
converted_data = map(lambda v: datetime.strptime(v, '%Y-%m-%d'), date_schedule.values() )
filtered_data = filter(lambda v: v >= current_date, converted_data)
min_date = min(filtered_data, key=lambda v: v - current_date)
return min_date.strftime('%Y-%m-%d')
current_date = datetime.today()
print(days_till_payment(date_schedule, current_date)) # 2019-10-28
答案 2 :(得分:0)
问题:我想输出下一个即将到来的日期以及从今天起直到该日期还有多少天。
注意:
dict
项必须按有序排列。 请改用collections.OrderedDict
!
def strptime(datestr):
return datetime.strptime(datestr, '%Y-%m-%d')
def days_till_payment(date_schedule, current_date):
for k, v in date_schedule.items():
v = strptime(v)
if v > current_date:
return v, (v - current_date).days
print(days_till_payment(date_schedule, datetime.now()))
>>> (datetime.datetime(2019, 10, 28, 0, 0), 19)