Using Python to count the number of business days in a month?

后端 未结 6 865
南旧
南旧 2021-01-05 18:27

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

6条回答
  •  失恋的感觉
    2021-01-05 18:48

    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
    

提交回复
热议问题