Get (year,month) for the last X months

Viewed 18525

I got a very simple thing to to in python: I need a list of tuples (year,month) for the last x months starting (and including) from today. So, for x=10 and today(July 2011), the command 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 implementation of 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 outputs the correct solution for my test cases but I'm not comfortable with this solution: It assumes that a month has four weeks and this is simply not true. I could replace the weeks=4 with days=30 which would make a better solution but it is still not correct.

The other solution which came to my mind is to use simple maths and subtract 1 from a months counter and if the month-counter is 0, subtract 1 from a year counter. The problem with this solution: It requires more code and isn't very readable either.

So how can this be done correctly?

8 Answers

Or you can define a function to get the last month, and then print the months ( it's a bit rudimentary)

def last_month(year_month):#format YYYY-MM
    aux = year_month.split('-')
    m = int(aux[1])
    y = int(aux[0])

    if m-1 == 0:
        return str(y-1)+"-12"
    else:
        return str(y)+"-"+str(m-1)

def print_last_month(ran, year_month= str(datetime.datetime.today().year)+'-'+str(datetime.datetime.today().month)):
    i = 1 
    if ran != 10:
        print( last_month(year_month) )
        print_last_month(i+1, year_month= last_month(year_month))
    def list_last_year_month(self):
    last_day_of_prev_month = date.today()
    number_of_years = self.number_of_years
    time_list = collections.defaultdict(list)
    for y in range(number_of_years+1):
        for m in range(13):
            last_day_of_prev_month = last_day_of_prev_month.replace(day=1) - timedelta(days=1)
            last_month = str(last_day_of_prev_month.month)
            last_year = str(last_day_of_prev_month.year)
            time_list[last_year].append(last_month)
    return time_list
Related