4 回答
TA贡献1802条经验 获得超5个赞
dates = set()
for single_date in daterange(start, end):
dates.add(single_date.strftime("%Y-%m-01"))
print(sorted(list(dates)))
TA贡献1772条经验 获得超6个赞
import datetime
from datetime import timedelta, date
from dateutil.relativedelta import relativedelta
start=date(2017,4,1)
end=(datetime.date.today().replace(day=1)) - datetime.timedelta(days=1) #last completed month
lst = []
current_date = start
while current_date < end:
current_date = current_date.replace(day=1) + relativedelta(months=1)
lst.append(current_date)
print(lst)
TA贡献1862条经验 获得超7个赞
问题是你实际上并没有使用你的集合来检查你之前是否见过一个日期:
myset = set()
for single_date in daterange(start, end):
mydate = str(single_date.strftime("%Y-%m-01"))
if mydate not in myset:
print(mydate)
myset.add(mydate)
TA贡献1840条经验 获得超5个赞
我强烈建议您使用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',
'2017-05-01',
'2017-06-01',
'2017-07-01',
'2017-08-01',
'2017-09-01',
'2017-10-01',
'2017-11-01',
'2017-12-01',
'2018-01-01',
'2018-02-01',
'2018-03-01',
'2018-04-01',
'2018-05-01',
'2018-06-01',
'2018-07-01',
'2018-08-01',
'2018-09-01',
'2018-10-01',
'2018-11-01',
'2018-12-01',
'2019-01-01',
'2019-02-01',
'2019-03-01',
'2019-04-01',
'2019-05-01',
'2019-06-01',
'2019-07-01',
'2019-08-01',
'2019-09-01',
'2019-10-01',
'2019-11-01',
'2019-12-01',
'2020-01-01',
'2020-02-01',
'2020-03-01',
'2020-04-01',
'2020-05-01',
'2020-06-01',
'2020-07-01']
添加回答
举报