S Jagdeesh
S Jagdeesh

Reputation: 1553

Python - Future and Previous Calendar Quarter

I have a requirement where I need do some calculation on result set getting in JSON format (sample below).

  {
  "level1": {
    "finalresult": [
      {
        "Amount": "12",
        "Month": "04",
        "Year": "2018",
        "Quarter": "2"
      },
      {
        "Amount": "13",
        "Month": "08",
        "Year": "2018",
        "Quarter": "3"
      },
      {
        "Amount": "13",
        "Month": "07",
        "Year": "2017",
        "Quarter": "3"
      },
      {
        "Amount": "124",
        "Month": "12",
        "Year": "2018",
        "Quarter": "4"
      },
      {
        "Amount": "153",
        "Month": "07",
        "Year": "2018",
        "Quarter": "3"
      }

How can I start writing a function to find out sum of amount for following -

1. Next 3 quarters (from current month)

2. Last 2 quarters (from current month)

How do I proceed ahead from here -

response=requests.get("json url")
jsondata=response['level1']['finalresult']

now = datetime.datetime.now()

current_year = now.year

total_sum_last2qrtrs=[]
total_sum_next3qrtrs=[]

for result in jsondata:

Upvotes: 0

Views: 73

Answers (1)

Something like this might work:

current_quarter = ((now.month-1)//3)+1

def total_sum_next3qrtrs():
    year_next_3_quarters = []
    next_3_quarters = [(i%4+1) for i in range(current_quarter, current_quarter+3)]

    amounts = []

    for q in next_3_quarters:
        if q < current_quarter:
            year_next_3_quarters.append({'Year':current_year+1, 'Quarter': q})
        else:
            year_next_3_quarters.append({'Year':current_year, 'Quarter': q})

    for nq in year_next_3_quarters:
        for q in jsondata:
            if nq['Year'] == int(q['Year']) and nq['Quarter'] == int(q['Quarter']):
                amounts.append(int(q['Amount']))
    return sum(amounts)

def total_sum_last2qrtrs():
    year_last_2_quarters = []
    last_2_quarters = [(i%4+1) for i in range(current_quarter-3, current_quarter-1)]

    amounts = []

    for q in last_2_quarters:
        if q < current_quarter:
            year_last_2_quarters.append({'Year':current_year, 'Quarter': q})
        else:
            year_last_2_quarters.append({'Year':current_year-1, 'Quarter': q})

    for nq in year_last_2_quarters:
        for q in jsondata:
            if nq['Year'] == int(q['Year']) and nq['Quarter'] == int(q['Quarter']):
                amounts.append(int(q['Amount']))
    return sum(amounts)

current_quarter = ((now.month-1)//3)+1

print total_sum_next3qrtrs()
print total_sum_last2qrtrs()

output:

290 # 153 + 124 + 13
0   # None that meet the criteria

Of course it may need improvements if the results are not as desired, but it seems to provide correct outputs based on current data.

Upvotes: 1

Related Questions