Create a list of dates for same day of week in a year

Sayth Renshaw flebber.crue at gmail.com
Wed Jun 28 00:15:21 EDT 2017


> > Is there an obvious method I am missing in creating a list of dates? I want to get a list of each Saturday and each Wednesday for the year 2017.
> >
> > It seems and maybe this is where I am wrong but doesn't the datetime library already know the dates if yes is there an easy way to query it?
> >
> 
> Sorta-kinda.
> 
> >>> import datetime
> >>> today = datetime.date.today()
> >>> monday = today - datetime.timedelta(days=today.weekday())
> >>> wednesday = monday + datetime.timedelta(days=2)
> >>> saturday = monday + datetime.timedelta(days=5)
> >>> week = datetime.timedelta(days=7)
> >>> next_wed = wednesday + week
> 
> You can mess around with that. If you want to find the beginning of
> the year, you could start by using datetime.date(2017, 1, 1) instead
> of today(), and then locate the previous Monday the same way.
> 
> So yes, all the information is available, but no, there's no easy way
> to say "give me all the Saturdays in 2017". You'd have to iterate.
> 
> ChrisA

Thanks ChrisA could using the calendar and a for loop work better?

As below test a date to see if the value = 5 so loop months 1-12 and then days 1-31 and just throw an error when the date doesn't exist 30th of Feb etc
In [19]: import calendar


In [23]: calendar.weekday(2017,6,24)
Out[23]: 5

Or I have set the Saturday to be the firstday of the week https://docs.python.org/2/library/calendar.html is there a way to loop for all firstdayofweeks in year and return dates out that way?

Not sure how to get all dates in the year as an object for iteration though. The calendar iter items end at months https://docs.python.org/2/library/calendar.html#calendar.Calendar.itermonthdays

In [20]: calendar.setfirstweekday(calendar.SATURDAY)

In [21]: calendar.firstweekday()
Out[21]: 5

Cheers

Sayth



More information about the Python-list mailing list