pythontimeweek-number

How do I get the week number of the month?


Does Python offer a way to directly get the current week of the month (e.g., from 1 to 4)?

I'm accessing an Oracle DB with cx_Oracle and trying to optimize the computation time passing queries already with the month and week of the month(the table is partitioned by month and subpartitioned by week of the month, which John Machin's comment link has a definition as: "WEEK_OF_MONTH field range from .. 1 to .. 5")

This is to avoid using PARTITION_KEY = ((TO_CHAR(SYSDATE, 'MM'))-1) and SUBPARTITION_WEEK = TO_NUMBER(TO_CHAR(SYSDATE, 'W')) as that would invalidate the index use. Passing the query with the correct numbers allows using the indexes.


Solution

  • In order to use straight division, the day of month for the date you're looking at needs to be adjusted according to the position (within the week) of the first day of the month. So, if your month happens to start on a Monday (the first day of the week), you can just do division as suggested above. However, if the month starts on a Wednesday, you'll want to add 2 and then do the division. This is all encapsulated in the function below.

    from math import ceil
    
    def week_of_month(dt):
        """ Returns the week of the month for the specified date.
        """
    
        first_day = dt.replace(day=1)
    
        dom = dt.day
        adjusted_dom = dom + first_day.weekday()
    
        return int(ceil(adjusted_dom/7.0))