Jack
Jack

Reputation: 1754

Get next month first date based on datetime numpy array

Data

lst=array(['2019-08-30T00:00:00.000000000', '2019-09-30T00:00:00.000000000',
       '2019-10-31T00:00:00.000000000', '2019-11-29T00:00:00.000000000',
       '2020-01-23T00:00:00.000000000', '2020-02-28T00:00:00.000000000'],
      dtype='datetime64[ns]')

Goal

I want to get next month first date for each element in the above array. For example, 2019-08-30T00:00:00.000000000 will be '2019-09-01T00:00:00.000000000',2020-01-23T00:00:00.000000000 will be 2020-02-01T00:00:00.000000000,the final ouput will be dictionary like {'2019-08-30T00:00:00.000000000':'2019-09-01T00:00:00.000000000',……}

Try

It's easy to get by +timedelta(days=1) for some elements, but it's hard for '2020-01-23T00:00:00.000000000' etc.

Upvotes: 0

Views: 247

Answers (1)

Paul Panzer
Paul Panzer

Reputation: 53029

You can convert to month units, add one and convert back:

(lst.astype("M8[M]")+1).astype("M8[ns]")
# array(['2019-09-01T00:00:00.000000000', '2019-10-01T00:00:00.000000000',
#        '2019-11-01T00:00:00.000000000', '2019-12-01T00:00:00.000000000',
#        '2020-02-01T00:00:00.000000000', '2020-03-01T00:00:00.000000000'],
#       dtype='datetime64[ns]')

Upvotes: 1

Related Questions