6
votes

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'
2
I am unable to reproduce in Python 2.7, can you show how you are initializing your today variabe? Are you creating it using the datetime object like so, datetime.date(2014, 10, 10)? The error message seems to lead that you are not.Anthony Forloney
today = datetime.date.today()Suresh

2 Answers

8
votes

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))
1
votes

@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.