Python - 排除两个日期之间的周末

时间:2017-09-24 05:05:32

标签: python python-2.7 datetime

我想计算两个日期之间的差异,但想要从中排除周末。以下是日期格式:

CreateDate - 2017-08-29 10:47:00 ResolveDate - 2017-09-23 16:56:00

4 个答案:

答案 0 :(得分:2)

您可以使用numpy.busday_count:

from datetime import datetime
import numpy as np

create_date = "2017-08-29 10:47:00" 
resolve_date = "2017-09-23 16:56:00"

create_datetime = datetime.strptime(create_date, '%Y-%m-%d %H:%M:%S')
resolve_datetime = datetime.strptime(resolve_date, '%Y-%m-%d %H:%M:%S')

print("The difference in days is: %d" % ((resolve_datetime - create_datetime).days))
print("The difference in business days is: %d") % (np.busday_count(create_datetime, resolve_datetime))

<强>输出:

The difference in days is: 25
The difference in business days is: 19

答案 1 :(得分:2)

使用isoweekday()的另一种python方式:

import datetime, pprint

# isoweekday: Monday is 1 and Sunday is 7
start_date = datetime.date(2017, 10, 1)
end_date = datetime.date(2017, 12, 31)
days = end_date - start_date
valid_date_list = {(start_date + datetime.timedelta(days=x)).strftime('%d-%b-%Y')
                        for x in range(days.days+1)
                        if (start_date + datetime.timedelta(days=x)).isoweekday() <= 5
                       }
print("Business Days = {}".format(len(valid_date_list)))

答案 2 :(得分:1)

运行while循环,不断向timedelta添加{1}} +1天。在一个单独的柜台跟踪工作日与周末。

答案 3 :(得分:1)

使用datetime模块:

import datetime

d1 = datetime.datetime.strptime('2017-08-29 10:47:00', '%Y-%m-%d %H:%M:%S')
d2 = datetime.datetime.strptime('2017-09-23 16:56:00', '%Y-%m-%d %H:%M:%S')
delta = (d2 - d1).days
diff_weekdays = delta - (delta // 7) * 2

print(diff_weekdays)    # 19