获取指定日期的上一个月日期

输入:20170320,输出:20170220

 1 import datetime
 2 def get_lastmonth():
 3     date = raw_input('please input a date:
')
 4     if len(date) == 8:
 5         newdate = date[0:4] + '-' + date[4:6] + '-' + date[6:]
 6         datestr = datetime.datetime.strptime(newdate, "%Y-%m-%d").date()
 7         year = datestr.year
 8         month = datestr.month
 9         day = datestr.day
10         if month == 1:
11             month = 12
12             year -= 1
13         else:
14             month -= 1
15         lastmonth = datetime.datetime(year, month, day).strftime("%Y-%m-%d")
16         final = ''.join(lastmonth.split('-'))
17         return final
18     else:
19         return None
20         
21 print get_lastmonth()
原文地址:https://www.cnblogs.com/laresh/p/6647632.html