使用Python正则表达式验证日期格式

时间:2018-01-30 08:16:17

标签: python regex

我想检查用户输入的日期格式是否与以下内容匹配:

Jan 5 2018 6:10 PM

Month: First letter should be caps, followed 2 more in small. (total 3 letters)
<Space>: single space, must exist
Date: For single digit it should not be 05, but 5
<Space>: single space, must exist
Hour: 0-12, for single digit it should not be 06, but 6
Minute: 00-59
AM/PM

我正在使用以下正则表达式并尝试匹配:

import re,sys
usr_date = str(input("Please enter the older date until which you want to scan ? \n[Date Format Example: Jan 5 2018 6:10 PM] :  "))

valid_usr_date = re.search("^(\s+)*[A-Z]{1}[a-z]{2}\s{1}[1-31]{1}\s{1}[1-2]{1}[0-9]{1}[0-9]{1}[0-9]{1}\s{1}[0-12]{1}:[0-5]{1}[0-9]{1}\s{1}(A|P)M$",usr_date,re.M)

if not valid_usr_date:
    print ("The date format is incorrect. Please follow the exact date format as shown in example. Exiting Program!")
    sys.exit()

但是,即使格式正确,也会出现syntax wrong错误。我做错了什么。

2 个答案:

答案 0 :(得分:8)

我不会使用正则表达式,因为你无法实际验证日期本身(例如,正则表达式会很乐意接受dynamic result = JObject.Parse(source); int id = result.321.basic_info.user_id; )。

相反,请使用Abc 99 9876 9:99 PM

strptime

如果字符串采用“错误”格式,您将获得from datetime import datetime string = 'Jan 5 2018 6:10 PM' datetime.strptime(string, '%b %d %Y %I:%M %p')

这种方法唯一明显的“问题”是,由于某种原因,您需要将日期和小时设置为零填充,而ValueError似乎没有这样的指令。

包含所有可用指令的表格为here

答案 1 :(得分:1)

您可以使用一个解析输入字符串并尝试返回datetime对象的函数,如果它不能引发ValueError

from datetime import datetime

def valid_date(s):
    try:
        return datetime.strptime(s, '%Y-%m-%d %H:%M')
    except ValueError:
        msg = "Not a valid date: '{0}'.".format(s)
        raise argparse.ArgumentTypeError(msg)