How can I use numpy.timedelta to add(or subtract) 1 month?

Viewed 604

I'm trying to decrement a date to 1 month. I mean to get the same date 1 month earlier.

import pandas as pd 
import numpy as np 

pd.to_datetime(201905, format='%Y%m') - np.timedelta64(1, 'M')

I expected to get the 1st day of previous month like

Timestamp('2019-04-01 00:00:00')

But the output is

Timestamp('2019-03-31 13:30:54')

The problem seems to be the same when I'm trying to add a month.

Code

pd.to_datetime(201905, format='%Y%m') + np.timedelta64(1, 'M')

Returns

Timestamp('2019-05-31 10:29:06')

instead of

Timestamp('2019-06-01 00:00:00')

How can I solve the issue?

My final goal is to take date in the integer format YYYYmm (like 201905) then add (or subtract) any number of months and return new date in the same format (integer, YYYYmm). Maybe it can be done easily with another packages?

1 Answers

Timedelta of one month is the length of a year divided by 12, so it is 'average' month unit:

a = pd.to_datetime(201905, format='%Y%m') - np.timedelta64(1, 'M')
print (a)
2019-03-31 13:30:54

If want subtract 1 month use offsets.DateOffset:

b = pd.to_datetime(201905, format='%Y%m') - pd.offsets.DateOffset(months=1)    
print (b)
2019-04-01 00:00:00
Related