Get (year,month) for the last X months
I don't see it documented anywhere, but time.mktime
will "roll over" into the correct year when given out-of-range, including negative, month values:
x = 10
now = time.localtime()
print([time.localtime(time.mktime((now.tm_year, now.tm_mon - n, 1, 0, 0, 0, 0, 0, 0)))[:2] for n in range(x)])
Neatest would be to use integer division (//
) and modulus (%
) functions, representing the month by the number of months since year 0:
months = year * 12 + month - 1 # Months since year 0 minus 1
tuples = [((months - i) // 12, (months - i) % 12 + 1) for i in range(10)]
The - 1
in the months
expression is required to get the correct answer when we add 1 to the result of the modulus function later to get 1-indexing (i.e. months go from 1 to 12 rather than 0 to 11).
Or you might want to create a generator:
def year_month_tuples(year, month):
months = year * 12 + month - 1 # -1 to reflect 1-indexing
while True:
yield (months // 12, months % 12 + 1) # +1 to reflect 1-indexing
months -= 1 # next time we want the previous month
Which could be used as:
>>> tuples = year_month_tuples(2011, 7)
>>> [tuples.next() for i in range(10)]
Using relativedelta
...
import datetime
from dateutil.relativedelta import relativedelta
def get_last_months(start_date, months):
for i in range(months):
yield (start_date.year,start_date.month)
start_date += relativedelta(months = -1)
>>> X = 10
>>> [i for i in get_last_months(datetime.datetime.today(), X)]
>>> [(2013, 2), (2013, 1), (2012, 12), (2012, 11), (2012, 10), (2012, 9), (2012, 8), (2012, 7), (2012, 6), (2012, 5)]
Update: Adding a timedelta
version anyway, as it looks prettier :)
def get_years_months(start_date, months):
for i in range(months):
yield (start_date.year, start_date.month)
start_date -= datetime.timedelta(days=calendar.monthrange(start_date.year, start_date.month)[1])
You don't need to work with timedelta
since you only need year and month, which is fixed.
def get_years_months(my_date, num_months):
cur_month = my_date.month
cur_year = my_date.year
result = []
for i in range(num_months):
if cur_month == 0:
cur_month = 12
cur_year -= 1
result.append((cur_year, cur_month))
cur_month -= 1
return result
if __name__ == "__main__":
import datetime
result = get_years_months(datetime.date.today(), 10)
print result