How would one go about finding the date of the next Saturday in Python? Preferably using datetime
and in the format '2013-05-25'?
>>> 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:
12 - d.weekday()
is between 6 and 12 where 5 - d.weekday()
would be between 5 and -1Here 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'
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With