简体   繁体   中英

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.

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'

I found the best answer from here working fine in my case

try this

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

Note that this seems to survive all of your cases:

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

When I was dealing with this I came with this solution:

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)

So OP could use it as:

'Last Sunday was {:%m/%d/%Y} and last Saturday was {:%m/%d/%Y}'.format(prior_week_start(), prior_week_end())
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)

this is what i did:

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

so now i can run..

what_date_was_last("sun")

or any day of the week

what_date_was_last("tue")

Following code works for me:

    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)

Note: Above I have taken normal weekday(0 for Monday) but in isoweekday Monday would be 1. For more details you can check out weekday() and isoweekday() method of python built-in package datetime.py :

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

Simplest way is:

import datetime

today = datetime.datetime.now(datetime.timezone.utc)
last_sat = today - datetime.timedelta(days=today.weekday()+2)
last_sun = today - datetime.timedelta(days=today.weekday()+1)

today is set to UTC, feel free to use your preferred way.

This works for my purposes (I have to run a script every Monday), so I just count the days backward.

from datetime import datetime, timedelta

prev_sun = datetime.now() - timedelta(days=8)
prev_sun = prev_sun.strftime('%m/%d/%Y')

prev_sat = datetime.now() - timedelta(days=2)
prev_sat = prev_sat.strftime('%m/%d/%Y')

Hope that helps keep things nice and simple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM