Skip to content

Instantly share code, notes, and snippets.

@waylan
Last active February 22, 2021 19:14
Show Gist options
  • Save waylan/20fe81c43638cccff480084f352eeb48 to your computer and use it in GitHub Desktop.
Save waylan/20fe81c43638cccff480084f352eeb48 to your computer and use it in GitHub Desktop.
A couple functions which use Pandas to work with a year which runs from Sept to Aug. Each function only wraps a single line of Pandas calls, so their value is limited. But, remembering how to accomplish the things they do is valuable.
import pandas
def get_service_year(date):
'''
Return service year for given date.
The service year runs from Sept to Aug and Sept-Dec are in the service year of
the following calendar year. In other words, the date 2020-09 will return 2021.
Accepts date as an ISO formatted string (for example YYYY-MM), a datetime.date
object, a datetime.datetime object, or any of Pandas' date objects.
'''
return pandas.Period(date, freq='M').asfreq('A-AUG').year
def get_months_of_service_year(year):
'''
Return a list of months in given service year as a pandas.PeriodIndex.
The service year runs from Sept to Aug and Sept-Dec are in the service year of
the following calendar year. Therefore, the year 2021 would return a list of
dates from 2020-09 to 2021-08.
Accepts year as an integer, an ISO formatted string, a datetime.date object,
a datetime.datetime object, or any of Pandas' date objects.
As a pandas.PeriodIndex is returned, one can test if a date is `in` the year.
For example:
>>> yr = get_months_of_service_year(2021)
>>> '2020-11' in yr
True
>>> '2020-08' in yr
False
>>> datetime.date(2021, 2, 1) in yr
True
For a native Python list, do:
>>> y.astype(str).to_list()
['2020-09', '2020-10', ... '2021-08']
>>> [datetime.date(p.year, p.month, 1) for p in y]
[datetime.date(2020, 9, 1), ... datetime.date(2021, 8, 1)]
'''
return pandas.period_range(
end=pandas.Period(year, freq='A-AUG'),
periods=12,
freq='M'
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment