找到下周六的日期

时间:2013-05-27 09:14:18

标签: python datetime python-2.7

如何在Python中查找下周六的日期?最好使用datetime,格式为'2013-05-25'?

5 个答案:

答案 0 :(得分:14)

>>> 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到12之间,其中5 - 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'

答案 1 :(得分:0)

我发现此pendulum非常有用。只需一行

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'

答案 2 :(得分:0)

您需要两个主要软件包,

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 )

答案 3 :(得分:0)

如果你只想要今天的日期(灵感来自 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')

答案 4 :(得分: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 对象