How do I find days since start of Fiscal Year with pandas

  datetime, pandas, period, python

I have a DataFrame with several million rows with a date time column that I convert to fiscal year (July 1) with the following:

df['As Quarter'] = df['usage_date'].dt.to_period('Q-JUL')
df['Fiscal Year'] = df['As Quarter'].dt.qyear

I’d like to get the # of days into the fiscal year (equivalent to dayofyear) that df[‘usage_date’] is. For example July 2 would be 2.

Currently, I do this:

df['year_start'] = df.apply(lambda x : (pd.to_datetime('07-01-' + str(x['Fiscal Year']-1))),axis=1)
df['year_start'] = df['year_start'].dt.tz_localize('US/Eastern')
df['days_in'] = (df['usage_date'] - df['year_start']).dt.days

but that feels clunky and is slow, especially when everything else is very fast. Is there a way to do this?

Thanks!

Source: Python Questions

LEAVE A COMMENT