Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

At first I tried using a timedelta but it doesn't accept months as an argument, so my next working example is this:

from datetime import datetime
current_date = datetime.now()

months = []
for month_adjust in range(2, -3, -1): # Order by new to old.
    # If our months are out of bounds we need to change year.
    if current_date.month + month_adjust <= 0:
        year = current_date.year - 1
    elif current_date.month + month_adjust > 12:
        year = current_date.year + 1
    else:
        year = current_date.year
    # Keep the months in bounds.
    month = (current_date.month + month_adjust) % 12
    if month == 0: month = 12
    months.append(current_date.replace(year, month=month, day=1))

Is there a cleaner way?

share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

Based on this answer, I would do something like :

from datetime import date
from dateutil.relativedelta import relativedelta
today = date.today()
months = [today + relativedelta(months = +i) for i in range(2,-3,-1)]

It's always better not to have to play with the dates manually as so many things can go wrong.

(I don't have access to a machine with relativedelta here so it's not tested but I'm pretty confident it should work)

share|improve this answer
    
That is wonderful, thanks! BTW you can drop the + in +i. :) –  Kit Sunde Jan 6 '13 at 23:35
    
Also you don't need the .month in the list compression as I need the date object. –  Kit Sunde Jan 6 '13 at 23:41
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.