user3580316 user3580316 - 4 months ago 10
Python Question

Python get last month and year

I am trying to get last month and current year in the format: July 2016.

I have tried (but that didn't work) and it does not print July but the number:

import datetime
now = datetime.datetime.now()
print now.year, now.month(-1)

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