Home > Software design >  ValueError: Value must be Period, string, integer, or datetime
ValueError: Value must be Period, string, integer, or datetime

Time:12-08

I have an issue using datetime...

I have a dataframe with a column time

print(dt['time'].dtypes)

It replies:

datetime64[ns]

Now I want to have the number of days of the month of the date:

dt['NB_DAYS'] = p.Period(dt['time']).days_in_month

But I have an issue for which I really can't find answers on the web:

ValueError: Value must be Period, string, integer, or datetime

Can you help me with that? Thanks

CodePudding user response:

Use Series.dt.days_in_month:

dt['NB_DAYS'] = dt['time'].dt.days_in_month

If remove dt pandas test DatetimeIndex:

dt['NB_DAYS'] = pd.DatetimeIndex(dt['time']).days_in_month

dt = pd.DataFrame({ "time": pd.date_range("2010-12-30", freq='12D', periods=10)})

dt['NB_DAYS'] = dt['time'].dt.days_in_month
dt['NB_DAYS1'] = pd.DatetimeIndex(dt['time']).days_in_month
print (dt)
        time  NB_DAYS  NB_DAYS1
0 2010-12-30       31        31
1 2011-01-11       31        31
2 2011-01-23       31        31
3 2011-02-04       28        28
4 2011-02-16       28        28
5 2011-02-28       28        28
6 2011-03-12       31        31
7 2011-03-24       31        31
8 2011-04-05       30        30
9 2011-04-17       30        30
  • Related