Python: third Friday of a month

后端 未结 5 1558
被撕碎了的回忆
被撕碎了的回忆 2021-01-31 21:24

I am a rookie python programmer and I need to write a script to check if a given date (passed as a string in the form \'Month, day year\') is the third Friday of the month. I am

5条回答
  •  囚心锁ツ
    2021-01-31 21:33

    Yet another way to accomplish this... using integer division...

    import datetime
    
    def is_date_the_nth_friday_of_month(nth, date=None):
        #nth is an integer representing the nth weekday of the month
        #date is a datetime.datetime object, which you can create by doing datetime.datetime(2016,1,11) for January 11th, 2016
    
        if not date:
            #if date is None, then use today as the date
            date = datetime.datetime.today()
    
        if date.weekday() == 4:
            #if the weekday of date is Friday, then see if it is the nth Friday
            if (date.day - 1) // 7 == (nth - 1):
                #We use integer division to determine the nth Friday
                #if this integer division == 0, then date is the first Friday, 
                # if the integer division is...
                #   1 == 2nd Friday
                #   2 == 3rd Friday
                #   3 == 4th Friday
                #   4 == 5th Friday
                return True
    
        return False
    

提交回复
热议问题