Finding the date of the next Saturday

China☆狼群 提交于 2021-01-21 08:07:49

问题


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


回答1:


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



回答2:


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'



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



来源:https://stackoverflow.com/questions/16769902/finding-the-date-of-the-next-saturday

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!