Skip to content
Advertisement

A more suitable way to rewrite this?

I have the method:

 def checkAgainstDate():
     currentDate = date.today()
     currentMonth = date.today().month
     if currentMonth == 1
         year = currentDate.year-1
         return date(year, 11, 01)
     elif currentMonth == 2:
         year = currentDate.year-1
         return date(year, 12, 01)
     else
         return date(currentDate.year, currentMonth-2, 01)

This just returns the first of the month 2 months ago, which is what I want is there a better approach I could have used using timedeltas? I choose my way because weeks in a month are not always constant.

Advertisement

Answer

dateutil is an amazing thing. It really should become stdlib someday.

>>> from dateutil.relativedelta import relativedelta
>>> from datetime import datetime
>>> (datetime.now() - relativedelta(months=2)).replace(day=1)
datetime.datetime(2010, 6, 1, 13, 16, 29, 643077)
>>> (datetime(2010, 4, 30) - relativedelta(months=2)).replace(day=1)
datetime.datetime(2010, 2, 1, 0, 0)
>>> (datetime(2010, 2, 28) - relativedelta(months=2)).replace(day=1)
datetime.datetime(2009, 12, 1, 0, 0)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement