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.
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)
Convert to an "absolute month number", subtract 2, convert back to year & month:
currentdate = date.today()
monthindex = 12*currentdate.year + (currentdate.month-1) -2
return datetime( monthindex // 12, monthindex % 12 + 1, 1)
精彩评论