Search code examples
pythondjangopython-datetime

How can I extend month in Django


I am trying to add extra month in my expiry_date field in Django, I've done like this

import datetime

now = datetime.datetime.now()

year = now.year
day = now.day
hour = now.hour
minute = now.minute
second = now.second

def add_expiry(a):
    month = now.month
    print('month : ', month)
    current_month = month+a
    print('month adding variable : ', current_month)
    date = f"{year}/{current_month}/{day}"
    time = f"{hour}:{minute}:{second}"
    return f"{date} {time}"
print(add_expiry(6))

Output :

month :  6
month adding variable :  12
2021/12/27 11:54:17

but problem is it will increase only month but what about year how I can handle year please help.

Example : current_date = 2021-06-27 12:24:52.976751 if I add 4 as parameter it should return 2021-10-27 12:24:52.976751

and if I add 7 as parameter it should return 2022-04-27 12:24:52.976751

Note : I don't want to use dateutil


Solution

  • The easiest way to do this is to use the module dateutil:

    >>> from dateutil import relativedelta
    >>> datetime.datetime.now() + relativedelta.relativedelta(months=1)
    datetime.datetime(2021, 7, 27, 14, 30, 53, 111845)
    >>> datetime.datetime.now() + relativedelta.relativedelta(months=4)
    datetime.datetime(2021, 10, 27, 14, 32, 20, 238002)