使用 python 获取上周日期?

get lastweek dates using python?

我正在尝试使用 python 获取上周的日期。

如果日期是:2014 年 10 月 10 日意味着

应该是打印

10 OCT 2014, 09 OCT 2014, 08 OCT 2014, 07 OCT 2014, 06 OCT 2014, 05 OCT 2014, 04 OCT 2014

我试过了:

today = (10 OCT 2014)

dates = [today + datetime.timedelta(days=i) for i in range(-4 - today.weekday(), 4 - today.weekday())]
print dates

我收到这个错误:

exceptions.AttributeError: 'unicode' object has no attribute 'weekday'

你的问题和算法好像不对应。这就是你想要的吗?

from datetime import date
from datetime import timedelta
today = date(2014, 10, 10) # or you can do today = date.today() for today's date

for i in range(0,7):
    print (today - timedelta(days=i))

@MarkG 一语中的,但如果你想获得所要求的准确输出,这会起作用:

import datetime

today = '10 OCT 2014'

dates = [datetime.datetime.strptime(today, '%d %b %Y') - datetime.timedelta(days=i) for i in range(7)]
print ', '.join([day.strftime('%d %b %Y').upper() for day in dates])

请注意,您需要将今天的日期作为字符串传递。