我有 2 个日期时间对象的“范围”,由开始日期和停止日期定义。我想创建一个新的“范围”(开始和停止日期)来匹配前两个范围中的日期。
这是我尝试过的,但我的列表有问题:它似乎没有正确获取最后一个元素?
import datetime
#First date range is next week from monday to sunday:
next_week_day = datetime.datetime.now().date() + datetime.timedelta(days=7)
monday = next_week_day - datetime.timedelta(days=next_week_day.weekday())
sunday = monday + datetime.timedelta(days=7)
daterange = [monday + datetime.timedelta(days=x) for x in range(0, (sunday-monday).days)]
#Second daterange can be anything:
start = datetime.date(2020, 8, 2)
end = datetime.date(2020, 9, 25)
daterange_2 = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]
#then I create a list to add matching days to create the new range
date_list = []
for date in daterange:
for date_2 in daterange_2:
if date_2 == date:
date_list.append(date)
#and retrieve first and last day in list
first_date = date_list[0]
second_date = date_list[-1]
print(first_date, second_date)
print(type(first_date), type(second_date))
打印'2020, 9, 24'secondary_date 而不是'2020, 9, 25'. 我缺少什么?
慕容3067478
相关分类