How to get the previous month name in Python
In this tutorial, we are going to learn about how to get the previous month name using the current date in Python.
Python has a datetime module which helps us to deal with date object and timestamps, etc.
Getting the previous month name
To get the previous month name in Python, first we need to access the current date object using the
datetime.now() method which available in datetime module.
from datetime import datetime currentDate = datetime.now() # returns current date time
Now, we need to subtract the current month with
-1 to get the previous month.
from datetime import datetime currentDate = datetime.now() previousMonth = currentDate.month -1 if currentDate.month > 1 else 12 print(previousMonth)
In the above example, we have subtracted the currentDate.month -1. where it returns the previous month in number format.
To convert it to the name format, first we need to create a months list and access it by using the square brackets
Here is an example:
from datetime import datetime currentDate = datetime.now() previousMonth = currentDate.month -1 if currentDate.month > 1 else 12 months_list = ['January','February','March','April','May','June','July','August', 'September','October','November','December'] print(months_list[previousMonth -1])
In the above code at the last line, we are subtracting the
previousMonth-1 because in python lists are zero based indexing, for that we are subtracting again with minus
Note: In Python lists are zero-indexed. so the first element is available at index 0 and negative indices counting back from the end of a list, so the index of
-1 is used to access the last element of a list.