1 from datetime import * 2 import calendar 3 4 def get_monthago_date(): 5 nowtime = date.today() 6 nowtime_year = nowtime.year 7 nowtime_month = nowtime.month 8 nowtime_day = nowtime.day 9 10 onemonthago = nowtime_month - 1 #减去一个月,判断是否为0,为0表示当前月份是1月份 11 12 if onemonthago == 0: #如果当前月份为1月份,就需要设置年份减去1,月份为12月 13 oneyearago = nowtime_year - 1 14 onemonthago = 12 15 monthindex, monthdays = calendar.monthrange(oneyearago, onemonthago) #获取上一个月有多少天 16 17 if monthdays >= nowtime_day: #如果上一个月的总天数大于当前日期就用当前的日期 18 onemonthdate = nowtime.replace(year=oneyearago, month=onemonthago, day=nowtime_day) 19 else: #如果上一个月的总天数都小于当前的日期(2月28和3.31这种情况)就使用上个月的最大日期 20 onemonthdate = nowtime.replace(year=oneyearago, month=onemonthago, day=monthdays) 21 22 return onemonthdate.strftime(‘%Y-%m-%d‘) 23 else: 24 monthindex, monthdays = calendar.monthrange(nowtime_year, onemonthago) 25 26 if monthdays >= nowtime_day: 27 onemonthdate = nowtime.replace(year=nowtime_year, month=onemonthago, day=nowtime_day) 28 else: 29 onemonthdate = nowtime.replace(year=nowtime_year, month=onemonthago, day=monthdays) 30 31 return onemonthdate.strftime(‘%Y-%m-%d‘)
时间: 2024-10-14 23:27:37