vendredi 28 juin 2019

How to efficiently check different date formats when converting month to number

I'm trying to convert a given month to a month number in integer format. There are three valid formats that I want to try to convert. A month number that's given as a string (input function returns a string), a month abbreviation, and a full month name.

While my function works as intended I feel like it's not that well written, despite my attempts to make it as clean as possible. In particular, I'm not happy that I have an except statement that just passes. Handling both a string conversion to an integer AND checking to see if the string is a valid month to convert to an integer was a tough task.

I tried to change the order of the try-excepts, removing the string-to-int to make it's on try-except block without going straight into the date formatting in the exception but that's about it. The function below is the best attempt I've had. I couldn't think of anything else except maybe create helper functions?

Code

def get_start_month_updated():
    date_formats = ['%b', '%B']
    while True:
        month = input("What is the starting month?")
        try:
            month_num = int(month)
            if 1 <= month_num <= 12:
                return month_num
        except ValueError:
            for date_format in date_formats:
                try:
                    month_num = strptime(month, date_format).tm_mon
                    return month_num
                except ValueError:
                    pass
            else:
                print("You must enter a valid month")
        else:
            print("You must enter a valid month")

My results are correct and the function works as intended, but I feel like the code is messy and there is a better way to do this without getting really convoluted.

Aucun commentaire:

Enregistrer un commentaire