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
You can use Regex 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".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.