Victor
Victor

Reputation: 17087

Pandas period(month) to last day of the month in YYYY-MM-DD format

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

Answers (2)

piRSquared
piRSquared

Reputation: 294218

You may want 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.

Setup

df = pd.DataFrame(dict(MONTH=[pd.Period('2019-01')]))

With normalize

df.MONTH.dt.end_time.dt.normalize()

0   2019-01-31
Name: MONTH, dtype: datetime64[ns]

Without normalize

0   2019-01-31 23:59:59.999999999
Name: MONTH, dtype: datetime64[ns]

Upvotes: 2

BENY
BENY

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

Related Questions