0

hoping someone helps me out. I have a nested json file and I'm trying to calculate the age difference between two lines of the file, the start_date and end_date with date format of mm/yyyy only. So I'm trying to split it so I can calculate the year difference between end_date and start_date, if over 10 years, I add to another list.

This is my code below, but it prints an empty list and I don't know how to fix it. Any tips or directions will be appreciated

Oh...I have to use default python libraries so even though pandas will be easier, I can't use it.

remove_card=[] 

def datebreakdown(data_file):
    expr1 = data_file['Credit Card']['start_date']
    expr2 = data_file['Credit Card']['end_date']
    breakdown1 = expr1.split('/') 
    breakdown2 = expr2.split('/')
    card_month = int(breakdown1[0]) - int(breakdown2[0])
    card_year= int(breakdown1[1]) - int(breakdown2[1])
    if card_year >= 10:
        return True
    elif card_year == 10 and card_year > 0:
        return True
    else:
        return False

for line in data_json: #data_json is name of the json file. 
    if datebreakdown(data_file) == True:
        remove_card.append(data_file)
Grace
  • 3
  • 2

1 Answers1

0

I think these are the conditions you want:

    if card_year > 10:
        return True
    elif card_year == 10 and card_month > 0:
        return True
    else:
        return False

The first condition should be strictly >, not >=. The second condition should compare the months when the year difference is exactly 10.

Another problem is that you're subtracting the dates in the wrong order. You're subtracting the end from the start, so it will always be negative. So those subtractions should be:

    card_month = int(breakdown2[1]) - int(breakdown1[0])
    card_year= int(breakdown2[1]) - int(breakdown1[1])
def datebreakdown(data_file):
    expr1 = data_file['Credit Card']['start_date']
    expr2 = data_file['Credit Card']['end_date']
    year1, month1 = expr1.split('/') 
    year2, month2 = expr2.split('/')
    start_date = int(year1) + int(month1)/12
    end_date = int(year2) + int(month2)/12
    return end_date - start_date > 10

DEMO

Barmar
  • 741,623
  • 53
  • 500
  • 612