Home > Mobile >  How would you shorten this long winded if/elif function?
How would you shorten this long winded if/elif function?

Time:09-26

This code works as intended but is not very elegant. I am looking for different perspectives or better methods of getting the same result. Also if you have any recommendations for naming conventions when it comes to variables for code readability, feedback is welcome.

def get_oldest(date1, date2):
    """Given 2 date strings in "MM/DD/YYYY" format, return oldest one."""
    date_one = date1.split("/")
    date_two = date2.split("/")
    if date_one[2] < date_two[2]:
        return date1
    elif date_one[2] > date_two[2]:
        return date2
    elif date_one[2] == date_two[2]:
        if date_one[0] < date_two[0]:
            return date1
        elif date_one[0] > date_two[0]:
            return date2
        elif date_one[0] == date_two[0]:
            if date_one[1] < date_two[1]:
                return date1
            elif date_one[1] > date_two[1]:
                return date2
            elif date_one[1] == date_two[1]:
                return date1


get_oldest("06/21/1958", "06/24/1958")

CodePudding user response:

Step 1: Use a sane date format. mm/dd/yyyy is not a sane date format.

Step 2: Use the built-in min() function.

There is no step 3.

min(["1958-06-21", "1958-06-24"])

min() expects a list of values. That list can be 1-N items long. It works well for your case (the smallest of two values), but any other case works just as well.

CodePudding user response:

Any reason not to use the built-in datetime library?

from datetime import datetime

def get_oldest(date1, date2):
    date_one = datetime.strptime(date1, "%m/%d/%Y")
    date_two = datetime.strptime(date2, "%m/%d/%Y")
    if date_one < date_two:
        return date_one
    else:
        return date_two

print(get_oldest("06/21/1958", "06/24/1958"))
print(get_oldest("01/23/2005", "12/31/2004"))

Returns

1958-06-21 00:00:00
2004-12-31 00:00:00
  • Related