A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from http://mail.python.org/pipermail/python-list/2005-September/334127.html below:

Creating a list of Mondays for a year

Creating a list of Mondays for a yearPeter Hansen peter at engcorp.com
Sun Sep 18 16:52:08 EDT 2005
Chris wrote:
> Is there a way to make python create a list of Mondays for a given year?
> 
> For example,
> 
> mondays = ['1/3/2005','1/10/2005','1/17/2005','1/24/2005',
> '1/31/2005','2/7/2005',   ... ]

from datetime import date, timedelta

def mondays(year):
     '''generate all days that are Mondays in the given year'''
     jan1 = date(year, 1, 1)

     # find first Monday (which could be this day)
     monday = jan1 + timedelta(days=(7-jan1.weekday()) % 7)

     while 1:
         if monday.year != year:
             break
         yield monday
         monday += timedelta(days=7)

 >>> [str(x) for x in mondays(2005)]
['2004-01-05', '2004-01-12', ... '2004-12-27']

Extension to support any day of the week (including renaming the 
function!) is left as an exercise to the reader. ;-)

--
Peter

More information about the Python-list mailing list

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4