gpt4 book ai didi

Python:如何从日期列表中计算日期范围?

转载 作者:太空宇宙 更新时间:2023-11-03 13:23:12 25 4
gpt4 key购买 nike

我有一个日期列表,例如:

['2011-02-27', '2011-02-28', '2011-03-01', '2011-04-12', '2011-04-13', '2011-06-08']

如何找到这些日期中包含的连续日期范围?在上面的例子中,范围应该是:

[{"start_date": '2011-02-27', "end_date": '2011-03-01'},
{"start_date": '2011-04-12', "end_date": '2011-04-13'},
{"start_date": '2011-06-08', "end_date": '2011-06-08'}
]

谢谢。

最佳答案

这行得通,但我对此并不满意,将致力于更清洁的解决方案并编辑答案。完成,这是一个干净、有效的解决方案:

import datetime
import pprint

def parse(date):
return datetime.date(*[int(i) for i in date.split('-')])

def get_ranges(dates):
while dates:
end = 1
try:
while dates[end] - dates[end - 1] == datetime.timedelta(days=1):
end += 1
except IndexError:
pass

yield {
'start-date': dates[0],
'end-date': dates[end-1]
}
dates = dates[end:]

dates = [
'2011-02-27', '2011-02-28', '2011-03-01',
'2011-04-12', '2011-04-13',
'2011-06-08'
]

# Parse each date and convert it to a date object. Also ensure the dates
# are sorted, you can remove 'sorted' if you don't need it
dates = sorted([parse(d) for d in dates])

pprint.pprint(list(get_ranges(dates)))

和相关输出:

[{'end-date': datetime.date(2011, 3, 1),
'start-date': datetime.date(2011, 2, 27)},
{'end-date': datetime.date(2011, 4, 13),
'start-date': datetime.date(2011, 4, 12)},
{'end-date': datetime.date(2011, 6, 8),
'start-date': datetime.date(2011, 6, 8)}]

关于Python:如何从日期列表中计算日期范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6934128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com