[Tutor] how to get the weeks of a month

Alan Gauld alan.gauld at yahoo.co.uk
Mon Mar 4 14:19:50 EST 2019


On 04/03/2019 18:54, john fabiani wrote:

> I need to print out the weeks of the month - given any month and any year.
> 

I'm not totally clear how you define a week.

In your example the first week starts on Friday
and ends on Sunday.

Subsequent weeks start on Monday and run to Sunday.

So, is a week essentially a variable number of days
prior to a Sunday?

What do you do if a month ends on a Thursday,
say? How is the last week printed?
EDIT: OK I see the comment at the end now.

> For example this month would have:
> 
> 3/1/2019 - 3/3/2019   # notice that this a short week
> 3/4/2019 - 3/10/2019
> 3/11/2019 - 3/17/2019
> 3/18/2019 - 3/24/2019
> 3/25/2019 - 3/31/2019  # also this can be a short week as in April 2019 
> last week would be 4/29/2019 - 4/30-2019

So what I think you want is to

start with the first day and print each day up to Sunday.
Newline
print the current date up to sunday
newline
repeat until you run out of days in the month.

datetime has functions for extracting the date,
the day and the month It also has functions for
formatting the date string.

Or you could use calendar to matrix
representation of the month.

>>> import calendar as cal
>>> cal.monthcalendar(2019,3)
[[0, 0, 0, 0, 1, 2, 3], [4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16,
17], [18, 19, 20, 21, 22, 23, 24], [25, 26, 27, 28, 29, 30, 31]]
>>>

That looks close to what you want?


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list