Reputation: 17087
I have a pandas period object in YYYY-MM format. I am trying to get the last day of the month from this.
df['Date']=(df.MONTH).end_time
I get the error:
'Series' object has no attribute 'end_time'
How can I resolve this?
Upvotes: 1
Views: 1386
Reputation: 294218
normalize
First thing to realize is that for a pandas.Series
you access the datetime and timedelta functions via the .dt
accessor. This is what allows you to get at end_time
. However, that gives you the last date with the last possible time component. This may be more than you were bargaining for. In the case that you really just want the date. You can use normalzie
Convert times to midnight.
The time component of the date-time is converted to midnight i.e. 00:00:00. This is useful in cases, when the time does not matter. Length is unaltered. The timezones are unaffected.
This method is available on Series with datetime values under the .dt accessor, and directly on Datetime Array/Index.
df = pd.DataFrame(dict(MONTH=[pd.Period('2019-01')]))
normalize
df.MONTH.dt.end_time.dt.normalize()
0 2019-01-31
Name: MONTH, dtype: datetime64[ns]
normalize
0 2019-01-31 23:59:59.999999999
Name: MONTH, dtype: datetime64[ns]
Upvotes: 2
Reputation: 323226
Try with MonthEnd
s=pd.Series('2019-01')
pd.to_datetime(s,format='%Y-%m')+pd.tseries.offsets.MonthEnd()
Out[113]:
0 2019-01-31
dtype: datetime64[ns]
Upvotes: 3