Monday 3 January 2022

Introduction to the Python Calendar Module

 The Calendar module is built into Python 3. But for some reason it is installed by default.

We can install it to 

- Windows Administrator using :

pip install calendar

- For Linux or macOS : 


sudo pip install calendar

After the Calendar module is imported , 

Launch Python 3 and enter,

import calendar

Now the module is called and it inherits its functions.



Lets see how we can use the Calendar module...


1. Displaying a month in wall calendar fashion.


jan =calendar.TextCalendar(calendar.MONDAY)
jan.prmonth(2022,1)

The 1st month of the year 2022 is printed below.






2. Displaying the number of leap years between two specific years.


leaps = calendar.leapdays(1900,2019)
print("There are",leaps,"leap years betweeen 1900 and 2019")


So there are 29 leap years between 1900 and 2019 





3. Displaying a whole year calendar.



year = int(input("Enter a year : "))
print(calendar.prcal(year))

For the input I entered 2022 , so the whole 2022 calendar is printed.





4. Printing the individual months.


for name in calendar.month_name:
    print(name)








5. Printing the individual days.


for name in calendar.day_name:
    print(name)









6. The Calendar module also allows us to write the functions in HTML, so that you can display it on a website. Let's start by creating a new file , 


year = int(input("Enter the year to be displayed :"))
cal = open("/Users/oneth/Work/CODES/cal.html","w")
cal.write(calendar.HTMLCalendar(calendar.MONDAY).formatyear(year))
cal.close()

Now a HTML file is created at the given location , the output will look like this .






1 comment:

Introduction to the Python Calendar Module

 The Calendar module is built into Python 3. But for some reason it is installed by default. We can install it to  - Windows Administrator u...