如何根据开始和结束获取for循环中的日期列表?

我想使用 for 循环获取开始日期和结束日期之间范围的唯一 yyyy-mm-01 列表。这是我的代码:


import datetime

from datetime import timedelta, date


start=date(2017,4,1)

end=(datetime.date.today().replace(day=1)) - datetime.timedelta(days=1) #last completed month


def daterange(start, end):

    for n in range(int((end - start).days)):

        yield start + timedelta(n)


for single_date in daterange(start, end):

    myset = str(single_date.strftime("%Y-%m-01"))

    print(myset)


The issue is that my result looks like this:

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-04-01

2017-05-01

我尝试添加 set() 但它仍然显示冗余日期。我该如何解决?


白衣非少年
浏览 136回答 4
4回答

12345678_0001

dates = set()for single_date in daterange(start, end):    dates.add(single_date.strftime("%Y-%m-01"))print(sorted(list(dates)))

梦里花落0921

import datetimefrom datetime import timedelta, datefrom dateutil.relativedelta import relativedeltastart=date(2017,4,1)end=(datetime.date.today().replace(day=1)) - datetime.timedelta(days=1) #last completed monthlst = []current_date = startwhile current_date < end:&nbsp; &nbsp; current_date = current_date.replace(day=1) + relativedelta(months=1)&nbsp; &nbsp; lst.append(current_date)print(lst)

牧羊人nacy

问题是你实际上并没有使用你的集合来检查你之前是否见过一个日期:myset = set()for single_date in daterange(start, end):&nbsp; &nbsp; mydate = str(single_date.strftime("%Y-%m-01"))&nbsp; &nbsp; if mydate not in myset:&nbsp; &nbsp; &nbsp; &nbsp; print(mydate)&nbsp; &nbsp; &nbsp; &nbsp; myset.add(mydate)

慕斯709654

我强烈建议您使用dateutils模块来获取这样的重复日期。您可以使用cmd安装它pip install python-dateutil>>> from dateutil.rrule import rrule, MONTHLY>>>>>> start=date(2017,4,1)>>> end=(datetime.date.today().replace(day=1)) - datetime.timedelta(days=1)>>> res = list(d.strftime("%Y-%m-%d") for d in rrule(dtstart=start, until=end, freq=MONTHLY))>>> pprint(res)['2017-04-01',&nbsp;'2017-05-01',&nbsp;'2017-06-01',&nbsp;'2017-07-01',&nbsp;'2017-08-01',&nbsp;'2017-09-01',&nbsp;'2017-10-01',&nbsp;'2017-11-01',&nbsp;'2017-12-01',&nbsp;'2018-01-01',&nbsp;'2018-02-01',&nbsp;'2018-03-01',&nbsp;'2018-04-01',&nbsp;'2018-05-01',&nbsp;'2018-06-01',&nbsp;'2018-07-01',&nbsp;'2018-08-01',&nbsp;'2018-09-01',&nbsp;'2018-10-01',&nbsp;'2018-11-01',&nbsp;'2018-12-01',&nbsp;'2019-01-01',&nbsp;'2019-02-01',&nbsp;'2019-03-01',&nbsp;'2019-04-01',&nbsp;'2019-05-01',&nbsp;'2019-06-01',&nbsp;'2019-07-01',&nbsp;'2019-08-01',&nbsp;'2019-09-01',&nbsp;'2019-10-01',&nbsp;'2019-11-01',&nbsp;'2019-12-01',&nbsp;'2020-01-01',&nbsp;'2020-02-01',&nbsp;'2020-03-01',&nbsp;'2020-04-01',&nbsp;'2020-05-01',&nbsp;'2020-06-01',&nbsp;'2020-07-01']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python