Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialOzzy Robledo
6,288 Pointsclean_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
Treehouse TeacherHi! 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
6,288 PointsWhen 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:
try:
date_object = datetime.datetime.strptime(date_str, '%B %d, %Y').date()
return date_object
except ValueError:
print('''
\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.
Chris Freeman
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 PointsGood question. Perhaps Megan Amendola has some feedback on this.