Python: third Friday of a month

后端 未结 5 1570
被撕碎了的回忆
被撕碎了的回忆 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:41

    This is the nicest I've found so far.

    from datetime import date
    from dateutil.relativedelta import relativedelta, FR
    
    def get_third_fri_of_mth(dt):
        print (dt + relativedelta(day=1, weekday=FR(3)))
    
    get_third_fri_of_mth(date(2019, 1, 30))
    get_third_fri_of_mth(date(2019, 6, 4))
    

    Relative delta replaces the day in the date you specify by day = 1. From this new date, weekday=FR(3) specifies the 3rd friday.

提交回复
热议问题