8

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

4

6 回答 6

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

(12 - d.weekday()) % 7用来计算给定日期和下星期六之间的天数的增量,因为weekday介于 0(星期一)和 6(星期日)之间,所以星期六是 5。但是:

  • 5 和 12 是相同的模 7(是的,我们一周有 7 天 :-))
  • 所以12 - d.weekday()在 6 到 125 - d.weekday()之间,在 5 到 -1 之间
  • 所以这让我不用处理否定的情况(周日为-1)。

这是任何工作日的非常简单的版本(不检查):

>>> 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'
于 2013-05-27T09:46:41.447 回答
4

我发现这个钟摆非常有用。只有一行

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

请参阅下面的更多细节:

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'
于 2019-04-25T00:32:04.183 回答
3

你需要两个主要的包,

import datetime
import calendar

一旦你有了这些,你可以通过以下代码简单地获得所需的一周日期,

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

奖金 跟随内容,如果你输入

saturday.weekday()

这将导致5。因此,您也可以使用5代替,calendar.SATURDAY您将获得相同的结果。

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

于 2019-04-25T01:15:52.180 回答
1

如果你只想要今天的日期(灵感来自 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')
于 2021-04-15T08:03:39.813 回答
0

只是想分享一个代码。这样,您将获得一个日期列表,其中星期六将在接下来的 10 天内。

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)
于 2021-12-16T09:38:49.070 回答
0

同样,基于 Emmanuel 的示例,但使 0-6 符合您的一周:

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

可以通过以下方式调用:

EndofWeekDay( datetime.date.today() )

返回一个 datetime.date 对象

于 2021-05-30T15:20:31.943 回答