从日期和会计年度末获取季度的开始和结束日期
鉴于某些数据,我想知道获取上一季度开始和结束的最简单/最简单的方法。
Given a certain data, I would like to know the easiest/cleanest way of getting the beginning and the end of the previous quarter.
例如,给定以下日期:
from datetime import datetime
example_date = datetime.strptime('2017-05-12', '%Y-%m-%d')
如果会计年度在9月结束( month = 9
),则结果应为:
if the fiscal year ends in September (month=9
), the result should be:
datetime.datetime(2017,01,01), datetime.datetime(2017,03,31)
在另一端,如果该财政年度在10月结束(月= 10),则结果为
On the other end, if the fiscal year ended in October (month=10) the result would be
datetime.datetime(2017,02,01), datetime.datetime(2017,04,30)
该函数的原型如下:
def get_range(date_in, fy_end_month):
pass
您可以定义两个功能:一个用于获取给定日期的季度,另一个用于获取给定季度的开始和结束日期。要获取上一季度的开始日期和结束日期,您只需从当前季度中减去一个(对第一季度进行一些处理)即可。
You can define two function: one for the getting the quarter of a given date, and another for getting the start and end dates of a given quarter. To get the start and end dates of the previous quarter, you would just need to subtract one from the current quarter (with some handling of first quarter).
import datetime as dt
from dateutil.relativedelta import relativedelta
def get_quarter(date):
"""
Returns the calendar quarter of `date`
"""
return 1+(date.month-1)//3
def quarter_start_end(quarter, year=None):
"""
Returns datetime.daet object for the start
and end dates of `quarter` for the input `year`
If `year` is none, it defaults to the current
year.
"""
if year is None:
year = dt.datetime.now().year
d = dt.date(year, 1+3*(quarter-1), 1)
return d, d+relativedelta(months=3, days=-1)
一旦定义了这些,就可以定义一个简单的函数来获取上一个季度。
Once these are defined, we can define a simple function to get the previous quarter.
def prev_quarter_range(date):
"""
Returns the start and end dates of the previous quarter
before `date`.
"""
if isinstance(date, str):
date = parser.parse(date)
year = date.year
q = get_quarter(date)-1
# logic to handle the first quarter case
if q==0:
q = 4
year -= 1
return quarter_start_end(q, year)
现在您可以将返回的日期分配给变量
And now you can assign the returned dates to variables
prev_q_start, prev_q_end = prev_quarter_range('2-feb-2011')
print(prev_q_start)
print(prev_q_end)
# prints:
2010-10-01
2010-12-31