使用Python计算一个月中的工作日数? [英] Using Python to count the number of business days in a month?
问题描述
我正在尝试编写一个Python脚本,该脚本将计算当月的工作日数。例如,如果 month =八月
,则 businessDays = 22
。
I am trying to write a Python script that will calculate how many business days are in the current month. For instance if month = August
then businessDays = 22
.
这是我发现月份的代码:
Here is my code for discovering the month:
def numToMonth( num ):
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
return str(months[ num - 1 ])
此代码可以正常工作,我可以对另一个函数进行硬编码以使该月份与该月应包含的天数相匹配...但这对工作日没有帮助。
This code works fine, and I could hard code another function to match the month with how many days that month should contain...but this does not help me with business days.
有帮助吗?我习惯使用C,C ++,所以请不要猛击我的Python技能。
Any help? I'm used to C, C++ so please don't bash my Python "skills".
编辑:我无法在计算机上安装任何其他库或模块,因此请使用默认的Python模块发布答案。 (Python 2.7, datetime
等。)此外,我的PC具有Windows 7操作系统。
I cannot install any extra libraries or modules on my machine, so please post answers using default Python modules. (Python 2.7, datetime
etc.) Also, my PC has Windows 7 OS.
推荐答案
这是一个漫长的过程,但是至少它可以正常工作,并且不需要标准模块以外的任何东西。
This is a long-winded way, but at least it works and doesn't require anything other than the standard modules.
import datetime
now = datetime.datetime.now()
holidays = {datetime.date(now.year, 8, 14)} # you can add more here
businessdays = 0
for i in range(1, 32):
try:
thisdate = datetime.date(now.year, now.month, i)
except(ValueError):
break
if thisdate.weekday() < 5 and thisdate not in holidays: # Monday == 0, Sunday == 6
businessdays += 1
print businessdays
这篇关于使用Python计算一个月中的工作日数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!