确定给定日期范围上一次出现的年份

时间:2016-01-21 17:23:14

标签: algorithm date

我最近不得不创建一个函数来确定上一次出现给定日期范围的年份。给定的日期范围总是小于1年,如果范围超过新年,则该函数应返回2个不同的值:开始年份和结束年份。请参阅以下示例:

If the date range is 10 Jun - 20 Jun:
    If current date is 01 Apr 2016: Return 2015, 2015
                       15 Jun 2016: Return 2015, 2015
                       01 Aug 2016: Return 2016, 2016

If the date range is 20 Dec - 10 Jan:
    If current date is 02 Jan 2016: Return 2014, 2015
                       01 May 2016: Return 2015, 2016
                       25 Dec 2016: Return 2015, 2016

我实现了自己的python函数来执行此操作:

# Returns the years for the previous occurrence of the given period
def _get_last_years_for_period(start, end):
  current_year  = datetime.date.today().year
  current_month = datetime.date.today().month
  current_day   = datetime.date.today().day

  if (start['month'] < end['month']) or ((start['month'] == end['month']) and (start['day'] < end['day'])):
    # Period does not overlap between 2 different years
    if current_month > end['month']:
      return [current_year, current_year]
    elif (current_month == end['month']) and (current_day > end['day']):
      return [current_year, current_year]
    else:
      return [current_year-1, current_year-1]
  else:
    # Period overlaps over 2 different years
    if current_month > end['month']:
      return [current_year-1, current_year]
    elif (current_month == end['month']) and (current_day > end['day']):
      return [current_year-1, current_year]
    else:
      return [current_year-2, current_year-1]

然而,我无法帮助,但我觉得有一种更优雅的方式来实现这一点。我很好奇是否有人对更快,更优雅甚至更容易阅读的实现有任何想法。如果你这样做,请分享(不要担心用Python编写它,使用你想要的任何东西)。

1 个答案:

答案 0 :(得分:0)

我通过定义一个简单的比较器来简化它:

def comes_before(month_day_1, month_day_2):
  return (month_day_1[0] < month_day_2[0]
          or (month_day_1[0] == month_day_2[0]
              and month_day_1[1] < month_day_2[1]))

def get_years_for_period(month_day_1, month_day_2):
  now = datetime.date.today()
  year2 = now.year if comes_before(month_day_2, [now.month, now.day]) else now.year - 1
  year1 = year2 if comes_before(month_day_1, month_day_2) else year2 - 1
  return [year1, year2]