0

I have some Date formats that i can accept YYYYMMDDHHMMSS or YYYYMMDDHHMM or YYYYMMDDHH or YYYYMMDD. I want to check if the Date is in these formats, otherwise print an Error message or catch some error. I tried the achieving this using RegEx. It got really messy and it also matches if the format looks as follows: YYYYMMDDHHMMSS_someWord**. i used re.match() and re.FindAll(), which behaved as described and that wasn't what i wanted. My code though looks like this but honestly does't work.

_date ='201909010900'
regex = re.compile("[1-2][0,9][0-9]{2}[0,1][0-9][0,1,2,3][0-9][0,1,2][0-9][0-5][0-9][0-5][0-9]")
_date = re.findall(regex, _date)
print(_date)
match = re.match(regex, _date[0])
if (match):
     print(_date)
else:
    regex = re.compile("[1-2][0,9][0-9]{2}[0,1][0-9][0,1,2,3][0-9][0,1,2][0-9]")    
    _date = re.findall(regex, _date)
    match= re.match(regex,_date[0])
if (match):
    print(_date)
else: 
    regex = re.compile("[1-2][0,9][0-9]{2}[0,1][0-9][0,1,2,3][0-9][0,1,2][0-9][0-5][0-9]")
    _date = re.findall(regex, _date)
    match= re.match(regex,_date[0])
    
if (match):
    print(_date)        
else: 
    regex = re.compile("[1-2][0,9][0-9]{2}[0,1][0-9][0,1,2,3][0-9][0,1,2][0-9][0-5][0-9][0-5][0-9]")
    _date = re.findall(regex, _date)
    match= re.match(regex,_date[0])
if (match):
    print(_date)
else: 
    print("Invalid date, the format has to be YYYYMMDDHHMMSS or YYYYMMDD or YYYYMMDDHHMM or YYYYMMDDHH")

My question is how can i Pythonic and regarding Clean Coding and OOP Principals achieve this. I saw this solution and was thinking if writing multiple Try and one Catch or some how fix that code. which doen't look like the Best Practice to me.

How can i achieve this?

Mostafa Bouzari
  • 9,207
  • 3
  • 16
  • 26
  • Maybe of interest that dateutil.parser will correctly parse many date formats and raise an error for unknown formats [link](https://dateutil.readthedocs.io/en/stable/parser.html) – user19077881 May 19 '23 at 11:07
  • If the expected `date` parameter is to be a valid date format for your list, when would the passed value contain some unexpected characters? Does the value come from a user or system? – etch_45 May 19 '23 at 11:31

1 Answers1

0

i found one solution as described here. We can use the code here to check for multiple date format, and return the result then we can check if that's what we wanted or not.

Mostafa Bouzari
  • 9,207
  • 3
  • 16
  • 26