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

Chris Angelico rosuav at gmail.com
Tue Jun 27 23:07:42 EDT 2017


On Wed, Jun 28, 2017 at 12:48 PM, Sayth Renshaw <flebber.crue at gmail.com> wrote:
> 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



More information about the Python-list mailing list