Creating a list of Mondays for a year

Peter Hansen peter at engcorp.com
Sun Sep 18 16:52:08 EDT 2005


Chris wrote:
> Is there a way to make python create a list of Mondays for a given year?
> 
> For example,
> 
> mondays = ['1/3/2005','1/10/2005','1/17/2005','1/24/2005',
> '1/31/2005','2/7/2005',   ... ]

from datetime import date, timedelta

def mondays(year):
     '''generate all days that are Mondays in the given year'''
     jan1 = date(year, 1, 1)

     # find first Monday (which could be this day)
     monday = jan1 + timedelta(days=(7-jan1.weekday()) % 7)

     while 1:
         if monday.year != year:
             break
         yield monday
         monday += timedelta(days=7)

 >>> [str(x) for x in mondays(2005)]
['2004-01-05', '2004-01-12', ... '2004-12-27']

Extension to support any day of the week (including renaming the 
function!) is left as an exercise to the reader. ;-)

--
Peter



More information about the Python-list mailing list