Search code examples
pythonoopdatetime-formatpython-datetimegdelt

How to allow (accept) multiple Date formats?


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?


Solution

  • 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.