-3

I have a str variable which is my_variable = str(201705). I want to get the previous month of my_variable using datetime in python. Is there a method to accomplish this? So far I have:

from datetime import datetime
my_variable = str(201705)
month = datetime.strptime(my_variable, '%Y%m').strftime("%b%Y")

This gives me my current variables month in str format, so May2017. I want to get just the previous month stored in a new variable. So my_new_month would = April.

Is this possible using the python datetime library, and if not, is there another solution to accomplish this?

Dasax121
  • 23
  • 8

1 Answers1

1
from datetime import datetime, timedelta
my_variable = str(202102)
d1 = datetime.strptime(my_variable, '%Y%m')
days = d1.day
# use timedelta to subtract n+1 days from current datetime object
d2 = d1 - timedelta(days=days+1)
# get month of d2
print(d2.month)
taesu
  • 4,482
  • 4
  • 23
  • 41
  • is there any way to do this in 1 line of code? This also prints the month number, i need the actual month name to be printed – Dasax121 Feb 16 '21 at 21:46
  • d2 is a datetime object. You can do whatever you want with it, including printing the month number and month in English. As for 1 line code, yes you can, but can't imagine why anyone would want the code to be in 1 line. – taesu Feb 16 '21 at 21:48