4

I want to calculate 6 month before date in python.So is there any problem occurs at dates (example 31 august).Can we solve this problem using timedelta() function.can we pass months like date=now - timedelta(days=days) instead of argument days.

Ashith
  • 309
  • 1
  • 3
  • 17
  • 1
    So how do you (or your organization) define what is 6 months before August? If going by straight last day of the month in billing cycle, it could be 28 Feb or 29 Feb, if a month is 30 days it would be 4th March. You need to clarify this. – metatoaster Jul 30 '15 at 04:40
  • Its for daily report of six months. I think the easiest and better option will be subtracting 183 day so the script will not break – Ashith Jul 30 '15 at 04:51
  • Then you already had your answer by doing `date = datetime.now() - timedelta(days=183)`, if that is your definition (6 months being defined as 183 days). – metatoaster Jul 30 '15 at 05:23

3 Answers3

9

timedelta does not support months, but you can try using dateutil.relativedelta for your calculations , which do support months.

Example -

>>> from dateutil import relativedelta
>>> from datetime import datetime
>>> n = datetime.now()

>>> n - relativedelta.relativedelta(months=6)
datetime.datetime(2015, 1, 30, 10, 5, 32, 491815)

>>> n - relativedelta.relativedelta(months=8)
datetime.datetime(2014, 11, 30, 10, 5, 32, 491815)
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
3

If you are only interested in what the month was 6 months ago then try this:

import datetime

month = datetime.datetime.now().month - 6
if month < 1:
    month = 12 + month  # At this point month is 0 or a negative number so we add
Eric Bulloch
  • 827
  • 6
  • 10
0

Following function should work fine for both month add and month substract.

import datetime
import calendar

def add_months(sourcedate, months):
     month = sourcedate.month - 1 + months
     year = sourcedate.year + month / 12
     month = month % 12 + 1
     day = min(sourcedate.day,calendar.monthrange(year,month)[1])
     return datetime.date(year,month,day)

#Example: Get today    
dateToday = datetime.date.today()

#Substract 6 month from Today
print add_months(dateToday ,-6)
user353gre3
  • 2,747
  • 4
  • 24
  • 27