Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 796
akkatracker Avatar asked May 27 '13 09:05

akkatracker


2 Answers

>>> 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'
like image 74
Emmanuel Avatar answered Oct 03 '22 13:10

Emmanuel


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'
like image 26
r44 Avatar answered Oct 03 '22 12:10

r44