get lastweek dates using python?
13,374
Solution 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))
Solution 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.
Author by
Suresh
Updated on June 14, 2022Comments
-
Suresh almost 2 years
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'
-
Suresh about 9 yearsmy input is today=item[xxxx] here i have to check the future and past date with item[xxxxx] and system current date for count the last week.. if dates having future and past dates its should be spiked.