简体   繁体   中英

How to get 1st business date of year in python?

How do I determine the first business date of the year?. I am trying using

`Import holidays
 HOLIDAYS= holidays.US()`

I would start by using this existing StackOverflow answer to get the first Monday of the year, then filter by holidays using the holidays module.

import datetime

import holidays

us_holidays = holidays.UnitedStates()


def next_workday(start_date, weekday=0):
    """
    Weekday is an integer. 0=Monday, 1=Tuesday, etc.
    """
    start_date -= datetime.timedelta(days=1)  # Go back 1 to be inclusive of the start date itself

    days_ahead = weekday - start_date.weekday()
    if days_ahead <= 0:  # Target day already happened this week
        days_ahead += 7

    start_date = start_date + datetime.timedelta(days_ahead)

    while 1:
        if start_date in us_holidays:
            start_date += datetime.timedelta(1)
        else:
            return start_date


for i in range(100):
    year = 2000 + i
    print(f'First workday of {year} is', next_workday(datetime.date(year, 1, 1)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM