📜  Python - 在日期列表中查找连续日期

📅  最后修改于: 2022-05-13 01:55:18.243000             🧑  作者: Mango

Python - 在日期列表中查找连续日期

给定一个日期列表,任务是编写一个Python程序来检查列表中的所有日期是否连续。

方法#1:使用 days() +循环

在这种情况下,我们通过使用 days() 检查与前一个日期的天数差异来检查连续日期。所有日期的迭代都是使用循环完成的。

Python3
# Python3 code to demonstrate working of
# Test if dates are consecutive
# Using days() + loop
from datetime import datetime, timedelta
  
# initializing list
test_list = [datetime(2019, 12, 30), datetime(2019, 12, 31), 
             datetime(2020, 1, 1), datetime(2020, 1, 2),
             datetime(2020, 1, 3), datetime(2020, 1, 4)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# using loop for iterating all elements
res = True
for idx in range(1, len(test_list)):
  
    # checking for 1 day time difference
    if (test_list[idx] - test_list[idx - 1]).days != 1:
        res = False
        break
  
# printing result
print("Are dates consecutive : " + str(res))


Python3
# Python3 code to demonstrate working of
# Test if dates are consecutive
# Using all() + days()
from datetime import datetime, timedelta
  
# initializing list
test_list = [datetime(2019, 12, 30), datetime(2019, 12, 31), 
             datetime(2020, 1, 1), datetime(2020, 1, 2),
             datetime(2020, 1, 3), datetime(2020, 1, 4)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# using loop for iterating all elements
res = all((test_list[idx] - test_list[idx - 1]).days ==
          1 for idx in range(1, len(test_list)))
  
# printing result
print("Are dates consecutive : " + str(res))


输出:

方法#2:使用all() + days()

与上述方法类似,这里唯一的区别是 all() 用于检查每天的连续性以获得更紧凑的解决方案。

蟒蛇3

# Python3 code to demonstrate working of
# Test if dates are consecutive
# Using all() + days()
from datetime import datetime, timedelta
  
# initializing list
test_list = [datetime(2019, 12, 30), datetime(2019, 12, 31), 
             datetime(2020, 1, 1), datetime(2020, 1, 2),
             datetime(2020, 1, 3), datetime(2020, 1, 4)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# using loop for iterating all elements
res = all((test_list[idx] - test_list[idx - 1]).days ==
          1 for idx in range(1, len(test_list)))
  
# printing result
print("Are dates consecutive : " + str(res))

输出: