pythondatetimepython-2.7

Finding the date of the next Saturday


How would one go about finding the date of the next Saturday in Python? Preferably using datetime and in the format '2013-05-25'?


Solution

  • >>> from datetime import datetime, timedelta
    >>> d = datetime.strptime('2013-05-27', '%Y-%m-%d') # Monday
    >>> t = timedelta((12 - d.weekday()) % 7)
    >>> d + t
    datetime.datetime(2013, 6, 1, 0, 0)
    >>> (d + t).strftime('%Y-%m-%d')
    '2013-06-01'
    

    I use (12 - d.weekday()) % 7 to compute the delta in days between given day and next Saturday because weekday is between 0 (Monday) and 6 (Sunday), so Saturday is 5. But:

    Here is a very simple version (no check) for any weekday:

    >>> def get_next_weekday(startdate, weekday):
        """
        @startdate: given date, in format '2013-05-25'
        @weekday: week day as a integer, between 0 (Monday) to 6 (Sunday)
        """
        d = datetime.strptime(startdate, '%Y-%m-%d')
        t = timedelta((7 + weekday - d.weekday()) % 7)
        return (d + t).strftime('%Y-%m-%d')
    
    >>> get_next_weekday('2013-05-27', 5) # 5 = Saturday
    '2013-06-01'