Calendar Functions in Python | Set 1( calendar(), month(), isleap()…)


Handling date through some type of in-built calendar is central to any programming language. Here we see how to handle various date related functions available in python’s in-built library.

firstweekday()

Using this function we find the number assigned to the first day of the week.

Example

 Live Demo

import calendar

# print starting day number
print("The number of the first day in calendar is : ")
print(calendar.firstweekday())

Output

Running the above code gives us the following result −

The number of the first day in calendar is :
0

leapdays(StartYear, EndYear)

This function is used to calculate the number of leap days between two given years.

Example

 Live Demo

import calendar
print("The number of leap days between 1980 and 2015:")
print (calendar.leapdays(1980, 2015))

Output

Running the above code gives us the following result −

The number of leap days between 1980 and 2015:
9

HTMLCalendar

This function allows you to print HTML formatted calendar for a month.

Example

 Live Demo

import calendar
hc = calendar.HTMLCalendar(calendar.TUESDAY)
a = hc.formatmonth(2019, 3)
print(a)

Output

Running the above code gives us the following result −

<table border="0" cellpadding="0" cellspacing="0" class="month"> 
<tr><th colspan="7" class="month">March 2019</th></tr> 
<tr><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th>
<th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th><th class="mon">Mon</th></tr> 
<tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td>
<td class="fri">1</td><td class="sat">2</td><td class="sun">3</td><td class="mon">4</td></tr> 
<tr><td class="tue">5</td><td class="wed">6</td><td class="thu">7</td><td class="fri">8</td>
<td class="sat">9</td><td class="sun">10</td><td class="mon">11</td></tr> <tr><td class="tue">12</td>
<td class="wed">13</td><td class="thu">14</td><td class="fri">15</td><td class="sat">16</td>
<td class="sun">17</td><td class="mon">18</td></tr> <tr><td class="tue">19</td><td class="wed">20</td>
<td class="thu">21</td><td class="fri">22</td><td class="sat">23</td><td class="sun">24</td>
<td class="mon">25</td></tr> <tr><td class="tue">26</td><td class="wed">27</td><td class="thu">28</td>
<td class="fri">29</td><td class="sat">30</td><td class="sun">31</td><td class="noday">&nbsp;</td>
</tr></table>
raja
Published on 23-Aug-2019 14:25:41
Advertisements