user10293055
user10293055

Reputation:

Months difference between two dates

I have two dates in the format a = Timestamp('2022-07-01 00:00:00') and the other date is in same format b = Timestamp('1993-09-01 00:00:00')

So I'm trying to find number of months difference between these two, The way I did is

relativedelta(a,b).years * 12

Which gives the value 336, but the actual difference is 346. Please let me know where I went wrong help me correct it.

Upvotes: 7

Views: 8843

Answers (2)

Chris
Chris

Reputation: 1668

The reason for the shortfall is because relativedelta is giving you the number of 'complete' years, i.e. from 1993-09-01 to 2021-09-1, so you are missing the last ten months between 2021-09-01 and 2022-07-01. A simple modification to your current code is to add the months like this:

relativedelta(a,b).years * 12 + relativedelta(a,b).months

Which gives the correct result of 346 months.

Upvotes: 7

Sreeram TP
Sreeram TP

Reputation: 11907

You can round the date to Month with to_period() and then subtract the result

a = pd.Timestamp('2022-07-01 00:00:00')
b = pd.Timestamp('1993-09-01 00:00:00')

months = a.to_period('M') - b.to_period('M')

print(months) # 346

Upvotes: 5

Related Questions