-2
from dateutil.parser import parse
import re
from datetime import datetime

def date_fun(date):
  try:
    dt = parse(date)
    dt = dt.strftime('%d/%m/%Y')
    dmy_split=re.split('[- / ]', dt)

    # error here:
    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")              # Format matched   
    else:
        print("True")
  except ValueError:        # If match not found keep searching    
        print("False")                                               

date_fun("abc")
date_fun("12/1/91")
date_fun("2002-9-18")

This a date validation program and I got the 'Leading 0 not permitted' error at the highlighted part though I haven't used '01' anywhere:

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):
  File "<string>", line 1
    01
     ^
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers

Why am I getting this error, and how do I get rid of it?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Laxmi Ty
  • 3
  • 4
  • Why are you using `eval` here? – tripleee Aug 27 '22 at 14:52
  • The split elements of date are considered as strings. I cannot check for the ambiguity condition without comparing the date components with integers. So I used 'eval' to remove the strings & convert the date into integer. I used int() in my previous code but the conversion wasn't happening, so I was suggested eval(). I've tried int() now & my problem has been solved. – Laxmi Ty Aug 27 '22 at 14:57

1 Answers1

1

though I haven't used '01' anywhere

Yes you have. The first element in dmy_split is '01'.

This is one of the many reasons why eval() is not recommended.

Why do you need eval() anyway? Just use int().

John Gordon
  • 29,573
  • 7
  • 33
  • 58