Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get fiscal year based on current timestamp-python

I am trying get the start date of the financial year based on today's date.

So after a little research, I found this package called fiscalyear where you can modify the start date of the fiscal year. In my case i wanted 01-07-year to be the start date of my fiscal year so i set fiscalyear.START_MONTH = 7

I have tried the below(reproducible example if you pip install fiscalyear):

import datetime
import fiscalyear
fiscalyear.START_MONTH = 7
a = fiscalyear.FiscalYear(datetime.datetime.now().year).start.date()
a.strftime('%Y-%m-%d')

Which outputs correctly:

'2018-07-01'

However, this would not work when the month turns to August, since the datetime.datetime.now().year doesnot change. So i tried doing something like:

if (datetime.datetime.now()-pd.to_datetime('2018-07-01')).days < 365:
    a = fiscalyear.FiscalYear(datetime.datetime.now().year).start.date()
    print(a.strftime('%Y-%m-%d'))
else:
    a = fiscalyear.FiscalYear(datetime.datetime.now().year+1).start.date()
    print(a.strftime('%Y-%m-%d'))

I have a bad feeling about what I am doing since this might now work for leap years too.

Is there some better way to do this in python which will detect the start date of the fiscal year based on current timestamp?

py version: 3.6.7

like image 245
anky Avatar asked Oct 19 '25 02:10

anky


2 Answers

My knowledge in the fiscal area is somewhere close to Zero, but according to [ReadTheDocs.FiscalYear]: Basic Usage:

The FiscalYear class provides an object for storing information about the start and end of a particular fiscal year.

...

The start and end of each of the above objects are stored as instances of the FiscalDateTime class. This class provides all of the same features as the datetime class, with the addition of the ability to query the fiscal year, fiscal quarter, fiscal month, and fiscal day.

So, FiscalYear isn't to be used with dates, but FiscalDateTime (or its simpler sibling: FiscalDate) instead.

>>> import fiscalyear
>>> fiscalyear.START_MONTH = 7
>>>
>>> cur_y = fiscalyear.FiscalYear(datetime.datetime.now().year)
>>> cur_y.start.date()
datetime.date(2018, 7, 1)
>>> cur_y.end.date()
datetime.date(2019, 6, 30)
>>>
>>> cur_dt = fiscalyear.FiscalDate(2019, 2, 19)  # Current date (at answer time)
>>> cur_dt.fiscal_year
2019
>>>
>>> jul_dt = fiscalyear.FiscalDate(2019, 7, 19)  # A date past July 1st (when the fiscal year should change)
>>> jul_dt.fiscal_year
2020
like image 108
CristiFati Avatar answered Oct 21 '25 16:10

CristiFati


You can try following code, It worked for me:

>>> import fiscalyear
>>> fiscalyear.START_MONTH = 4
>>> fiscalyear.FiscalYear.current()
FiscalYear(2021)
>>> 
like image 31
Vinod Singh Avatar answered Oct 21 '25 15:10

Vinod Singh