I have the method:
JavaScript
x
12
12
1
def checkAgainstDate():
2
currentDate = date.today()
3
currentMonth = date.today().month
4
if currentMonth == 1
5
year = currentDate.year-1
6
return date(year, 11, 01)
7
elif currentMonth == 2:
8
year = currentDate.year-1
9
return date(year, 12, 01)
10
else
11
return date(currentDate.year, currentMonth-2, 01)
12
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.
JavaScript
1
9
1
>>> from dateutil.relativedelta import relativedelta
2
>>> from datetime import datetime
3
>>> (datetime.now() - relativedelta(months=2)).replace(day=1)
4
datetime.datetime(2010, 6, 1, 13, 16, 29, 643077)
5
>>> (datetime(2010, 4, 30) - relativedelta(months=2)).replace(day=1)
6
datetime.datetime(2010, 2, 1, 0, 0)
7
>>> (datetime(2010, 2, 28) - relativedelta(months=2)).replace(day=1)
8
datetime.datetime(2009, 12, 1, 0, 0)
9