[Tutor] how to get the weeks of a month

john fabiani johnf at jfcomputer.com
Mon Mar 4 17:12:39 EST 2019



On 3/4/19 1:35 PM, David Rock wrote:
>> On Mar 4, 2019, at 15:28, john fabiani <johnf at jfcomputer.com> wrote:
>>
>> I knew there was a simple why to get it done!  But where is it off my a day?
>>
> comparing
>
> $ cal
>       March 2019
> Su Mo Tu We Th Fr Sa
>                  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
>
> to
>
> 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]]
>
> I see the first element of the array is
> [0, 0, 0, 0, 1, 2, 3]
>
> where I would have expected
> [0, 0, 0, 0, 0, 1, 2]
>
> Which I’m sure is just a question of “defining the start of the week” properly, but if you just took it as-is, Mar 1 would be Thursday, not Friday if you translated literally.
>
>
>> David Rock
> david at graniteweb.com
My understanding is - a week starts on Monday and ends on Sunday. So 
that looks correct.  Below I use a max function but I wonder if I should 
use a min function too.  Recall I am looking for the string of the dates 
for the week.

Here is my code:
import datetime
import calendar


#get the weeks of a month to get the dates to display
tday = datetime.datetime(2020,03,01)

weeksInMonth =calendar.monthcalendar(tday.year, tday.month)
lastdayof1stweek = weeksInMonth[0][6]
firstweek = tday.strftime("%m-%d_%Y")+ " - "+ 
datetime.datetime(tday.year, tday.month, 
lastdayof1stweek).strftime("%m-%d-%Y")
print firstweek
for i in range(len(weeksInMonth)):
     if i == 0:
         continue
     firstday = weeksInMonth[i][0]
     lastday =  max(weeksInMonth[i])
     weekstr = datetime.datetime(tday.year, tday.month, 
firstday).strftime("%m-%d-%Y") + ' - ' + datetime.datetime(tday.year, 
tday.month, lastday).strftime("%m-%d-%Y")
     print weekstr

def max(arr):
     max_ = arr[0]
     for item in arr:
         if item > max_:
             max_ = item
     return max_


More information about the Tutor mailing list