I'm attempting to round the date from this dataframe below to the 1st day of the next month - i.e. 1997-10-10 would result in 1997-11-01:
Date
1997-10-10
1997-05-27
1997-04-30
1997-12-19
1997-08-12
Currently my code looks like:
df = pd.read_csv(XXX)
df['Date'] = pd.to_datetime(df.Date)
df['Date'] = df['Date'].dt.date.replace(day = 1)
According to the python library documentation,
date.replace(year=self.year, month=self.month, day=self.day)
Return a date with the same value, except for those parameters given new values by whichever keyword arguments are specified. For example, if d == date(2002, 12, 31), then d.replace(day=26) == date(2002, 12, 26).
I had presumed that I could use .replace
with only 1 argument - day -however I'm receiving a number of errors.
I think you need MonthBegin(0)
:
df['Date'] = pd.to_datetime(df.Date) + pd.offsets.MonthBegin(0)
print (df)
Date
0 1997-11-01
1 1997-06-01
2 1997-05-01
3 1998-01-01
4 1997-09-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