In this tutorial we will finish our get_date() function and test it out!
PLEASE USE THE CODE BELOW, IT FIXES SOME ERRORS FROM THE VIDEO ABOVE
Now that we have extracted the information from the text it's time to process it. There are a few scenarios we need to consider: 1. We have a day but no month 2. We have only a day of the week 3. The date mentioned is before the current date 4. We don't find a date
There are a few other ones as well but these are our main concern.
And here is the rest of the function to handle the aboce situations.
defget_date(text):text=text.lower()today=datetime.date.today()iftext.count("today")>0:returntodayday=-1day_of_week=-1month=-1year=today.yearforwordintext.split():ifwordinMONTHS:month=MONTHS.index(word)+1elifwordinDAYS:day_of_week=DAYS.index(word)elifword.isdigit():day=int(word)else:forextinDAY_EXTENTIONS:found=word.find(ext)iffound>0:try:day=int(word[:found])except:pass# THE NEW PART STARTS HEREifmonth<today.monthandmonth!=-1:# if the month mentioned is before the current month set the year to the nextyear=year+1# This is slighlty different from the video but the correct versionifmonth==-1andday!=-1:# if we didn't find a month, but we have a dayifday<today.day:month=today.month+1else:month=today.month# if we only found a dta of the weekifmonth==-1andday==-1andday_of_week!=-1:current_day_of_week=today.weekday()dif=day_of_week-current_day_of_weekifdif<0:dif+=7iftext.count("next")>=1:dif+=7returntoday+datetime.timedelta(dif)ifday!=-1:# FIXED FROM VIDEOreturndatetime.date(month=month,day=day,year=year)
Testing and Using get_date()
Now that we have created this function it's time to use it and see if it works!
Let's add this to our mainline and start saying some dates to the computer!