Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get lastweek dates using python?

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'
like image 695
Suresh Avatar asked Feb 12 '15 13:02

Suresh


People also ask

How do I get last week Monday date in Python?

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.

How do I get the weekly date in Python?

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.

How do I get last week's startdate and Enddate in Python?

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


1 Answers

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))
like image 131
MarkG Avatar answered Sep 21 '22 17:09

MarkG