Tartaglia
Tartaglia

Reputation: 1041

Loop through Year while skipping certain months

I am using the following loop for a monthly time series and I would like to skip the months of May and November:

from pandas.tseries.offsets import MonthEnd

for beg in pd.date_range('2014-01-01', '2017-12-31', freq='MS'):
    print(beg.strftime("%Y-%m-%d"), (beg + MonthEnd(1)).strftime("%Y-%m-%d"))

Can anyone suggest an approach?

Upvotes: 1

Views: 39

Answers (1)

Rakesh
Rakesh

Reputation: 82775

Using a simple if condition to check if month not in check list.

Ex:

import pandas as pd
from pandas.tseries.offsets import MonthEnd

for beg in pd.date_range('2014-01-01', '2017-12-31', freq='MS'):
    if not beg.month in [5, 11]:
        print(beg.strftime("%Y-%m-%d"), (beg + MonthEnd(1)).strftime("%Y-%m-%d"))  

Upvotes: 2

Related Questions