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

41,707

Solution 1

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)

Solution 2

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']

Solution 3

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.

Solution 4

using list comprehension:

from datetime import date, timedelta
def find_sundays_between(start:date, end:date):
    total_days:int = (dend-dstart).days + 1
    sunday:int = 6
    # this will return all sundays between start-end dates.
    all_days = [dstart + timedelta(days=x) for x in range(total_days)]
    sundays = [day for day in days if day is sunday]
    return sundays

date_start:date = date(2018,1,1)
date_end:date = date(2018,12,31)
sundays = find_sundays_between(date_start, date_end)

Solution 5

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
...
Share:
41,707

Related videos on Youtube

rmontgomery429
Author by

rmontgomery429

Updated on March 12, 2022

Comments

  • rmontgomery429
    rmontgomery429 about 2 years

    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.

    • Noon Silk
      Noon Silk over 14 years
      Find the first Sunday and constantly add 7? Until you hit the limit of days for that month, then start from 0 ...
    • Jonathan Leffler
      Jonathan Leffler over 14 years
      See also very similar question from same person: stackoverflow.com/questions/2003841/…
  • sjpatel
    sjpatel over 9 years
    Hey, I know its too late, but how to adjust the code for fetching saturdays
  • sth
    sth over 9 years
    @sjpatel: You need to change the offset calculation to start with the first saturday instead of sunday. This could be done with timedelta(days = (5 - d.weekday() + 7) % 7). Or, more explicitly timedelta(days = (5 - d.weekday() if d.weekday() <= 5 else 7 + 5 - d.weekday()))
  • Queue Overflow
    Queue Overflow over 7 years
    Nice answer! For strangers I want to notice, just add brackets to the print expression and this code will run by Python 3
  • thouger
    thouger almost 4 years
    It will lost the day where sunday is 1st.Use "today + datetime.timedelta(days=-today.weekday(), weeks=1)" will better.
  • nitekrawler
    nitekrawler over 3 years
    @thouger pretty sure the original code works. January 1, 2012 is a Sunday. If you plug 2012 into the function it returns 2012-01-01 as the first entry.
  • Dinesh Singh
    Dinesh Singh almost 3 years
    Shouldn't you replace before with after?