带有日期时间对象的列表的最后一个元素

我有 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'. 我缺少什么?


尚方宝剑之说
浏览 107回答 1
1回答

慕容3067478

您需要更新两者的范围daterange并daterange_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 + 1)]# 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 + 1)]# then I create a list to add matching days to create the new rangedate_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 listfirst_date = date_list[0]second_date = date_list[-1]print(first_date, second_date)print(type(first_date), type(second_date))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python