我使用此代码查找两个日期之间的月份:
from dateutil.rrule import rrule, MONTHLY
from datetime import datetime
start_date = datetime(2017, 4, 30)
end_date = datetime(2017, 5, 6)
months = [dt.strftime("%m")
for dt in rrule(MONTHLY, dtstart=start_date,
until=end_date)]
In [14]: months
Out[14]: ['04']
我期待['04','05']
例如,如果我更改日期
from dateutil.rrule import rrule, MONTHLY
from datetime import datetime
start_date = datetime(2017, 4, 30)
end_date = datetime(2017, 5, 30)
months = [dt.strftime("%m")
for dt in rrule(MONTHLY, dtstart=start_date,
until=end_date)]
In [42]: months
Out[42]: ['04', '05']
答案 0 :(得分:4)
试试这个:
from datetime import datetime
from dateutil.relativedelta import relativedelta
from dateutil.rrule import rrule, MONTHLY
start_date = datetime(2017,4,30)
end_date = datetime(2017,5,6)
oneMonth = relativedelta(months=1)
months = [dt.strftime("%m")
for dt in rrule(MONTHLY, dtstart=start_date,
until=end_date+oneMonth)]
print months
输出:
['04', '05']