我试图用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'
答案 0 :(得分:5)
您的问题和算法似乎并不对应。这是你之后的事吗?
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))
答案 1 :(得分:1)
@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])
请注意,您需要将今天的日期作为字符串传递。