Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

get the last sunday and saturday's date in python

Looking to leverage datetime to get the date of beginning and end of the previous week, sunday to saturday.

So, if it's 8/12/13 today, I want to define a function that prints:

Last Sunday was 8/4/2013 and last Saturday was 8/10/2013

How do I go about writing this?

EDIT: okay, so there seems to be some question about edge cases. For saturdays, I want the same week, for anything else, I'd like the calendar week immediately preceding today's date.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

datetime.date.weekday returns 0 for Monday. You need to adjust that.

Try following:

>>> import datetime
>>> today = datetime.date.today()
>>> today
datetime.date(2013, 8, 13)
>>> idx = (today.weekday() + 1) % 7 # MON = 0, SUN = 6 -> SUN = 0 .. SAT = 6
>>> idx
2
>>> sun = today - datetime.timedelta(7+idx)
>>> sat = today - datetime.timedelta(7+idx-6)
>>> 'Last Sunday was {:%m/%d/%Y} and last Saturday was {:%m/%d/%Y}'.format(sun, sat)
'Last Sunday was 08/04/2013 and last Saturday was 08/10/2013'

If you are allowed to use python-dateutil:

>>> import datetime
>>> from dateutil import relativedelta
>>> today = datetime.datetime.now()
>>> start = today - datetime.timedelta((today.weekday() + 1) % 7)
>>> sat = start + relativedelta.relativedelta(weekday=relativedelta.SA(-1))
>>> sun = sat + relativedelta.relativedelta(weekday=relativedelta.SU(-1))
>>> 'Last Sunday was {:%m/%d/%Y} and last Saturday was {:%m/%d/%Y}'.format(sun, sat)
'Last Sunday was 08/04/2013 and last Saturday was 08/10/2013'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...