The world’s leading publication for data science, AI, and ML professionals.

If Python DateTime Can’t Help, Try Calendar Module

Use the calendar lib in Python to fill the gaps in the datetime module

Photo by MaeM on Pixabay
Photo by MaeM on Pixabay

If you’ve ever used Python Programming language, I’m sure that you must have used the datetime module, or maybe you have already nailed it. Indeed, the datetime module can be one of the representatives of "Pythonic" as an important Python built-in library. Its sub-module timedelta is one of my favourites for its creativity.

5 Cold Knowledge Points About Python Timedelta

However, the datetime module has some limitations by design which makes it less convenient sometimes. This is totally fine because there are a large number of built-in libraries in Python and each of them will have its own concentration. In this article, I’ll introduce the calendar module that will fill some gaps in the datetime module.

A Simple Example

Photo by valentinsimon0 on Pixabay
Photo by valentinsimon0 on Pixabay

The datetime module has been designed to focus on the basic date and time object and hence it handles the "even" date/time units such as seconds, hours and days. Have you noticed that there are no "months"?

For example, we have a datetime object t1 and we want to add 1 day to it. This will be very easy because 1 day = 24 hours = 86400 seconds, no matter which day.

t1 + timedelta(days=1)

However, what if we want to add 1 month to it? There are several problems that prevent us to solve this problem within the scope of the datetime module.

  1. The number of days in a month is variance (28, 29, 30 or 31 days)
  2. "The same day of the next month" might not exist, such as the date Jan 30, 2021 (there is no Feb 30, 2021)

Therefore, when we need to solve any problems that are particularly related to the calendar, the datetime module is quite limited or inconvenient. In this case, do NOT re-invent the wheels by defining the calendar rules using datetime, just use the calendar module which is also built-in to Python.


Import the Calendar Module

There are many features that are provided by the Calendar module in Python. Let’s go through some of the typical ones that will be very useful. Of course, we need to import the module before everything.

import calendar as cal

Locale Specific Calendar

Photo by jarmoluk on Pixabay
Photo by jarmoluk on Pixabay

When we mention the Calendar, it must come with locales. That is, different country/culture/language will have different definitions. This is handled by Python very well. The locale information will be decided by the operating system.

Using the calendar module, we can easily get this information.

  • day_name – day of week
  • day_abbr – abbreviation of day of week
  • month_name – month names
  • month_abbr – abbreviation of the month names

Here are some examples to list these arrays.

The reason why the first element of month_name and month_abbr is empty is for convenience purposes. For example, we can intuitively get the name of the 1st month by month_name[1] rather than using the index 0.

Now, let’s have a look at the tricks in the Calendar module.

Leap Years

Photo by mohamed_hassan on Pixabay
Photo by mohamed_hassan on Pixabay

One of the difficult things when dealing with the calendar is to decide whether a year is a leap year. This is as simple as calling a function and pass the year as the argument.

cal.isleap(2020)

If we want to know how many leap years in a range of year, we can use the leapdays() function.

cal.leapdays(2000, 2020)

Don’t be confused by the name of the function. In fact, the date Feb 29 is called the leap day. Therefore, only the leap year will have the leap day. Consequently, the number of leap years = the number of leap days.

Month Calendar

Photo by vkaresz72 on Pixabay
Photo by vkaresz72 on Pixabay

By using the function monthcalendar(), we can get a 2D list with all the days in a month. For example, the April of 2021 looks like this.

cal.monthcalendar(2021, 4)

Have you noticed that the sub-lists are guaranteed to have 7 elements? Yes, for each of the sub-lists, the indexes represent the day of weeks. That is, index 0 indicates Monday and 6 indicates Sunday (by default).

Why is this useful?

Let me give you an example. Can you list all the Mondays in the April of 2021?

[week[0] for week in cal.monthcalendar(2021, 4) if week[0] != 0]

There will be more creative ways of using this month calendar. Just go find them yourself 🙂

Month Range & Day of Week Query

Photo by Amber_Avalona on Pixabay
Photo by Amber_Avalona on Pixabay

Another simple but useful function is the monthrange() function. Given a certain month, it will return a tuple with

  1. Day of week for the first day of the month
  2. Total number of days in the month

For example, we can get the above information for the April of 2021 by simply calling cal.monthrange(2021, 4).

We can also query the day of week for a certain day by calling the weekday() function as follows.

cal.weekday(2021, 4, 4)

If we want to convert it into something more readable, simply use the locale array.

cal.day_name[cal.weekday(2021, 4, 4)]

Show Calendar

Photo by tigerlily713 on Pixabay
Photo by tigerlily713 on Pixabay

We can even use the Calendar module to print a "Calendar" in Python. This is extremely simple. We just need to call the calendar() function and pass in the year as follows.

year = cal.calendar(2021)
print(year)

We can also control the display style of this calendar by three parameters

  • c: the padding between months
  • w: the padding between days
  • l: the padding between weeks (rows)
year = cal.calendar(theyear=2021, w=3, l=1, c=8)
print(year)

Instead of displaying a calendar for an entire year, we can also display a calendar for a particular month. The parameters are exactly the same.

cal.prmonth(2021, 4, w=3, l=2)

Summary

Photo by kaboompics on Pixabay
Photo by kaboompics on Pixabay

In this article, I have introduced the calendar module that is built-in to Python. Most of the time we can use the datetime module to solve any date or time-related problems. When the calendar is involved, the datetime module might meet its shortage because it is not designed for these kinds of problems.

The calendar module is very convenient when we are dealing with some calendar specific problems such as the leap year. By using such built-in modules, the development in Python will be even faster!

Join Medium with my referral link – Christopher Tao

If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)


Related Articles