0

I am trying to get a program to check to make sure a string variable "date" is in the correct format YYYY-MM-DD. I attempted this with the code below.

def check_date_format(date):
    has_correct_dashes = check_dashes(date)
    split_date = date.split('-')
    while not has_correct_dashes or (split_date[0]) != 4 or len(split_date[1]) != 2 or \
            len(split_date[2]) != 2:
        date = input('ERROR: Must follow 1970-01-01 format, try again: ')
        has_correct_dashes = check_dashes(date)
        split_date = date.split('-')
    return date

My problem is that the while loop is never returning true, but I'm not sure why (even when given the correct format).

Thanks

Joey Quatela
  • 9
  • 1
  • 2
  • 1
    shouldn't `(split_date[0]) != 4` be `len(split_date[0]) != 4` ...? and what is `has_correct_dashes` ? – Sudhir Bastakoti Dec 09 '21 at 02:43
  • 4
    You aren't modifying `date`, and the caller presumably already has a reference to the string. There's no need to return the value, and there's no need to reinvent the wheel: just use `datetime.datetime.strptime(date, "%Y-%m-%d")`, which will either succeed or raise a `ValueError`. – chepner Dec 09 '21 at 02:48
  • 2
    Does this answer your question? [In python, how to check if a date is valid?](https://stackoverflow.com/questions/9987818/in-python-how-to-check-if-a-date-is-valid) – Ryan Fu Dec 09 '21 at 02:50
  • I have given you two duplicates: to show how to validate dates generally, and to explain what is wrong with your logic. – Karl Knechtel Dec 09 '21 at 03:09

1 Answers1

0

You can use Regex and a recursive function to solve this.

import re

regex = re.compile("[0-9]{4}\-[0-9]{2}\-[0-9]{2}")

def check_date_format(date):
    match = re.match(regex, date)

    if (match):
        return date

    else: 
       return check_date_format(input("Invalid date, try again: "))

print(check_date_format("1969-07-20"))

# Prints "1969-07-20".
kggn
  • 73
  • 1
  • 8