import time
import datetime as datetime
def late_time(time2):
#time2是外部传入的任意日期
now_time = datetime.datetime.strptime(time2, '%Y-%m-%d')
#如需求是当前时间则去掉函数参数改写 为datetime.datetime.now()
threeDayAgo = (now_time - datetime.timedelta(days =30))
# 转换为时间戳
timeStamp =int(time.mktime(threeDayAgo.timetuple()))
# 转换为其他字符串格式
otherStyleTime = threeDayAgo.strftime("%Y-%m-%d")
return otherStyleTime
a = late_time("2019-3-30")
print(a)# 打印2018-02-28
没必要那么麻烦吧比如 给定 ‘20150819’日期
那么它的一个月前的日期就是 20150719
她的 半年前日期就是 20150219
所以 关键就是 月份-1 或者月份-6(注意年数的变化)
那么 是这个逻辑的话
import datetime,time,calendar
def months(dt,months):#这里的months 参数传入的是正数表示往后 ,负数表示往前
month = dt.month - 1 + months
year = dt.year + month / 12
month = month % 12 + 1
day = min(dt.day,calendar.monthrange(year,month)[1])
dt = dt.replace(year=year, month=month, day=day)
return str(dt.replace(year=year, month=month, day=day)).replace('-','')
time_temp = '20150419'
dt=datetime.date(int(time_temp[0:4]), int(time_temp[4:6]), int(time_temp[6:8]))
print '一个月前的今天是',months(dt,-1)
print '6个月前的今天是',months(dt,-6)