Home > Net >  Date validation program not printing custom error
Date validation program not printing custom error

Time:08-26

My program converts a date to the 'dmy' format & checks if it's 'Ambiguous', 'True' (no ambiguity), or 'False'. I have used 'Date Parser' in this program . When any of the dates is impossible (say '30/2/2002'), I want the output to be 'False' as specified, but my compiler returns the error - ParserError: day is out of range for month: 30/2/2008. How do I print my own error statement?

from dateutil.parser import parse
import re


def date_fun(date):
  dt = parse(date)
  dt.strftime('%d/%m/%Y')
  dmy_split=re.split('[- /]', date)
  
  try:
    if (eval(dmy_split[0]) >=1 and eval(dmy_split[0]) <=12 and eval(dmy_split[1]) >=1 and eval(dmy_split[1]) <=12 or len(dmy_split[2])==2):
                                                 print("ambiguous")                 
    else:
                                                     print("True")
  except ValueError:        
                                            
                                                     print("False")                                               


date_fun("30/2/2008")

CodePudding user response:

Since parse(date) already throws an error if you are using a date that doesn't exist, just put it in the "try-block"

from dateutil.parser import parse
import re


def date_fun(date):
    try:
        dt = parse(date)


    except ValueError:

        print("False")


date_fun("30/2/2008")

  • Related