<tutorialjinni.com/>

List of Months in Python

Posted Under: Python, Tutorials on Oct 4, 2023
List of Months in Python
One of the common tasks in data handling or manipulation, especially dealing with time series data, is to generate a list of months. In this tutorial, we will learn how to create a list of months in Python using multiple methods.

Using List

The simplest way to create a list of months is by manually defining a list. This method doesn't require any special modules and can be done quickly if you just need a simple list of months.
months_list = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

Using Calendar Module

Python's standard library includes the 'calendar' module which contains many useful functions related to the calendar, including a way to generate a list of month names.
import calendar
months_list = [calendar.month_name[i] for i in range(1, 13)]
In this code snippet, we are using list comprehension to generate the list of months. calendar.month_name is an array that contains the month names where index 0 is an empty string and index 1 to 12 correspond to the months.

Generate Abbreviated Month Names

Not only can we generate the full names of months, but the 'calendar' module also allows us to generate abbreviated month names which are often useful for display purposes or where full month names are too long.

import calendar
months_abbr = [calendar.month_abbr[i] for i in range(1, 13)]

In this code snippet, similar to the previous technique, we are using the 'month_abbr' function from the 'calendar' module which returns an array of abbreviated month names.

Generate List of Months with Locale

import calendar
import locale

# set the locale to French
#locale.setlocale(locale.LC_TIME, "fr_FR")
# set the locale to German
locale.setlocale(locale.LC_TIME, "de_DE")

months_list = [calendar.month_name[i] for i in range(1, 13)]

print (months_list)

#output= ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember']
In the code snippet above, we first set the locale to German using the 'setlocale' function of the 'locale' module and then generate the list of months which will now be in German.


imgae