如何有效比较datetime对象

2024-04-24 14:48:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本大约有15k条记录的字典,格式如下:

sample = {0: {'Schedule': ['2017-05-11', '2019-04-30', '2018-10-13', '2019-05-31', '', '']},
      1: {'Schedule': ['2017-05-09', '2019-05-31', '', '', '2018-10-13', '2019-05-31']},
      2: {'Schedule': ['2017-05-02', '2020-02-29', '', '', '2018-10-12', '2020-02-29']}}

现在我必须用两个datetime对象比较'Schedule'中的第一、第三和第五个日期,看看是否在这个范围内。我正在做下面的,但结果是相当缓慢,需要大约20秒。有人能提出一种更有效的搜索方法吗?你知道吗

完整样本代码:

from datetime import datetime

sample = {0: {'Schedule': ['2017-05-11', '2019-04-30', '2018-10-13', '2019-05-31', '', '']},
          1: {'Schedule': ['2017-05-09', '2019-05-31', '', '', '2018-10-13', '2019-05-31']},
          2: {'Schedule': ['2017-05-02', '2020-02-29', '', '', '2018-10-12', '2020-02-29']}}

start_date = datetime.date(datetime.strptime("2018-10-12","%Y-%m-%d"))
end_date = datetime.date(datetime.strptime("2018-10-16","%Y-%m-%d"))

for k,v in sample.items():
    earliest = [dt for dt in [v["Schedule"][0],v["Schedule"][2],v["Schedule"][4]] if dt] #only need to check these 3 starting dates
    def check_earliest(_list):  #check if any date meets search criteria
        for i in _list:
            if start_date <= datetime.date(datetime.strptime(i, "%Y-%m-%d")) <= end_date:
                return True
    if check_earliest(earliest):
        print ("Do something here...")

Tags: sampleinfordatetimedateifcheck记录
1条回答
网友
1楼 · 发布于 2024-04-24 14:48:16

不要使用datetime对象,从字典中的datetime对象开始,这样就不必仅为进行比较而转换它们。你知道吗

您不必使用datetime对象,因为您的日期是按YYYY-MM-DD顺序的ISO 8601 definition。这样的日期,如字符串,在字典中以正确的日期顺序进行比较。你知道吗

所以呢

start_date = "2018-10-12"
end_date = "2018-10-16"

for k,v in sample.items():
    sched = v['Schedule']
    earliest = [dt for dt in (sched[0], sched[2], sched[4]) if dt]
    def check_earliest(l):
        for i in l:
            if start_date <= i <= end_date:
                return True
    if check_earliest(earliest):
        print("Do something here...")

已经很好了。你知道吗

我会在这里使用any()函数来测试您的日期,而不是定义您自己的函数:

for k, v in sample.items():
    sched = v['Schedule']
    if any(sched[i] and start_date <= sched[i] <= end_date for i in (0, 2, 4)):
        print ("Do something here...")

对于代码的其他区域来说,将字符串解析成date()实例一次可能会很有用,而不是每次需要datetime.date()对象时都使用字符串并进行转换。对于这里的这个比较,其实并不需要。你知道吗

相关问题 更多 >