views:

143

answers:

2

Using Python...

How can I select all of the Sundays (or any day for that matter) in a year?

[ '01/03/2010','01/10/2010','01/17/2010','01/24/2010', ...]

These dates represent the Sundays for 2010. This could also apply to any day of the week I suppose.

+8  A: 

You can use date from the datetime module to find the first Sunday in a year and than keep adding seven days, generating new Sundays:

from datetime import date, timedelta

def allsundays(year):
   d = date(year, 1, 1)                    # January 1st
   d += timedelta(days = 6 - d.weekday())  # First Sunday
   while d.year == year:
      yield d
      d += timedelta(days = 7)

for d in allsundays(2010):
   print d
sth
Lovely answer, very Pythonic.
Arrieta
I've deleted my answer, because your answer actually does in Python what I only had time to talk about in words :-) +1.
whybird
+1  A: 

Using the dateutil module, you could generate the list this way:

#!/usr/bin/env python
import dateutil.relativedelta as relativedelta
import dateutil.rrule as rrule
import datetime
year=2010
before=datetime.datetime(year,1,1)
after=datetime.datetime(year,12,31)
rr = rrule.rrule(rrule.WEEKLY,byweekday=relativedelta.SU,dtstart=before)
print rr.between(before,after,inc=True)

Although finding all Sundays is not too hard to do without dateutil, the module is handy especially if you have more complicated or varied date calculations.

If you are using Debian/Ubuntu, dateutil is provided by the python-dateutil package.

unutbu