excelpython-3.xexcel-formulapython-datetime

Equivalent of Excel's Weeknum function in Python


I am working on automating a report which is presently handled in Excel. As part of this, I wanted a Python equivalent of Excel's Weeknum function (Using System 1. Reference here ) which considers the week having 1st Jan as Week 1.

PS: I already tried ISOCalendar but it gives a wrong week as its week starts from Monday. I also tried the strftime("%U") and it returns the same wrong number.

Can someone help on this?


Solution

  • Here is the pseudocode. You can make it into Python. You'll define a function Weeknum that takes a date d as its input and returns a number between 1 and 53. You will use the weekday function to determine how many days the first week is short. So if January 1 is on the first day of the week, the number of days short is 0. If January 1 is the last day of the week, the number of days short is 6. There are a few ways to do that, depending a little on how well the first day of the week maps on to the conventions of the weekday function. Worst case you can count the days of the first week by setting a counter to 1 and a date variable to January 1 of the year, and while the day of the date is not the last day of the week and one to the counter and to the date. Then the number of days short is 7 minus the counter. Get the number j between 1 and 366 for the day of the year of d. One way to do so is to take 1+ the difference in days between d and January 1 of the year of d. Then Weeknum should return (j+6+number of days short) div 7.

    EDIT: I wrote it up in Python

    import datetime
    def julian(d):#takes a date d and returns what day in the year it is 1..366
        jan1 = datetime.date(d.year,1,1)
        return 1+(d-jan1).days
    def daysInFirstWeekOfJanuary(y):
        #takes a year and says how many days there were in the first week of #january that year
        janDay = datetime.date(y,1,1)
        result = 1
        while (janDay.weekday()!=5):#until Saturday, change if you hold Sunday is not the first day of the week
            result=result+1
            janDay=janDay+datetime.timedelta(days=1)
        return result
    def daysShortInFirstWeekOfJanuary(y):
        return 7-daysInFirstWeekOfJanuary(y)
    def weeknum(d):#takes a date and returns the week number in the year
    #where Jan 1 of the year is the start of week 1, and the following Sunday starts week 2
         return(julian(d)+6+daysShortInFirstWeekOfJanuary(d.year)) // 7