Home > Enterprise >  How can I add only months together in python?
How can I add only months together in python?

Time:11-02

I understand using relativedelta for exact month calculation taking into account the number of days in each month.

Are there any streamlined libraries for adding just month ints together?

ie. December is 12. Adding 2 months is 14 which is 2 == February?

I am hoping to solve all edge cases surrounding the problem with a tested library.

I have thought of doing a modulo calculation along the following:

curr_month = 12 - 1 (-1 for 0 indexing) = 11

if we do divmod(curr_month, 11) , we get (0,0) but the result in reality should be 11. If I just handled that with an if result[0] == 0: curr_month = 11, then whenever result[1] we will get the wrong answer

CodePudding user response:

This formula should work for you

>>> current_month = 12
>>> delta = 2
>>> (((current_month - 1)   delta) % 12)   1
2
  • Related