📜  Python程序检查日期范围内的日期

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

Python程序检查日期范围内的日期

给定一个日期列表和日期范围,任务是编写一个Python程序来检查给定范围内的列表中是否存在任何日期。

例子:

方法一:使用循环

在这里,对于每个元素,我们使用条件检查是否有任何日期落在范围内,如果找到,则返回 true。

Python3
# Python3 code to demonstrate working of
# Test for date in date range
# Using loop
from datetime import datetime
  
# initializing list
test_list = [datetime(2019, 12, 30), datetime(2018, 4, 4), 
             datetime(2016, 12, 21), datetime(2021, 2, 2), 
             datetime(2020, 2, 3), datetime(2017, 1, 1)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing date ranges
date_strt, date_end = datetime(2019, 3, 14), datetime(2020, 1, 4)
  
res = False
for ele in test_list:
  
    # checking for date in range
    if ele >= date_strt and ele <= date_end:
        res = True
  
# printing result
print("Does list contain any date in range : " + str(res))


Python3
# Python3 code to demonstrate working of
# Test for date in date range
# Using any()
from datetime import datetime
  
# initializing list
test_list = [datetime(2019, 12, 30), datetime(2018, 4, 4),
             datetime(2016, 12, 21), datetime(2021, 2, 2), 
             datetime(2020, 2, 3), datetime(2017, 1, 1)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing date ranges
date_strt, date_end = datetime(2019, 3, 14), datetime(2020, 1, 4)
  
# any() for checking presence of any date in range
res = any(ele >= date_strt and ele <= date_end for ele in test_list)
  
# printing result
print("Does list contain any date in range : " + str(res))


输出:

方法 2:使用any()

与上述方法类似,唯一的区别是 any() 用于检查范围内是否存在任何日期。

蟒蛇3

# Python3 code to demonstrate working of
# Test for date in date range
# Using any()
from datetime import datetime
  
# initializing list
test_list = [datetime(2019, 12, 30), datetime(2018, 4, 4),
             datetime(2016, 12, 21), datetime(2021, 2, 2), 
             datetime(2020, 2, 3), datetime(2017, 1, 1)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing date ranges
date_strt, date_end = datetime(2019, 3, 14), datetime(2020, 1, 4)
  
# any() for checking presence of any date in range
res = any(ele >= date_strt and ele <= date_end for ele in test_list)
  
# printing result
print("Does list contain any date in range : " + str(res))

输出: