Creating a list of Mondays for a year

George Sakkis gsakkis at rutgers.edu
Sun Sep 18 21:39:14 EDT 2005


"Peter Hansen" <peter at engcorp.com> wrote:

> George Sakkis wrote:
> > "Chris" <secun at yahoo.com> wrote:
> >>Is there a way to make python create a list of Mondays for a given year?
> >
> > Get the dateutil package (https://moin.conectiva.com.br/DateUtil):
> >
> > import dateutil.rrule as rrule
> > from datetime import date
> >
> > mondays2005 = tuple(rrule.rrule(rrule.WEEKLY,
> >                                 dtstart=date(2005,1,1),
> >                                 count=52,
> >                                 byweekday=rrule.MO))
>
> Count should probably be at least "53" to catch the years when there are
> that many Mondays.... such as 2001.  Unfortunately, I suspect that will
> screw it up for other years where there are only 52 (but I don't know
> this dateutil package so someone who does would have to say for sure).
>
> -Peter

Sorry, my bad; waldek in the post below got it right. Here's yet
another way that doesn't use the count or until keywords:

>>> from itertools import takewhile
>>> mondays2001 = tuple(takewhile(lambda d: d.year==2001,
                                  rrule.rrule(rrule.WEEKLY,
                                              dtstart=date(2001,1,1),
                                              byweekday=rrule.MO)))
>>> print len(mondays2001)
53

George




More information about the Python-list mailing list