如果密钥的日期比今天的日期早N天,如何删除密钥?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如果密钥的日期比今天的日期早N天,如何删除密钥?相关的知识,希望对你有一定的参考价值。
如果密钥的日期比今天的日期早N天,如何删除密钥?
假设我要删除所有比当前日期(5-6-2020)早2天以上的密钥,
原件:
{
"player": {
"1-6-2020=>1591023427": "5.4M",
"2-6-2020=>1591125091": "5.21M",
"3-6-2020=>1590947416": "3.07M",
"4-6-2020=>1591023427": "2.95M",
"5-6-2020=>1591125091": "2.93M"
},
"player2": {
"1-6-2020=>1591023427": "5.4M",
"2-6-2020=>1591125091": "5.21M",
"3-6-2020=>1590947416": "3.07M",
"4-6-2020=>1591023427": "2.95M",
"5-6-2020=>1591125091": "2.93M"
}
}
所需结果:
{
"player": {
"3-6-2020=>1590947416": "3.07M",
"4-6-2020=>1591023427": "2.95M",
"5-6-2020=>1591125091": "2.93M"
},
"player2": {
"3-6-2020=>1590947416": "3.07M",
"4-6-2020=>1591023427": "2.95M",
"5-6-2020=>1591125091": "2.93M"
}
}
答案
从字典中提取日期(这里我使用datetime模块的格式来提取它)
- 过滤掉距离太远的日子(为此使用内置过滤器的python内置函数)
- 最终遍历玩家,并将此过滤器应用于玩家的字典
def filter_days_wrapper(n):
n_days_back = n
def filter_last_days(item):
current_date = date.today()
entry_date = datetime.strptime(item[0].split("=>")[0], '%d-%m-%Y')
return current_date.day - entry_date.day <= n_days_back and
current_date.month == entry_date.month and
current_date.year == entry_date.year
return filter_last_days
for player in players:
# used 2 for example, players is your dictionary
players[player] = dict(filter(filter_days_wrapper(2), players[player].items()))
以上是关于如果密钥的日期比今天的日期早N天,如何删除密钥?的主要内容,如果未能解决你的问题,请参考以下文章
如何创建过去的新 NSDate 对象,例如比另一个日期早 1 秒?