简体   繁体   中英

Days Per Year Between Begin and End Date (Python)

I have a process I run in a Juptyter notebook where in one step, a calculation is done to basically says what is the amount of a loan and spread it over the years daily. So say a loan begins on '2024-04-01' and ends on '2028-04-01' it would apply the partial accrual in 2024 (from April on) and 2028 (from the beginning of the year to April) and the full amounts for the other years.

Where I am hoping to improve it is to dynamically generate the yearly data versus my current method of specifically defining every year in the process below. What I would like to keep is defining the year begin/end as an accounting year can vary from a calendar year. Any input is appreciated and if you see a much simpler way to achieve what I've written, I would very much appreciate it.

data['2024 Year Start'] = datetime.strptime('2024-01-01', '%Y-%m-%d')
data['2024 Year End'] = datetime.strptime('2024-12-31', '%Y-%m-%d')
data['2024 Days'] = pd.to datetime(data[['2024 Year End'], ['Last Loan Date']].min(axis=1)) - pd.to_datetime(data[['2024 Year Start', 'Loan From Date']].max(axis=1))
data['2024 Days'] = data['2024 Days'].astype('timedelta64[D]')-0
data['2024 Accrual'] = np.where((data['Last Loan Date'] >= data['2024 Year Start'])
            & (data['Loan From Date'] < data['2024 Year End']),
            data[ 'Daily Accrual'] * data['2024 Days'],
            0)

data['2025 Year Start'] = datetime.strptime('2025-01-01', '%Y-%m-%d')
data['2025 Year End'] = datetime.strptime('2025-12-31', '%Y-%m-%d')
data['2025 Days'] = pd.to datetime(data[['2025 Year End'], ['Last Loan Date']].min(axis=1)) - pd.to_datetime(data[['2025 Year Start', 'Loan From Date']].max(axis=1))
data['2025 Days'] = data['2025 Days'].astype('timedelta64[D]')-0
data['2025 Accrual'] = np.where((data['Last Loan Date'] >= data['2025 Year Start'])
            & (data['Loan From Date'] < data['2025 Year End']),
            data[ 'Daily Accrual'] * data['2025 Days'],
            0)

How about this:

from dateutil.relativedelta import relativedelta

# fiscal year settings
m_start = 3
d_start = 15

for y in range(2021,2028):
    year_start = datetime(year=y, month=m_start, day=d_start)
    year_end = year_start + relativedelta(years=1,days=-1)
    # if you like, put it in data cols
    data[str(y)+' Year Start'] = year_start
    data[str(y)+' Year End'] = year_end

The rest can be calculated as you are already doing, if necessary using a dynamically generated string (like 'str(y)' above) as key. If this is not what you need, maybe you can give us some source data and desired output.

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