获取从日期和会计年度结束的季度的开始和结束日期

时间:2017-09-02 23:37:52

标签: python date datetime

鉴于某些数据,我想知道最简单/最干净的方式来获得上一季度的开始和结束。

例如,给定以下日期:

from datetime import datetime
example_date = datetime.strptime('2017-05-12', '%Y-%m-%d')

如果会计年度在9月结束(month=9),结果应为:

datetime.datetime(2017,01,01), datetime.datetime(2017,03,31)

另一方面,如果会计年度在10月结束(月份= 10),结果将是

datetime.datetime(2017,02,01), datetime.datetime(2017,04,30)

该函数的原型将是这样的:

def get_range(date_in, fy_end_month):
  pass

1 个答案:

答案 0 :(得分:2)

您可以定义两个功能:一个用于获取给定日期的四分之一,另一个用于获取给定四分之一的开始和结束日期。要获得上一季度的开始和结束日期,您只需要从当前季度减去一个(对第一季度进行一些处理)。

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)

一旦定义了这些,我们就可以定义一个简单的函数来获得上一季度。

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)

现在您可以将返回的日期分配给变量

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