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:')) 
if(isleap(y)): 
   print(y, ' is leap year') 
else: 
   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) 
print(str)

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

mc={1:0,2:3,3:3,4:6,5:1,6:4,7:6,8:2,9:5,10:0,11:3,12:5}
cc={1500:0,1600:6,1700:4,1800:2,1900:0,2000:6,2100:4,2200:2}
wc={0:'Sunday',1:'Monday',2:'Tuesday',3:'Wednesday',4:'Thursday',5:'Friday',6:'Saturday'}
dd,mm,yyyy=[int(x) for x in input("Enter Date in dd/mm/yyyy format: ").split('/')]
cen=cc[yyyy-(yyyy--100)]
year=yyyy--100
leap=year//4
mon=mc[mm]
tot=cen+year+leap+mon+dd
print(wc[tot--7])