2016-01-21 21 views
0

我最近不得不創建一個函數來確定給定日期範圍的上一次出現的年份。給定的日期範圍將始終小於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編寫它,使用任何你想要的)。

+0

如果該範圍內的日期的一個是什麼2月29日? – rici

+1

你的代碼看起來沒問題。如果您在同一年內檢查日期是否接近另一個日期,則可以整理它並將其歸結爲四種情況。 –

回答

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] 
相關問題