如何在Python中查找两个日期之间的星期一或其他工作日的数量?

时间:2017-04-29 06:01:21

标签: python datetime

我有两个日期,我需要知道有多少周一至周五(除了Sta,Sun),每天应该计算

目前我在想这个:

Public Function update() As Boolean
    Dim STATE As Boolean = False
    Dim cmd As New OleDbCommand
    cmd.Connection = cn
    cmd.CommandType = CommandType.Text
    cmd.CommandText = "UPDATE [GUEST_DATA_TBL] SET [USD]=@USD, [RIEL]=@RIEL, [EURO]=@EURO, [BAHT]=@BAHT, [AUSD]=@AUSD, [GIFT]=@GIFT, [MEMO]=@MEMO WHERE [ID]=@ID"
    AssignParams(cmd)
    cmd.ExecuteNonQuery()
    Return STATE
End Function

'the parameters

Private Sub AssignParams(cmd As OleDbCommand)
        cmd.Parameters.AddWithValue("@ID", ID)
        cmd.Parameters.AddWithValue("@USD", USD)
        cmd.Parameters.AddWithValue("@RIEL", RIEL)
        cmd.Parameters.AddWithValue("@BAHT", BAHT)
        cmd.Parameters.AddWithValue("@EURO", EURO)
        cmd.Parameters.AddWithValue("@AUSD", AUSD)
        cmd.Parameters.AddWithValue("@GIFT", GIFT)
        cmd.Parameters.AddWithValue("@MEMO", MEMO)
End Sub

我没有得到如何有效地做到这一点,所以我不使用多行代码(如果-else和for循环少),可能是熊猫的一些技巧。

5 个答案:

答案 0 :(得分:5)

您可以定义一个功能并按如下方式使用:

def num_days_between( start, end, week_day):
    num_weeks, remainder = divmod( (end-start).days, 7)
    if ( week_day - start.weekday() ) % 7 <= remainder:
       return num_weeks + 1
    else:
       return num_weeks

其中week_day是您要计算的天数。

答案 1 :(得分:2)

此代码仍然使用for循环和if / else。

import datetime
import calendar

def weekday_count(start, end):
  start_date  = datetime.datetime.strptime(start, '%d/%m/%Y')
  end_date    = datetime.datetime.strptime(end, '%d/%m/%Y')
  week        = {}
  for i in range((end_date - start_date).days):
    day       = calendar.day_name[(start_date + datetime.timedelta(days=i+1)).weekday()]
    week[day] = week[day] + 1 if day in week else 1
  return week

print(weekday_count("01/01/2017", "31/01/2017"))

# prints result
# {'Monday': 5, 'Tuesday': 5, 'Friday': 4, 'Wednesday': 4, 'Thursday': 4, 'Sunday': 5, 'Saturday': 4}

答案 2 :(得分:1)

可以使用numpy库获取2020年的星期一数量

    import numpy as np
    np.busday_count('2020', '2021', weekmask='Mon')

答案 3 :(得分:0)

这是有效的 - 即使面对开始和结束之间的数万天 - 并且仍然非常灵活(在sum函数内最多迭代7次):

def intervening_weekdays(start, end, inclusive=True, weekdays=[0, 1, 2, 3, 4]):
    if isinstance(start, datetime.datetime):
        start = start.date()               # make a date from a datetime

    if isinstance(end, datetime.datetime):
        end = end.date()                   # make a date from a datetime

    if end < start:
        # you can opt to return 0 or swap the dates around instead
        raise ValueError("start date must be before end date")

    if inclusive:
        end += datetime.timedelta(days=1)  # correct for inclusivity

    try:
        # collapse duplicate weekdays
        weekdays = {weekday % 7 for weekday in weekdays}
    except TypeError:
        weekdays = [weekdays % 7]

    ref = datetime.date.today()                    # choose a reference date
    ref -= datetime.timedelta(days=ref.weekday())  # and normalize its weekday

    # sum up all selected weekdays (max 7 iterations)
    return sum((ref_plus - start).days // 7 - (ref_plus - end).days // 7
               for ref_plus in
               (ref + datetime.timedelta(days=weekday) for weekday in weekdays))

这分别为datetime.datedatetime.datetime提供了startend个对象。

此外,您可以选择关闭(inclusive=True)和半开(inclusive=False)间隔。

默认情况下,它会计算日期之间的工作日数,但您可以选择任意工作日(周末天数:weekdays=[5, 6])或单个工作日(周三:weekdays=2)。< / p>

答案 4 :(得分:0)

如果有人需要更简单的答案,

ReactiveFormConfig.set({"validationMessage":{"unique":"Enter unique value in the input"}});