Get the previous months name

By: Varghese Chacko 1 year, 2 months ago

Often we need to get previous months name in python, especially, when we have to save report from previous month's name. In python its is pretty simple. 

1. Get first day of  month by first getting today's date and then move the object's date to 1st day of month.

first_day_of_this_month = date.today().replace(day=1)

2. The day before the first day of month iscertainly isthe previous month. So less a date from first day of month.

last_day_prev_month = first_day_of_this_month –timedelta(days=1) 

3. Get the month name from thedate

prev_month_name = last_day_prev_month.strftime(“%B”)

Putting all together

from datetime import date, timedelta

first_day_of_this_month = date.today().replace(day=1) 

last_day_prev_month = first_day_of_this_month –timedelta(days=1) 

prev_month_name = last_day_prev_month.strftime(“%B”) 

print prev_month_name