Given a dataframe:
df = pd.DataFrame({'c':[0,1,1,2,2,2],'date':pd.to_datetime(['2016-01-01','2016-02-01','2016-03-01','2016-04-01','2016-05-01','2016-06-05'])})
How to get the previous month begin for each date? The below doesn't work for 6/5 and there is some extra time portion.
pd.to_datetime(df['date'], format="%Y%m") + pd.Timedelta(-1,unit='M') + MonthBegin(0)
EDIT
I have a workaround (2 steps back and 1 step forward):
(df['date']+ pd.Timedelta(-2,unit='M')+ MonthBegin(1)).dt.date
Don't like this. There should be something better.
You can use current_date. replace(day=1) to get first day in current month. And if you substract datetime. timedelta(days=1) then you get last day in previous month.
The is_month_start attribute of Pandas. Timestamp, which is an equivalent of Python's date time-object, is used to check if a given date is the first day of the month or not.
You can first subtract MonthEnd
to get to the end of the previous month, then MonthBegin
to get to the beginning of the previous month:
df['date'] - pd.offsets.MonthEnd() - pd.offsets.MonthBegin()
The resulting output:
0 2015-12-01
1 2016-01-01
2 2016-02-01
3 2016-03-01
4 2016-04-01
5 2016-05-01
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With