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'
Algorithm (Steps)Use the today() function(gets the current local date), to get today's current local date and create a variable to store it. Pass the weekday as an argument to the relativedelta() function. Here MO(-1) says getting last week Monday, MO means Monday. Print the last Monday date.
Use the weekday() method The weekday() method returns the day of the week as an integer, where Monday is 0 and Sunday is 6. For example, the date(2022, 05, 02) is a Monday.
You can use datetime. timedelta for that. It has an optional weeks argument, which you can set to -1 so it will subtract seven days from the date . You will also have to subract the current date's weekday (and another one, to even the day since the Monday is 0 ).
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With