plalanne
plalanne

Reputation: 1030

Days before end of month in pandas

I would like to get the number of days before the end of the month, from a string column representing a date. I have the following pandas dataframe :

df = pd.DataFrame({'date':['2019-11-22','2019-11-08','2019-11-30']})
df

         date
0  2019-11-22
1  2019-11-08
2  2019-11-30

I would like the following output :

 df
         date  days_end_month
0  2019-11-22               8
1  2019-11-08              22
2  2019-11-30               0

The package pd.tseries.MonthEnd with rollforward seemed a good pick, but I can't figure out how to use it to transform a whole column.

Upvotes: 0

Views: 869

Answers (1)

jezrael
jezrael

Reputation: 863741

Subtract all days of month created by Series.dt.daysinmonth with days extracted by Series.dt.day:

df['date'] = pd.to_datetime(df['date'])

df['days_end_month'] = df['date'].dt.daysinmonth - df['date'].dt.day

Or use offsets.MonthEnd, subtract and convert timedeltas to days by Series.dt.days:

df['days_end_month'] = (df['date'] + pd.offsets.MonthEnd(0) - df['date']).dt.days

print (df)
        date  days_end_month
0 2019-11-22               8
1 2019-11-08              22
2 2019-11-30               0

Upvotes: 2

Related Questions