Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 652
v0lkoff Avatar asked Jan 27 '26 11:01

v0lkoff


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
like image 93
jezrael Avatar answered Jan 29 '26 01:01

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!