I would like to get the most recent datetime
of a weekday()
index in Python. How could I do this?
Example:
Let's say today is Wednesday 02/09 (weekday
index 2). Input 0
would give me datetime
of last Tuesday, which is 02/07. 3
would give me datetime
of last Thursday, which would be 02/03.
CodePudding user response:
To my understanding, weekday()
only gives n'th day of the week based on a time instance.
So, ideally, the best way to get most recent weekday would be date.today().weekday()
.
CodePudding user response:
I broke it down to small steps, of course you can combine them to fewer expressions:
from datetime import date
def most_recent_date(most_recent_index):
today = date.today()
today_index = today.weekday()
today_ordinal = today.toordinal()
most_recent_ordinal = today_ordinal - (today_index - most_recent_index) % 7
most_recent = date.fromordinal(most_recent_ordinal)
return most_recent
print(most_recent_date(1))