Python get last month and year

now = datetime.datetime.now()
last_month = now.month-1 if now.month > 1 else 12
last_year = now.year - 1

to get the month name you can use

"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()[last_month-1]

An alternative solution using Pandas which converts today to a monthly period and then subtracts one (month). Converted to desired format using strftime.

import datetime as dt
import pandas as pd

>>> (pd.Period(dt.datetime.now(), 'M') - 1).strftime('%B %Y')
u'July 2016'

If you're manipulating dates then the dateutil library is always a great one to have handy for things the Python stdlib doesn't cover easily.

First, install the dateutil library if you haven't already:

pip install python-dateutil

Next:

from datetime import datetime
from dateutil.relativedelta import relativedelta

# Returns the same day of last month if possible otherwise end of month
# (eg: March 31st->29th Feb an July 31st->June 30th)
last_month = datetime.now() - relativedelta(months=1)

# Create string of month name and year...
text = format(last_month, '%B %Y')

Gives you:

'July 2016'

You can use just the Python datetime library to achieve this.

Explanation:

  • Replace day in today's date with 1, so you get date of first day of this month.
  • Doing - timedelta(days=1) will give last day of previous month.
  • format and use '%B %Y' to convert to required format.
import datetime as dt
format(dt.date.today().replace(day=1) - dt.timedelta(days=1), '%B %Y')
>>>'June-2019'