Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 883
rmontgomery429 Avatar asked Jan 05 '10 02:01

rmontgomery429


2 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) 
like image 163
sth Avatar answered Sep 28 '22 02:09

sth


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'] 
like image 43
Brad Solomon Avatar answered Sep 28 '22 03:09

Brad Solomon