1 fromDatetimeImport*2 ImportCalendar3 4 defget_monthago_date ():5Nowtime =Date.today ()6Nowtime_year =Nowtime.year7Nowtime_month =Nowtime.month8Nowtime_day =Nowtime.day9 TenOnemonthago = nowtime_month-1#minus one months, judging whether it is 0, 0 means the current month is January One A ifOnemonthago = = 0:#If the current month is January, you need to set the year minus 1, the month is December -Oneyearago = Nowtime_year-1 -Onemonthago = 12 theMonthindex, monthdays = Calendar.monthrange (Oneyearago, Onemonthago)#get how many days are there in the last one months - - ifMonthdays >= Nowtime_day:#if the total number of days in the last one months is greater than the current date, use the current date -Onemonthdate = Nowtime.replace (Year=oneyearago, Month=onemonthago, day=nowtime_day) + Else:#if the total number of days in the last one months is less than the current date (February 28 and 3.31), use the maximum date of the previous month -Onemonthdate = Nowtime.replace (Year=oneyearago, Month=onemonthago, day=monthdays) + A returnOnemonthdate.strftime ('%y-%m-%d') at Else: -Monthindex, monthdays =Calendar.monthrange (nowtime_year, Onemonthago) - - ifMonthdays >=Nowtime_day: -Onemonthdate = Nowtime.replace (Year=nowtime_year, Month=onemonthago, day=nowtime_day) - Else: inOnemonthdate = Nowtime.replace (Year=nowtime_year, Month=onemonthago, day=monthdays) - to returnOnemonthdate.strftime ('%y-%m-%d')
Calculate the date one months from today