Author -  Sai gowtham

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)

Output:

3

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 [] syntax.

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])

Output:

'March'

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 -1.

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.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY