简体   繁体   English

开始日期是每月的第一天,结束日期是下个月的第一天 Pandas

[英]start date is first day of month, end date is subsequent month first day Pandas

I'm looking to iterate through a date range where start_date and end_date increment on a monthly basis with each iteration starting at the beginning of the month.我希望遍历一个日期范围,其中 start_date 和 end_date 每月递增,每次迭代从月初开始。

First iteration example:第一次迭代示例:

start_date = '2020-01-01'
end_date = '2020-02-01'

The second iteration of the loop should look like:循环的第二次迭代应如下所示:

start_date = '2020-02-01'
end_date = '2020-03-01'

what I've tried:我试过的:

for x in range(20):
    start_date = pd.Timestamp('2020-01-01') + pd.offsets.MonthBegin(n=1)
    end_date = start_date + pd.offsets.MonthBegin(n=1)
    

The issue I am having is that on the next iteration I am not incrementing to the next month.我遇到的问题是,在下一次迭代中,我不会增加到下个月。 it stays on the current month.它停留在当前月份。 Is there a way to increment to the next month?有没有办法增加到下个月?

start_date = pd.to_datetime('2020-02-01')
end_date = pd.to_datetime('2020-03-01')
for x in range(20):
     
    print(start_date.strftime('%Y-%m-%d'))
    print(end_date.strftime('%Y-%m-%d'))
    # do the work here...


    # then increment the dates for the next iteration
    start_date = start_date + pd.offsets.MonthBegin(n=1)
    end_date = start_date + pd.offsets.MonthBegin(n=1)

seems to do the job似乎完成了这项工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM