Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: third Friday of a month

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 using Python 2.7.

For example, these dates can help you better understand my problem. Have a yearly calendar at hand.

  • input ---> output
  • 'Jan 18, 2013' ---> True
  • 'Feb 22, 2013' ---> False
  • 'Jun 21, 2013' ---> True
  • 'Sep 20, 2013' ---> True

I just want to use standard classes provided by the language, like time, datetime, calendar, etc.

I have looked into some answers but I see calculations like addidng/substracting 86400 seconds for every day or even doing comparisons depending on the number of days that a month has. IMHO these are wrong because the libreries in Python already take care of these details so there is no need to reinvent the wheel. Also calendars and dates are complex: leap years, leap seconds, time zones, week numbers, etc. so I think is better to let the libraries solve these tricky details.

Thanks in advance for your help.

like image 994
Juan Catalan Avatar asked Aug 25 '13 00:08

Juan Catalan


1 Answers

This should do it:

from datetime import datetime 

def is_third_friday(s):
    d = datetime.strptime(s, '%b %d, %Y')
    return d.weekday() == 4 and 15 <= d.day <= 21

Test:

print is_third_friday('Jan 18, 2013')  # True
print is_third_friday('Feb 22, 2013')  # False
print is_third_friday('Jun 21, 2013')  # True
print is_third_friday('Sep 20, 2013')  # True
like image 142
elyase Avatar answered Oct 22 '22 03:10

elyase