【问题标题】:start date is first day of month, end date is subsequent month first day Pandas开始日期是当月的第一天,结束日期是下个月的第一天 Pandas
【发布时间】:2020-12-17 17:39:11
【问题描述】:

我希望遍历一个日期范围,其中 start_date 和 end_date 每月递增,每次迭代从月初开始。

第一次迭代示例:

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

循环的第二次迭代应该如下所示:

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

我尝试过的:

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)
    

我遇到的问题是,在下一次迭代中,我不会增加到下个月。它停留在当前月份。有没有办法增加到下个月?

【问题讨论】:

  • 在 start_date 中将 n 替换为 x 并在 end_date 中替换为 x+1 ?如果您想跟踪它们,您可能应该在列表中收集日期。
  • 这确实成功了。非常感谢。

标签: python-3.x pandas date


【解决方案1】:
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)

似乎完成了这项工作

【讨论】:

  • 上面的答案可以解决问题,但也可以。太棒了!
猜你喜欢
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多