Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python datetime - Pandas: convert date in month to the 1st day of next month

I am wondering if there are any efficient methods or one-liner that, given a pandas DatetimeIndex date1, return a DatetimeIndex date2 that is the first day of the next month?

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

I have tried this one liner

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

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

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

You'll find a lot of examples in the official Pandas docs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...