0

How to calculate two datetime's month difference?

If I have two datetime, such as: 2017.01.01 and 2018.04.01, the months difference is 15. (2017.01.01 ~ 2018.04.01)

But how can I calculate it?

sof-03
  • 2,255
  • 4
  • 15
  • 33

1 Answers1

0

code:

from datetime import datetime
from dateutil import relativedelta


date1 = datetime.strptime(str('2017.01.01'), '%Y.%m.%d')

date2 = datetime.strptime(str('2018.04.01'), '%Y.%m.%d')
r = relativedelta.relativedelta(date1, date2)
print(r.months)

r = - (r.months + r.years * 12)
print(r)

OUTPUT:

-3
15
Nihal
  • 5,262
  • 7
  • 23
  • 41