DreamIsPower
DreamIsPower

Reputation: 1

Difference of start date and end date

I am trying to get a code to return true if the start date is before or the same as the end date. However, I am unable to get the correct output for some testing cases.

def difference(start_day, start_mon, start_year, end_day, end_mon, end_year):    
    start_date = (start_day, start_mon, start_year)
    end_date = (end_day, end_mon, end_year)
    if start_date <= end_date:
        return True
    else:
        return False

***My output:***
difference(19, 3, 2014, 19, 3, 2014)    #True       
difference(18, 3, 2014, 19, 3, 2014)    #True   
difference(20, 3, 2014, 19, 3, 2014)    #False      
difference(19, 3, 2015, 19, 3, 2014)    #False      
difference(19, 6, 2014, 19, 3, 2014)    #False      
difference(18, 12, 2014, 19, 11, 2014)  #True   <- This is the wrong output
difference(18, 12, 2014, 19, 11, 2015)  #True

***Expected output:***
difference(19, 3, 2014, 19, 3, 2014)    #True       
difference(18, 3, 2014, 19, 3, 2014)    #True   
difference(20, 3, 2014, 19, 3, 2014)    #False      
difference(19, 3, 2015, 19, 3, 2014)    #False      
difference(19, 6, 2014, 19, 3, 2014)    #False      
difference(18, 12, 2014, 19, 11, 2014)  #False      
difference(18, 12, 2014, 19, 11, 2015)  #True

I tried different ways of writing the code but I am still unable to obtain the expected output for all the test cases.

Upvotes: 0

Views: 197

Answers (2)

rftr
rftr

Reputation: 1275

If you definitely want to use tuples you could change the position of year and day in the tuples:

def difference(start_day, start_mon, start_year, end_day, end_mon, end_year):    
    start_date = (start_year, start_mon, start_day)
    end_date = (end_year, end_mon, end_day)
    return start_date <= end_date

Upvotes: 0

Tom Wojcik
Tom Wojcik

Reputation: 6189

As answered here

Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal (i.e. the first is greater or smaller than the second) then that's the result of the comparison, else the second item is considered, then the third and so on.

That's how all sequences are compared. Python Docs

Sequence objects typically may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.

What you want to do instead is compare date objects.

from datetime import date


def difference(start_day, start_mon, start_year, end_day, end_mon, end_year):
    start_date = date(day=start_day, month=start_mon, year=start_year)
    end_date = date(day=end_day, month=end_mon, year=end_year)
    return start_date <= end_date

Upvotes: 1

Related Questions