简体   繁体   English

熊猫date_range从每周的特定日期开始,每周一次

[英]Pandas date_range on a weekly basis starting with a particular day of the week

Looking for a sophisticated way loop through date range and run only on every Sunday. 寻找一种复杂的方式遍历日期范围并仅在每个星期日运行。

import pandas

for da in pandas.date_range("20181101","20181217",freq='B'):
    runJob()

But are there some options which runs the loop for every Sunday in the date range ? 但是,是否有一些选项可以在日期范围内的每个星期日运行循环?

Set freq='W-SUN' to specify Sundays only: 设置freq='W-SUN'仅指定星期日:

pd.date_range("20181101", "20181217", freq='W-SUN')

DatetimeIndex(['2018-11-04', '2018-11-11', '2018-11-18', '2018-11-25',
               '2018-12-02', '2018-12-09', '2018-12-16'],
              dtype='datetime64[ns]', freq='W-SUN')

Doing a little crosschecking... 做一点交叉检查...

dt = pd.date_range("20181101", "20181217", freq='W-SUN')
assert dt.strftime('%A').unique().tolist() == ['Sunday']

You can actually specify the anchor to be any day of the week, as long as the offset specified is in the form "W-<day_of_week>" . 实际上,您可以将锚点指定为星期几,只要指定的偏移量为"W-<day_of_week>"

In this case, the default is actually Sunday, so just using freq='W' is sufficient. 在这种情况下,默认值实际上是星期日,因此仅使用freq='W'就足够了。

pd.date_range("20181101","20181217", freq='W')

See the docs section on Anchored Date Offsets for more information. 有关更多信息,请参见“ 锚定日期偏移量”上的“文档”部分。

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

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