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

Viewed 45605

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.

10 Answers

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.

If looking for a more general approach (ie not only Sundays), we can build on sth's answer:

def weeknum(dayname):
    if dayname == 'Monday':   return 0
    if dayname == 'Tuesday':  return 1
    if dayname == 'Wednesday':return 2
    if dayname == 'Thursday': return 3
    if dayname == 'Friday':   return 4
    if dayname == 'Saturday': return 5
    if dayname == 'Sunday':   return 6

This will translate the name of the day into an int.

Then do:

from datetime import date, timedelta
def alldays(year, whichDayYouWant):
    d = date(year, 1, 1)
    d += timedelta(days = (weeknum(whichDayYouWant) - d.weekday()) % 7)
    while d.year == year:
        yield d
        d += timedelta(days = 7)

for d in alldays(2020,'Sunday'):
    print(d)

Note the presence of % 7 in alldays(). This outputs:

2020-01-05
2020-01-12
2020-01-19
2020-01-26
2020-02-02
2020-02-09
2020-02-16
...

Can also do:

for d in alldays(2020,'Friday'):
    print(d)

which will give you:

2020-01-03
2020-01-10
2020-01-17
2020-01-24
2020-01-31
2020-02-07
2020-02-14
...

according to @sth answer I like to give you an alternative without a function

from datetime import date, timedelta,datetime

sunndays = list()

year_var = datetime.now() #get current date
year_var = year_var.year  #get only the year

d = date(year_var, 1, 1)  #get the 01.01 of the current year = 01.01.2020

#now we have to skip 4 days to get to sunday.
#d.weekday is wednesday so it has a value of 2
d += timedelta(days=6 - d.weekday()) # 01.01.2020 + 4 days (6-2=4)

sunndays.append(str(d.strftime('%d-%m-%Y'))) #you need to catch the first sunday

#here you get every other sundays
while d.year == year_var:
    d += timedelta(days=7)
    sunndays.append(str(d.strftime('%d-%m-%Y')))

print(sunndays) # only for control

if you want every monday for example

#for 2021 the 01.01 is a friday the value is 4
#we need to skip 3 days 7-4 = 3
d += timedelta(days=7 - d.weekday())
import time
from datetime import timedelta, datetime

first_date = '2021-01-01'
final_date = '2021-12-31'
first_date = datetime.strptime(first_date, '%Y-%m-%d')
last_date = datetime.strptime(final_date, '%Y-%m-%d')
week_day = 'Sunday'
dates = [first_date + timedelta(days=x) for x in range((last_date - first_date).days + 1) if (first_date + timedelta(days=x)).weekday() == time.strptime(week_day, '%A').tm_wday]

It will return all Sunday date of given date range.

according to @sth answer,it will lost the day when 1st is sunday.This will be better:

d = datetime.date(year, month-1, 28)
for _ in range(5):
    d = d + datetime.timedelta(days=-d.weekday(), weeks=1)
    if d.month!=month:
        break
    date.append(d)
Related