简体   繁体   English

检查日期格式 YYYY-MM-DD

[英]Checking a date format YYYY-MM-DD

I am trying to get a program to check to make sure a string variable "date" is in the correct format YYYY-MM-DD.我正在尝试让一个程序检查以确保字符串变量“日期”的格式正确为 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).我的问题是while循环永远不会返回true,但我不确定为什么(即使给出了正确的格式)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM