Python gets last month and year

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

I tried (but this did not work) and it does not print July, but the number:

import datetime
now = datetime.datetime.now()
print now.year, now.month(-1)
+9
source share
5 answers
now = datetime.datetime.now()
last_month = now.month-1 if now.month > 1 else 12
last_year = now.year - 1

to get the name of the month that you can use

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

If you are manipulating dates, then the dateutil library is always great to have the convenience that Python stdlib does not cover easily.

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'
+19
source
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
+1

, Pandas, , (). strftime.

import datetime as dt
import pandas as pd

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

Python .

:

  • 1, .
  • Doing - timedelta (days = 1) .
  • format and use "% B% Y" to convert to the desired format.
import datetime as dt
format(dt.date.today().replace(day=1) - dt.timedelta(days=1), '%B %Y')
>>>'June-2019'
0
source

Source: https://habr.com/ru/post/1650341/


All Articles