[Django]-How to find all week numbers that are first week of month in a year python

1πŸ‘

βœ…

I’ve done a loop through the months, then got the first Sunday (starting at month’s 1st and moving to the next day until a Sunday is found), then got the week-of-year of the date found:

from datetime import datetime
from datetime import date

# dayofweek: Sunday=0, Monday=1 and so on
def get_week_number(year=2017, dayofweek=0):
    weeks = []

    for month in range(1, 13):
        # get first Sunday of month
        d = date(year, month, 1)
        while(d.weekday() != dayofweek):
            d = d.replace(day=d.day + 1)

        # isocalendar()[1] is the week-of-year field
        weeks.append(d.isocalendar()[1])

    return weeks

print(get_week_number(2017, 0))

The result, though, is different from what you expect:

[1, 6, 10, 14, 18, 23, 27, 32, 36, 40, 45, 49]

I also tried with weeks.append(int(d.strftime("%W"))) but it gives the same results – I’m using Python 3.5.2 and a week is defined as:

The ISO year consists of 52 or 53 full weeks, and where a week starts on a Monday and ends on a Sunday. The first week of an ISO year is the first (Gregorian) calendar week of a year containing a Thursday. This is called week number 1, and the ISO year of that Thursday is the same as its Gregorian year.

πŸ‘€user7605325

2πŸ‘

(Edited, because of error in weekday numbering)

>>> import datetime
>>> june1 = datetime.datetime(2017,6,1)
>>> june1
datetime.datetime(2017, 6, 1, 0, 0)
>>> june1_weekday = june1.weekday()
>>> if june1_weekday < 6:  # 6 indicates Sunday
        first_sunday_in_june = june1 + datetime.timedelta(days=6-june1_weekday)
else:
        first_sunday_in_june = june1


>>> print(first_sunday_in_june)
2017-06-04 00:00:00

Assuming you want ISO weeknumbers, you can then use the isocalendar() method. This gives a tuple (year, weeknumber, weekday). This uses the convention that weeks start with Monday, and the first week of the year is the first week with at least four days in the year (or in other words, the week with the first Thursday).

>>> first_sunday_in_june.isocalendar()
(2017, 22, 7)

If you have another convention for first-day-of-the-week or first-week-of-the-year, you will have to brew your own function to get the week number.

Use the above method in a loop over the months, and you can create the desired list with week numbers.

πŸ‘€Ruud de Jong

Leave a comment