Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 748
Sumit Chouhan Avatar asked Jan 28 '23 00:01

Sumit Chouhan


1 Answers

Set freq='W-SUN' to specify Sundays only:

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>".

In this case, the default is actually Sunday, so just using freq='W' is sufficient.

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

See the docs section on Anchored Date Offsets for more information.

like image 84
cs95 Avatar answered Jan 29 '23 14:01

cs95