首页 > 解决方案 > 如何判断列表中的两个日期在 Python 中是否连续?

问题描述

我已按顺序对字符串日期列表进行了排序

sorteddates =['2017-04-26', '2017-05-05', '2017-05-10', '2017-05-11', '2017-05-16']

我尝试使用它按连续日期对代码进行排序,因为我很难理解。我想看看哪两个日期是连续的。只有两个日期。

dates = [datetime.strptime(d, "%Y-%m-%d") for d in sorteddates]
date_ints = set([d.toordinal() for d in dates])

标签: pythonpython-3.x

解决方案


  1. 将列表从 str 转换为datetime-- 仍然按排序顺序。
  2. 遍历列表;对于每个项目,检查下一个项目是否在一天后 -datetime也有timedelta值。

一些代码:

# Convert list to datetime; you've shown you can do that part.
enter code here
one_day = datetime.timedelta(days=1)
for today, tomorrow in zip(sorteddates, sorteddates[1:]):
    if today + one_day == tomorrow:
        print ("SUCCESS")

推荐阅读