I have a very simple thing for python: I need a list of tuples (year,month) for the last x months, starting (including) from today. So, for x = 10 and today (July 2011), the team should output:
[(2011, 7), (2011, 6), (2011, 5), (2011, 4), (2011, 3), (2011, 2), (2011, 1), (2010, 12), (2010, 11), (2010, 10)]
Only the default datetime version for python should be used. I came up with the following solution:
import datetime [(d.year, d.month) for d in [datetime.date.today()-datetime.timedelta(weeks=4*i) for i in range(0,10)]]
This solution displays the correct solution for my test cases, but I do not like this solution: it assumes that the month has four weeks, and this is simply not true. I could replace weeks=4 with days=30 , which would make a better solution, but it is still incorrect.
Another solution that occurred to me was to use simple mathematical calculations and subtract 1 from the month counter, and if the month counter is 0, subtract 1 from the year counter. The problem with this solution: it requires more code and is not very readable.
So how can this be done correctly?