Get Third Sunday of The Month
Sometimes you have to rely on a routine to reliably provide dates. In this example I want to know for certain what the third Sunday of every month is. Could be various reasons but mostly for me it is to predict maintenance windows or use during scripting for automation.
$ cat /tmp/thirdweek.py from datetime import date, timedelta def allsundays(year): d = date(year, 1, 1) # January 1st d += timedelta(days = 6 - d.weekday()) # First Sunday while d.year == year: yield d d += timedelta(days = 7) def SundaysInMonth(year,month): d = date(year,month,1) # First day of the month d += timedelta(days = 6 - d.weekday()) # First Sunday while d.year == year and d.month == month: yield d d += timedelta(days = 7) def xSundayOfMonth(x,Sundays): i=0 for Sunday in Sundays: i=i+1 if i == x: #print "%s - %s" % (i,Sunday) return Sunday print "All Sundays in Year" for d in allsundays(2016): print d print "All Third Sundays in Year" for month in range(1,13): Sundays=SundaysInMonth(2016,month) print xSundayOfMonth(3,Sundays)