Pandas: convert date to month on first day of next month

I am wondering if there are any efficient methods or single-line ones that, with pandas date, DatetimeIndex date1 return DatetimeIndex date2, which is the first day of the next month?

For example, if date1 is '2011-09-30', then date2 is '2011-10-01'?

I tried this one liner

    df.index.to_period("M").to_timestamp('M')

But this only seems to be able to return "the last day of the same month." Is it possible to do some datetime arithmetic here?

Thanks!

+6
source share
1 answer

you can use pd.offsets.MonthBegin()

In [261]: d = pd.to_datetime(['2011-09-30', '2012-02-28'])

In [262]: d
Out[262]: DatetimeIndex(['2011-09-30', '2012-02-28'], dtype='datetime64[ns]', freq=None)

In [263]: d + pd.offsets.MonthBegin(1)
Out[263]: DatetimeIndex(['2011-10-01', '2012-03-01'], dtype='datetime64[ns]', freq=None)

There are many examples in the official Pandas docs.

+11

Source: https://habr.com/ru/post/1016796/


All Articles