Skip to content

Get third sunday of the month

wordpress meta

title: 'Get Third Sunday of The Month'
date: '2016-01-16T09:41:09-06:00'
status: publish
permalink: /get-third-sunday-of-the-month
author: admin
excerpt: ''
type: post
id: 931
category:
    - Automation
    - Python
tag: []
post_format: []

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)