为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

尚方宝剑之说 2023-08-08 16:48:01
我有 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 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))打印'2020, 9, 24'secondary_date 而不是'2020, 9, 25'. 我缺少什么?
查看完整描述

1 回答

?
慕容3067478

TA贡献1773条经验 获得超3个赞

您需要更新两者的范围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 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))


查看完整回答
反对 回复 2023-08-08
  • 1 回答
  • 0 关注
  • 106 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信