import datetime
def get_nday_list(n):
before_n_days = []
for i in range(1, n + 1)[::-1]:
before_n_days.append(str(datetime.date.today() - datetime.timedelta(days=i)))
return before_n_days
a = get_nday_list(7)
print(a)
['2017-02-22', '2017-02-23', '2017-02-24', '2017-02-25', '2017-02-26', '2017-02-27', '2017-02-28']
指定时间的前n天的日期:
import datetime
def get_day_nday_ago(date,n):
t = time.strptime(date, "%Y-%m-%d")
y, m, d = t[0:3]
Date = str(datetime.datetime(y, m, d) - datetime.timedelta(n)).split()
return Date[0]
# 示例
a=get_day_nday_ago('2017-02-11',7)
print a
2017-02-04