Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python SQLAlchemy Basics Working with SQLAlchemy Cleaning Data

Ozzy Robledo
Ozzy Robledo
4,745 Points

clean_date() function

I wrote this much less complicated function for cleaning the date and am curious if there is a reason something like this wasn't used? Am I missing something?

def clean_date(date_string):  
    date_obj = datetime.datetime.strptime(date_str, '%B %d, %Y').date()  
    return date_obj

Just curious, Thanks!

2 Answers

Megan Amendola
.a{fill-rule:evenodd;}techdegree seal-36
Megan Amendola
Treehouse Teacher

Hi! Sorry for the late reply :) Try running the function with a date that doesn't exist like clean_date('June 31, 2020'). Your function will throw an error. You'll want to move that into a try block to catch that error and make sure the user inputs a date that exists. You may think "Why would someone input a date that doesn't exist?" but from the database and spreadsheet cleaning I've done, you'd be surprised how often that happens. If I remember right, I wanted to make sure the date was 1) in the right format so I could do the conversion from a string to a DateTime and 2) make sure the date existed. If you run clean_date('06-14-2020') you'll also get an error since the date isn't in the format ('%B %d, %Y') your code said it would be in. I hope that helps!

Ozzy Robledo
Ozzy Robledo
4,745 Points

When I wrote the above code I was not to the point where we fixed errors from incorrect input. Here is my updated function:

def clean_date(date_str):  
    while True:  
            date_object = datetime.datetime.strptime(date_str, '%B %d, %Y').date()  
            return date_object  
        except ValueError:  
            \n***DATE ERROR***  
            \rIncorrect date format. Use example below:  
            \r"January 1, 2020"''')  
            date_str = input('please enter date: ')  

This handles any incorrectly formatted input.