How do I calculate the date six months from the current date using the datetime Python module?

How do I calculate the date six months from the current date using the datetime Python module?

I found this solution to be good. (This uses the python-dateutil extension)

from datetime import date
from dateutil.relativedelta import relativedelta

six_months = date.today() + relativedelta(months=+6)

The advantage of this approach is that it takes care of issues with 28, 30, 31 days etc. This becomes very useful in handling business rules and scenarios (say invoice generation etc.)

$ date(2010,12,31)+relativedelta(months=+1)
  datetime.date(2011, 1, 31)

$ date(2010,12,31)+relativedelta(months=+2)
  datetime.date(2011, 2, 28)

Well, that depends what you mean by 6 months from the current date.

  1. Using natural months:

    inc = 6
    month = (month + inc - 1) % 12 + 1
    year = year + (month + inc - 1) // 12
    
  2. Using a bankers definition, 6*30:

    date += datetime.timedelta(6 * 30)
    

How do I calculate the date six months from the current date using the datetime Python module?

With Python 3.x you can do it like this:

from datetime import datetime, timedelta
from dateutil.relativedelta import *

date = datetime.now()
print(date)
# 2018-09-24 13:24:04.007620

date = date + relativedelta(months=+6)
print(date)
# 2019-03-24 13:24:04.007620

but you will need to install python-dateutil module:

pip install python-dateutil

Leave a Reply

Your email address will not be published. Required fields are marked *