[Tutor] Help with range of months spanning across years

Alan Gauld alan.gauld at btinternet.com
Wed Feb 2 02:07:17 CET 2011


"Hugo Arts" <hugo.yoshi at gmail.com> wrote

>> What would be the most straightforward way to create a list of
>> year/month pairs from start to end? I want to end up with a list of
>> tuples like this:
>>
>> mylist = [(2009, 8), (2009, 9), (2009, 10), (2009, 11), (2009, 12), 
>> (2010, 1)]
>>
> That said, you can do this rather straightforwardly with two nested
> for loops and the range() or xrange(), one for the year and one for
> the month.

Or if you want to be able to use it across historic times
(taking account of calendar irregularities etc) then you
can get the data from the datetime module... It just
depends how open ended your lists need to be. For
months and years you are probably ok with a simple
loop approach as Hugo suggests, but if you ever need
to go to days or weeks then datetime would be safer..

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list