23

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)

8 Answers8

38

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'
John R Perry
  • 3,916
  • 2
  • 38
  • 62
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
24
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]
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
5

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'
Alexander
  • 105,104
  • 32
  • 201
  • 196
3
from datetime import date, timedelta

last_month = date.today().replace(day=1) - timedelta(1)             
last_month.strftime("%B %Y")

date.today().replace(day=1) gets the first day of current month, substracting 1 day will get last day of last month

seasee my
  • 99
  • 7
  • use `date.today().replace(day=1) ` can replace current day to 1st day, just the first day of current month, then minus one day and you can get the last day of last month. – seasee my Sep 10 '20 at 06:10
2

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'
zankalp
  • 47
  • 3
1
def subOneMonth(dt):
   day = dt.day
   res = dt.replace(day=1) - datetime.timedelta(days =1) 
   try:
     res.replace(day= day)
   except ValueError:
     pass
   return res

print subOneMonth(datetime.datetime(2016,07,11)).strftime('%d, %b %Y')
11, Jun 2016
print subOneMonth(datetime.datetime(2016,01,11)).strftime('%d, %b %Y')
11, Dec 2015
print subOneMonth(datetime.datetime(2016,3,31)).strftime('%d, %b %Y')
29, Feb 2016
galaxyan
  • 5,944
  • 2
  • 19
  • 43
1
from datetime import datetime, timedelta, date, time
#Datetime: 1  month ago
datetime_to = datetime.now().replace(day=15) - timedelta(days=30 * 1) 
#Date    : 2  months ago
date_to     = date.today().replace(day=15)   - timedelta(days=30 * 2) 
#Date    : 12 months ago
date_to     = date.today().replace(day=15)   - timedelta(days=30 *12) 
#Accounting standards: 13 months ago of pervious day
date_ma = (date.today()-timedelta(1)).replace(day=15)-timedelta(days=30*13)
yyyymm = date_ma.strftime('%Y%m') #201909
yyyy = date_ma.strftime('%Y')     #2019

#Error Range Test
from datetime import datetime, timedelta, date, time
import pandas as pd
for i in range(1,120):
    pdmon = (pd.Period(dt.datetime.now(), 'M')-i).strftime('%Y%m')
    wamon = (date.today().replace(day=15)-timedelta(days=30*i)).strftime('%Y%m')
    if pdmon != wamon:
        print('Incorrect %s months ago:%s,%s' % (i,pdmon,wamon))
        break
#Incorrect 37 months ago:201709,201710
0

import datetime as dt

  • .replace(day=1) replaces today's date with the first day of the month, simple
  • subtracting timedelta(1) subtracts 1 day, giving the last day of the previous month last_month = dt.datetime.today().replace(day=1) - dt.timedelta(1)
  • user wanted the word July, not the 6th month so updating %m to %B last_month.strftime("%Y, %B")
tahoe
  • 139
  • 1
  • 6