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.
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.
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