问题
I am trying to get the date of the last week with python.
if date is : 10 OCT 2014 means
It should be print
10 OCT 2014, 09 OCT 2014, 08 OCT 2014, 07 OCT 2014, 06 OCT 2014, 05 OCT 2014, 04 OCT 2014
I tried:
today = (10 OCT 2014)
dates = [today + datetime.timedelta(days=i) for i in range(-4 - today.weekday(), 4 - today.weekday())]
print dates
I am getting this error:
exceptions.AttributeError: 'unicode' object has no attribute 'weekday'
回答1:
Your question and algorithm don't seem to correspond. Is this what you're after?
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))
回答2:
@MarkG hit the nail on the head but if you're looking to get the exact output as asked this would work:
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])
Note that you need to pass the today's date as a string.
来源:https://stackoverflow.com/questions/28478553/get-lastweek-dates-using-python