Python: third Friday of a month

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

    you can use something like this to get third fridday of the month (current month), and then simply compare that third_friday with your day (by year, month, day)

    from datetime import datetime, timedelta
    import calendar
    
    now = datetime.now()
    first_day_of_month = datetime(now.year, now.month, 1)
    first_friday = first_day_of_month + timedelta(days=((4-calendar.monthrange(now.year,now.month)[0])+7)%7)
    # 4 is friday of week
    third_friday = first_friday + timedelta(days=14)
    

    Hope this helps.

提交回复
热议问题