Python: Number of the Week in a Month

前端 未结 9 589
庸人自扰
庸人自扰 2020-12-03 18:26

When specifying a date:

datetime.datetime(2011, 8, 15)

How can i get to know that this is the third week of the month?

What if I wa

相关标签:
9条回答
  • 2020-12-03 18:43
    testdate = datetime.datetime(2011, 2, 28)
    weekofmonth = (testdate.day+7-1)/7
    

    In general to find the ceiling of division: ceiling of (x/y) = (x+y-1)/y

    0 讨论(0)
  • 2020-12-03 18:50

    How about this. We give the date that we wish to find the week for. We reset the date to the first day of the month in a new variable. We then create the week in the year for both the first day and our given date. Subtract the first isoweek from the given date's isoweek and add one. You add one to correct the zero index number. This should give the week number in the month.

    import datetime
    
    def _get_week_of_day(date):
        first_day = date.replace(day=1)
        iso_day_one = first_day.isocalendar()[1]
        iso_day_date = date.isocalendar()[1]
        adjusted_week = (iso_day_date - iso_day_one) + 1
        return adjusted_week
    
    0 讨论(0)
  • 2020-12-03 18:53

    Maybe http://labix.org/python-dateutil will help.

    Other than that it's just math.

     from datetime import datetime, timedelta
    
        def week_of_month(date):
            month = date.month
            week = 0
            while date.month == month:
                week += 1
                date -= timedelta(days=7)
    
            return week
    
    0 讨论(0)
  • 2020-12-03 18:54

    Check answer here: https://stackoverflow.com/a/64192858/6089311

    import pandas as pd
    
    def weekinmonth(dates):
        """Get week number in a month.
        
        Parameters: 
            dates (pd.Series): Series of dates.
        Returns: 
            pd.Series: Week number in a month.
        """
        firstday_in_month = dates - pd.to_timedelta(dates.dt.day - 1, unit='d')
        return (dates.dt.day-1 + firstday_in_month.dt.weekday) // 7 + 1
        
    
    df = pd.DataFrame(pd.date_range(' 1/ 1/ 2000', periods = 100, freq ='D'), columns=['Date'])
    weekinmonth(df['Date'])
    
    0 讨论(0)
  • 2020-12-03 18:56

    This (somewhat clumsy) example, using the calendar module ...

    import calendar
    import datetime
    
    def week(dt):
        mth = calendar.monthcalendar(dt.year, dt.month)
        for i, wk in enumerate(mth):
            if dt.day in wk:
                return i + 1
    
    calendar.setfirstweekday(calendar.MONDAY)
    
    week(datetime.datetime(2011, 8, 15)) # 3
    week(datetime.datetime(2011, 2, 28)) # 5
    week(datetime.datetime(2011, 8, 29)) # 5
    

    ... gets the answer wrong for 2011-02-28, based on the OP's expectation, unless weeks start on Tuesday.

    0 讨论(0)
  • 2020-12-03 18:56

    To take into account the comment of @Usagi:

    datetime.datetime(2011, 8, 15) // should return 3
    datetime.datetime(2011, 2, 28) // should return 5
    datetime.datetime(2011, 8, 29) // should return 5
    

    The following equation manage that the first day of a month is not necessary a monday:

    (d.day-d.weekday() -2)//7+2
    

    The -2 and +2 allow to get a week number between 1 and 6

    0 讨论(0)
提交回复
热议问题