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, 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)
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 pd
def 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 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.