Search code examples
pythonpandasdatetimedate-range

When I set freq="W", why does the output become freq="W-Sun"?


When I set freq="W", why does the output become freq="W-Sun"?

import pandas as pd

a=pd.date_range('10/10/2018', periods=10, freq="W")
print(a)

Solution

  • Sunday is considered to be the start of the week by default, and with a weekly frequency, the date is generated from the next sunday forward.

    You can do a little preprocessing to compute the weekly frequency beforehand.

    start = '10/10/2018'
    pd.date_range(start, periods=10, freq='W-' + pd.to_datetime(start).strftime('%a'))
    
    DatetimeIndex(['2018-10-10', '2018-10-17', '2018-10-24', '2018-10-31',
                   '2018-11-07', '2018-11-14', '2018-11-21', '2018-11-28',
                   '2018-12-05', '2018-12-12'],
                  dtype='datetime64[ns]', freq='W-WED')
    

    This will set the frequency to be W-{whatever day} you're trying to start the date range from.