35

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.

4

8 回答 8

50

datetime.date.weekday返回0星期一。你需要调整它。

尝试以下操作:

>>> 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'

如果您被允许使用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'
于 2013-08-13T04:26:46.193 回答
12

在我的情况下,我从这里找到了最好的答案

尝试这个

from datetime import datetime,timedelta
import time

def last_day(d, day_name):
    days_of_week = ['sunday','monday','tuesday','wednesday',
                        'thursday','friday','saturday']
    target_day = days_of_week.index(day_name.lower())
    delta_day = target_day - d.isoweekday()
    if delta_day >= 0: delta_day -= 7 # go back 7 days
    return d + timedelta(days=delta_day)
于 2013-11-07T11:47:55.023 回答
8
from datetime import date

def satandsun(input):
    d = input.toordinal()
    last = d - 6
    sunday = last - (last % 7)
    saturday = sunday + 6
    print date.fromordinal(sunday)
    print date.fromordinal(saturday)

请注意,这似乎在您的所有案例中都存在:

>>> satandsun(date(2013, 8, 10))
2013-08-04
2013-08-10
>>> satandsun(date(2013, 8, 11))
2013-08-04
2013-08-10
>>> satandsun(date(2013, 8, 12))
2013-08-04
2013-08-10
>>> satandsun(date(2013, 8, 13))
2013-08-04
2013-08-10
>>> satandsun(date(2013, 8, 14))
2013-08-04
2013-08-10
>>> satandsun(date(2013, 8, 15))
2013-08-04
2013-08-10
>>> satandsun(date(2013, 8, 16))
2013-08-04
2013-08-10
>>> satandsun(date(2013, 8, 17))
2013-08-11
2013-08-17
于 2013-08-13T04:35:30.750 回答
5
>>> today = date.today().toordinal()
>>> lastWeek = today-7
>>> sunday = lastWeek - (lastWeek % 7)
>>> saturday = sunday + 6
>>> print "Last Sunday was %s and last Saturday was %s" % (date.fromordinal(sunday), date.fromordinal(saturday))
Last Sunday was 2013-08-04 and last Saturday was 2013-08-10
于 2013-08-13T04:27:17.973 回答
5

当我处理这个问题时,我提出了这个解决方案:

from datetime import datetime, timedelta

def prior_week_end():
    return datetime.now() - timedelta(days=((datetime.now().isoweekday() + 1) % 7))

def prior_week_start():
    return prior_week_end() - timedelta(days=6)

因此 OP 可以将其用作:

'Last Sunday was {:%m/%d/%Y} and last Saturday was {:%m/%d/%Y}'.format(prior_week_start(), prior_week_end())
于 2018-08-07T07:48:25.787 回答
4
import datetime

d = datetime.datetime.today()    
sat_offset = (d.weekday() - 5) % 7  
saturday = d - datetime.timedelta(days=sat_offset)    
print("Last Saturday was on", saturday)
sun_offset = (d.weekday() - 6) % 7
sunday = d - datetime.timedelta(days=sun_offset)
print("Last Sunday was on", sunday)
于 2018-10-24T11:38:52.997 回答
2

以下代码对我有用:

    today = datetime.date.today()
    last_sunday_offset = today.weekday() + 1  # convert day format mon-sun=0-6 => sun-sat=0-6 
    last_sunday = today - datetime.timedelta(days=last_sunday_offset)

注意:上面我采用了正常的工作日(星期一为 0),但在 isoweekday 中,星期一为 1。有关更多详细信息,您可以查看python 内置包 datetime.py的weekday() 和 isoweekday()方法:

    def weekday(self):
        "Return day of the week, where Monday == 0 ... Sunday == 6."
        return (self.toordinal() + 6) % 7

    # Day-of-the-week and week-of-the-year, according to ISO

    def isoweekday(self):
        "Return day of the week, where Monday == 1 ... Sunday == 7."
        # 1-Jan-0001 is a Monday
        return self.toordinal() % 7 or 7```
于 2021-04-16T11:04:32.120 回答
0

这就是我所做的:

import datetime


def what_date_was_last(day_of_the_week):
    today = datetime.date.today()

    last_seven_dates_from_yesterday = {}
    mod_count = -1
    for i in range(7):
        tdelta = datetime.timedelta(mod_count)
        mod_count -= 1
        date = today + tdelta
        last_seven_dates_from_yesterday[date.weekday()] = date

    days_of_the_week_dict = {
        "mon": 0,
        "tue": 1,
        "wed": 2,
        "thu": 3,
        "fri": 4,
        "sat": 5,
        "sun": 6,
    }       
    answer=last_seven_dates_from_yesterday
         [days_of_the_week_dict[day_of_the_week]]
    return answer

所以现在我可以跑了..

what_date_was_last("sun")

或一周中的任何一天

what_date_was_last("tue")
于 2022-02-13T18:21:28.880 回答