Search code examples
pythondjangopython-datetimepython-dateutil

How to calculate months left to particular date?


In my django app, I have some date. I need to count how many months left to this date, using full (rounded) months. eg: today is 19/02/2015 (february), my "search" date is 04/08/2015. Difference should be 6. How can I get a proper value?


Solution

  • from datetime import datetime,timedelta
    from calendar import monthrange
    
    today = datetime.today()
    dt = "04/08/2015"
    
    fut = datetime.strptime(dt, "%d/%m/%Y")
    diff = 0
    while today <= fut:
        today += timedelta(days=monthrange(today.day,today.month)[1])
        diff += 1
    print(diff)
    6
    

    Without importing calender we can increment a count everytime we see a new month:

    from datetime import datetime,timedelta
    
    today = datetime.today() 
    dt = "09/08/2015"
    
    fut = datetime.strptime(dt, "%d/%m/%Y")
    diff = 0
    while today <= fut:
        mon = today.month
        today += timedelta(days=1)
        if today.month != mon:
            diff += 1
    print(diff)
    6
    

    If you want to make the future day the last day of the month:

    from datetime import datetime, timedelta
    from calendar import monthrange
    
    today = datetime.today()
    dt = "02/08/2015"
    
    fut = datetime.strptime(dt, "%d/%m/%Y")
    fut = fut + timedelta(days=monthrange(fut.day,fut.month)[1]-fut.day)
    diff = 0
    while today < fut:
        mon = today.month
        today += timedelta(days=1)
        if today.month != mon:
            diff += 1
    print(diff)
    

    This is purposely inaccurate to allow for rounding as required, all we care about are the amount of different months we encounter.