10

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

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
akkatracker
  • 1,397
  • 3
  • 14
  • 25
  • 1
    Google around a little before you post here. Check this out. See if its useful: http://stackoverflow.com/questions/2436840/how-to-calculate-next-friday-at-3am – Anil May 27 '13 at 09:16
  • Thanks, saw that before but I don't need the time and was wondering whether there was a more concise way. – akkatracker May 27 '13 at 09:18
  • 2
    This link helps, my apologies for wasting time. If anyone has a better solution feel free to answer. http://stackoverflow.com/questions/8801084/how-to-calculate-next-friday-in-python – akkatracker May 27 '13 at 09:21

6 Answers6

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

  • 5 and 12 are the same modulo 7 (yes, we have 7 days in a week :-) )
  • so 12 - d.weekday() is between 6 and 12 where 5 - d.weekday() would be between 5 and -1
  • so this allows me not to handle the negative case (-1 for Sunday).

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'
Emmanuel
  • 13,935
  • 12
  • 50
  • 72
  • 2
    There's no need to add the modulo base (7) to avoid negative numbers. ["The modulo operator always yields a result with the same sign as its second operand."](https://docs.python.org/3/reference/expressions.html#:~:text=the%20modulo%20operator%20always%20yields%20a%20result%20with%20the%20same%20sign%20as%20its%20second%20operand) – Mattwmaster58 Dec 30 '21 at 19:17
  • 1
    @Mattwmaster58: didn't know, thanks! – Emmanuel Jan 03 '22 at 16:59
8

I found this pendulum pretty useful. Just one line

In [4]: pendulum.now().next(pendulum.SATURDAY).strftime('%Y-%m-%d')
Out[4]: '2019-04-27'

See below for more details:

In [1]: import pendulum

In [2]: pendulum.now()
Out[2]: DateTime(2019, 4, 24, 17, 28, 13, 776007, tzinfo=Timezone('America/Los_Angeles'))

In [3]: pendulum.now().next(pendulum.SATURDAY)
Out[3]: DateTime(2019, 4, 27, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))

In [4]: pendulum.now().next(pendulum.SATURDAY).strftime('%Y-%m-%d')
Out[4]: '2019-04-27'
r44
  • 434
  • 6
  • 5
  • This is best. There are many SO posts like this and its a bog of confusing implementations. – Merlin Jan 25 '23 at 19:37
3

You need two main packages,

import datetime
import calendar

Once you have those, you can simply get the desired date for the week by the following code,

today = datetime.date.today() #reference point. 
saturday = today + datetime.timedelta((calendar.SATURDAY-today.weekday()) % 7 )
saturday

Bonus Following the content, if you type

saturday.weekday()

It will result 5. Therefore, you can also use 5 in place of calendar.SATURDAY and you will get same result.

saturday = today + datetime.timedelta((5-today.weekday()) % 7 )

sargupta
  • 953
  • 13
  • 25
1

if you just want the date from today (inspired from Emanuelle )

def get_next_weekday(weekday_number):
    """
    @weekday: week day as a integer, between 0 (Monday) to 6 (Sunday)
    """
    assert 0 <= weekday_number <= 6
    today_date = datetime.today()
    next_week_day = timedelta((7 + weekday_number - today_date.weekday()) % 7)
    return (today_date + next_week_day).strftime('%d/%m/%Y')
MykoCh
  • 11
  • 2
  • 5
0

Again, based on Emmanuel's example, but making 0-6 conform to your week:

ScheduleShift = -1 # make Saturday end of week
EndofWeekDay = lambda do : do + datetime.timedelta( ( ScheduleShift + (13 -  do.weekday() ) %7 ) )

Which can be called with:

EndofWeekDay( datetime.date.today() )

returning a datetime.date object

chipfall
  • 300
  • 2
  • 6
0

Just wanted to share a code. With this, you will get a list of dates when Saturday days will be in the next 10 days.

from datetime import datetime, timedelta
target_day = 'Saturday'
now_ = datetime.today().date()
how_many_days = 10
next_date = [now_ + timedelta(days=x) for x in range(how_many_days) if (now_ + timedelta(days=x)).strftime("%A") == target_day]
print(next_date)
PythonMan
  • 787
  • 10
  • 18