Python – Numbers of Day in Month

pandas, python

I have a data frame with a date time index, and I would like to multiply some columns with the number of days in that month.

                   TUFNWGTP  TELFS  t070101  t070102  t070103  t070104  TUDIARYDATE                                                              2003-01-03   8155462.672158      2        0        0        0        0   2003-01-04   1735322.527819      1        0        0        0        0   2003-01-04   3830527.482672      2       60        0        0        0   2003-01-02   6622022.995205      4        0        0        0        0   2003-01-09   3068387.344956      1        0        0        0        0 

Here, I would like to multiply all the columns starting with t with 31. That is, expected output is

                   TUFNWGTP  TELFS  t070101  t070102  t070103  t070104  TUDIARYDATE                                                              2003-01-03   8155462.672158      2        0        0        0        0   2003-01-04   1735322.527819      1        0        0        0        0   2003-01-04   3830527.482672      2     1680        0        0        0   2003-01-02   6622022.995205      4        0        0        0        0   2003-01-09   3068387.344956      1        0        0        0        0 

I know that there are some ways using calendar or similar, but given that I'm already using pandas, there must be an easier way – I assume.

There is no such datetime property, but there is an offset M – but I don't know how I would use that without massive inefficiency.

Best Solution

There is now a Series.dt.days_in_month attribute for datetime series. Here is an example based on Jeff's answer.

In [3]: df = pd.DataFrame({'date': pd.date_range('20120101', periods=15, freq='M')})In [4]: df['year'] = df['date'].dt.yearIn [5]: df['month'] = df['date'].dt.monthIn [6]: df['days_in_month'] = df['date'].dt.days_in_monthIn [7]: dfOut[7]:         date  year  month  days_in_month0  2012-01-31  2012      1             311  2012-02-29  2012      2             292  2012-03-31  2012      3             313  2012-04-30  2012      4             304  2012-05-31  2012      5             315  2012-06-30  2012      6             306  2012-07-31  2012      7             317  2012-08-31  2012      8             318  2012-09-30  2012      9             309  2012-10-31  2012     10             3110 2012-11-30  2012     11             3011 2012-12-31  2012     12             3112 2013-01-31  2013      1             3113 2013-02-28  2013      2             2814 2013-03-31  2013      3             31