Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

django - Find Monday's date with Python

How do I find the previous Monday's date, based off of the current date using Python? I thought maybe I could use: datetime.weekday() to do it, but I am getting stuck.

I basically want to find today's date and Mondays date to construct a date range query in django using: created__range=(start_date, end_date).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
>>> import datetime
>>> today = datetime.date.today()
>>> today + datetime.timedelta(days=-today.weekday(), weeks=1)
datetime.date(2009, 10, 26)

Some words of explanation:

Take todays date. Subtract the number of days which already passed this week (this gets you 'last' monday). Add one week.

Edit: The above is for 'next monday', but since you were looking for 'last monday' you could use

today - datetime.timedelta(days=today.weekday())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...