Nov-12-2020, 12:35 AM
(This post was last modified: Nov-12-2020, 12:35 AM by chrischarley.)
(Nov-11-2020, 08:32 PM)cananb Wrote: Hi everyone, I just started how to learn to code.
I am trying to write a program that should count the days an athlete decides to run once every three days for the whole year
(On the 1st, 4th, 7th ... day of each month).
At the beginning of a new month, he always runs on the 1st day of the month, even if three days have not passed since his last run.
for x in range(1,32,3): print(x)This is the code I wrote for counting every three days but I couldn't find a solution for how to add the first days of months.
A little help with this would be perfect.
Here is an approach using the calendar and datetime modules. Both these modules come with the Python installation.
monthrange returns the day_of_week (here ignored by assigning to '_') and the last day number of the month.
A date is created with
date(yr, month, day)
and the strftime
method produces day_of_week, Month abbr., day_number and the year. from calendar import monthrange from datetime import date yr = 2020 for month in range(1,13): _, last_day = monthrange(yr,month) for day in range(1, last_day+1, 3): print(date(yr, month, day).strftime('%a %b %d %Y'))This outputs:
Output:Wed Jan 01 2020
Sat Jan 04 2020
Tue Jan 07 2020
Fri Jan 10 2020
Mon Jan 13 2020
Thu Jan 16 2020
Sun Jan 19 2020
Wed Jan 22 2020
Sat Jan 25 2020
Tue Jan 28 2020
Fri Jan 31 2020
Sat Feb 01 2020
Tue Feb 04 2020
Fri Feb 07 2020
Mon Feb 10 2020
Thu Feb 13 2020
Sun Feb 16 2020
Wed Feb 19 2020
Sat Feb 22 2020
Tue Feb 25 2020
Fri Feb 28 2020
...
Sun Nov 01 2020
Wed Nov 04 2020
Sat Nov 07 2020
Tue Nov 10 2020
Fri Nov 13 2020
Mon Nov 16 2020
Thu Nov 19 2020
Sun Nov 22 2020
Wed Nov 25 2020
Sat Nov 28 2020
Tue Dec 01 2020
Fri Dec 04 2020
Mon Dec 07 2020
Thu Dec 10 2020
Sun Dec 13 2020
Wed Dec 16 2020
Sat Dec 19 2020
Tue Dec 22 2020
Fri Dec 25 2020
Mon Dec 28 2020
Thu Dec 31 2020