Find first Sunday of the month in Python

In this tutorial, we will talk about How to find the first Sunday of the month in Python. So in order to understand how this program works. We need to what Calendar function.

What is calendar in python?

Calendar module is used to provide additional functions related to the calendar. In default, Monday has considered as the first day of the week in integer it’s [0]and Sunday as the last day of the week[6].

Display calendar of given month

In the program below .we import the calendar module. The built-in function month is used to display month.

import calendar
yy=2017
mm=4
print(calendar.month(yy,mm))
Output:

 August 2019                                                

Mo Tu We Th Fr Sa Su                                           

         1  2 3   4                                           

 5  6 7  8  9 10  11                                           

12 13 14 15 16 17 18                                           

19 20 21 22 23 24 25                                           

26 27 28 29 30 31

Some known functions on Calendar

  • isleap()  – checks if it is leap year or not
  • weekday()- Returns the weekday number of the given date
  • month() – Use to print the month of a specific year
  • calendar() –  Displays year, number of lines per week.
  • pryear()- Use for printing the calendar for an entire year

 

Find the First Sunday (any day) of the month in Python

import calendar
cal= calendar.TextCalendar(calendar.SUNDAY)
print(cal.prmonth(2019,1)
print(calendar.SUNDAY)

Output:

  January 2019                                                       

Su Mo Tu We Th Fr Sa                                                   

       1  2  3  4  5                                                   

 6  7  8  9 10 11 12                                                   

13 14 15 16 17 18 19                                                   

20 21 22 23 24 25 26                                                   

27 28 29 30 31

  

6

As written on the code above Text calendar is used. Text calendar is used to display plain Text Calendar as the name already tells but Text calendar also allow you to edit the calendar as per your requirement. Instead of (Calendar.SUNDAY) you can search for any days as well with ease. And prmonth()  is used to print month’s calendar according to user input not necessary to use print for execution.

Also read:

One response to “Find first Sunday of the month in Python”

  1. defreturn says:

    What if one wants to print first sunday of past years, for example 1984 ?

Leave a Reply

Your email address will not be published. Required fields are marked *