Python Calendar Module

The 'calendar' module is useful to create calendar for any month or year.This module is also useful to know whether a given year is leap year or not.The isleap() function of calendar module is useful for this purpose.

Calendar Module

Python Program to find a leap year
CopiedCopy Code

#to test whether leap year or not
from calendar import * 
y = int(input('Enter year:')) 
   print(y, ' is leap year') 
   print(y, ' is not leap')

The 'calendar ' module has 'month' function that is useful to display calendar for a specific month. For example, to display a calendar for the May month of year 2016, we can use this function as:

str = month(2016, 5) #return calendar for May 2016

The string 'str' returned by this month() function contains the calendar which can be displayed using print() function.

Calendar Module month and year display

Python Program to display Calendar for a Specific Month and Year
CopiedCopy Code

#to display calendar of given month of the year 
from calendar import * 
#ask for month and year 
yy = int(input("Enter year:")) 
mm = int(input("Enter month:")) 
#display the calendar for that month 
str = month(yy,mm) 

If we want to display a calendar for all the months of an entire year, we can use calendar() function of 'calendar ' module.This function returns the calendar as a string with several lines and is used in the following format:

calendar(year, w=2, l=1, c=6, m=3)

Here, 'year' represents the year number for which the calendar is needed. 'w' represents the width between two columns. Its default value is 2. 'l' represents the blank lines between two rows. Its default value is 1. 'c' represents column-wise space between two months. Its default value is 6. 'm' represents the number of months to be displayed in a row. Its default value is 3. Of course, the values of 'w', 'l', 'c' and 'm' are not compulsory.

Calendar Module useful examples

Python program to display the calendar for all months of a given year

CopiedCopy Code

#to display calendar for entire year 
from calendar import * 
year = int(input('Enter year:')) 
print(calendar(year, 2, 1, 8, 3))

Python Program to display dates of yesterday, today and tomorrow

CopiedCopy Code

from datetime import *
today =
yesterday = today - timedelta(days = 1)
tomorrow = today + timedelta(days = 1) 
print('Yesterday : ',yesterday)
print('Today : ',today)
print('Tomorrow : ',tomorrow)

Python Program to display week day based on input date without using any module

CopiedCopy Code

dd,mm,yyyy=[int(x) for x in input("Enter Date in dd/mm/yyyy format: ").split('/')]