How can I select all of the Sundays for a year using Python? How can I select all of the Sundays for a year using Python? python python

How can I select all of the Sundays for a year using Python?


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

from datetime import date, timedeltadef 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)


Pandas has great functionality for this purpose with its date_range() function.

The result is a pandas DatetimeIndex, but can be converted to a list easily.

import pandas as pddef allsundays(year):    return pd.date_range(start=str(year), end=str(year+1),                          freq='W-SUN').strftime('%m/%d/%Y').tolist()allsundays(2017)[:5]  # First 5 Sundays of 2017# ['01/01/2017', '01/08/2017', '01/15/2017', '01/22/2017', '01/29/2017']


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

#!/usr/bin/env pythonimport dateutil.relativedelta as relativedeltaimport dateutil.rrule as rruleimport datetimeyear=2010before=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.