python - Week number of the month

后端 未结 14 1334
忘掉有多难
忘掉有多难 2020-12-01 08:11

Does python offer a way to easily get the current week of the month (1:4) ?

相关标签:
14条回答
  • 2020-12-01 08:54

    Check out the python calendar module

    0 讨论(0)
  • 2020-12-01 08:55

    This should do it.

    #! /usr/bin/env python2
    
    import calendar, datetime
    
    #FUNCTIONS
    def week_of_month(date):
        """Determines the week (number) of the month"""
    
        #Calendar object. 6 = Start on Sunday, 0 = Start on Monday
        cal_object = calendar.Calendar(6)
        month_calendar_dates = cal_object.itermonthdates(date.year,date.month)
    
        day_of_week = 1
        week_number = 1
    
        for day in month_calendar_dates:
            #add a week and reset day of week
            if day_of_week > 7:
                week_number += 1
                day_of_week = 1
    
            if date == day:
                break
            else:
                day_of_week += 1
    
        return week_number
    
    
    #MAIN
    example_date = datetime.date(2015,9,21)
    
    print "Week",str(week_of_month(example_date))
    #Returns 'Week 4'
    
    0 讨论(0)
提交回复
热议问题