[Tutor] complex iteration over a list (original) (raw)
Tim Peters tim.peters at gmail.com
Sat Jul 3 15:09:32 EDT 2004
- Previous message: [Tutor] complex iteration over a list
- Next message: [Tutor] A year's calendar to a text file?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
[Michele Alzetta] ...
This particular problem though is more easily solved ! I've found that calendar is useless, but datetime.timedelta does it, as my startday is a timedelta object (and so is my endday, which I had changed to number of days thinking it would make things simpler).
startday = datetime(2004,6,1,8) endday = datetime(2004,9,1,8) def daysinperiod(startday,endday): daysinperiod = [] while startday <= endday: daysinperiod.append(startday.day) startday = startday + timedelta(days=1) return daysinperiod Eliminates the need for lists with the length of different months, eliminates the nightmare of leap-years ... Python is always simpler and more powerful than one thinks :-)
Well, often . A more concise way to spell that is:
def daysinperiod2(startday, endday): numdays = (endday - startday).days + 1 return [(startday + timedelta(i)).day for i in range(numdays)]
If you pass the number of days you want instead of endday, then it can be even shorter:
def daysinperiod2(startday, numdays): return [(startday + timedelta(i)).day for i in range(numdays)]
- Previous message: [Tutor] complex iteration over a list
- Next message: [Tutor] A year's calendar to a text file?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]