Python的第一个业务日期

时间:2016-07-20 16:52:51

标签: python date

如何在python中确定该月的第一个营业日期?我正在编写的程序是每次循环滴灌日期,我需要能够获得真/假。

我发现您可以通过以下方式获得上一个工作日:

import pandas as pd
pd.date_range("2014-01-14", periods=1, freq='BM')

由于

2 个答案:

答案 0 :(得分:5)

我认为,您可以使用BMS获得该月的第一个商务日期:

In[82]:pd.date_range('1/1/2000', '12/1/2000', freq='BMS')

Out[82]: 
DatetimeIndex(['2000-01-03', '2000-02-01', '2000-03-01', '2000-04-03',
               '2000-05-01', '2000-06-01', '2000-07-03', '2000-08-01',
               '2000-09-01', '2000-10-02', '2000-11-01', '2000-12-01'],
              dtype='datetime64[ns]', freq='BMS', tz=None)

答案 1 :(得分:4)

这使用美国联邦假日日历。它使用列表理解来遍历start_dateend_date之间的每个月的第一个工作日,然后如果它落在美​​国联邦假日或周末直到有效的营业日期,则增加一天找到了。

import datetime as dt
import pandas as pd
from pandas.tseries.holiday import USFederalHolidayCalendar

cal = USFederalHolidayCalendar()
start_date = '2015-1-1'
end_date = '2015-12-31'

def get_business_day(date):
    while date.isoweekday() > 5 or date in cal.holidays():
        date += dt.timedelta(days=1)
    return date

>>> first_bday_of_month = [get_business_day(d).date() 
                           for d in pd.date_range(start_date, end_date, freq='BMS')]
[datetime.date(2015, 1, 2),
 datetime.date(2015, 2, 2),
 datetime.date(2015, 3, 2),
 datetime.date(2015, 4, 1),
 datetime.date(2015, 5, 1),
 datetime.date(2015, 6, 1),
 datetime.date(2015, 7, 1),
 datetime.date(2015, 8, 3),
 datetime.date(2015, 9, 1),
 datetime.date(2015, 10, 1),
 datetime.date(2015, 11, 2),
 datetime.date(2015, 12, 1)]

>>> cal.rules
cal.rules
[Holiday: New Years Day (month=1, day=1, observance=<function nearest_workday at 0x10c593578>),
 Holiday: Dr. Martin Luther King Jr. (month=1, day=1, offset=<DateOffset: kwds={'weekday': MO(+3)}>),
 Holiday: Presidents Day (month=2, day=1, offset=<DateOffset: kwds={'weekday': MO(+3)}>),
 Holiday: MemorialDay (month=5, day=31, offset=<DateOffset: kwds={'weekday': MO(-1)}>),
 Holiday: July 4th (month=7, day=4, observance=<function nearest_workday at 0x10c593578>),
 Holiday: Labor Day (month=9, day=1, offset=<DateOffset: kwds={'weekday': MO(+1)}>),
 Holiday: Columbus Day (month=10, day=1, offset=<DateOffset: kwds={'weekday': MO(+2)}>),
 Holiday: Veterans Day (month=11, day=11, observance=<function nearest_workday at 0x10c593578>),
 Holiday: Thanksgiving (month=11, day=1, offset=<DateOffset: kwds={'weekday': TH(+4)}>),
 Holiday: Christmas (month=12, day=25, observance=<function nearest_workday at 0x10c593578>)]