Python3日期验证

时间:2018-06-01 17:03:22

标签: python python-3.x

如何在python 3中验证此日期时间 - 2018-05-30-16-54-00

当我将此日期文本传递给下面的方法时,会返回错误。

def validate(date_text):
    try:
        datetime.datetime.strptime(date_text, '%d-%b-%Y-%H-%M-%S')
    except ValueError:
        raise ValueError("Incorrect data format, should be YYYY-MM-DD-HH-MI-SS")     

1 个答案:

答案 0 :(得分:4)

修复日期时间字符串 - 它必须完全匹配。阅读the documentation

"%Y-%m-%d-%H-%M-%S"

您的字符串'%d-%b-%Y-%H-%M-%S'正在解析日期,月份名称已被删除(可识别区域设置),年份,H-M-S。

如果您需要在月/日之前验证为0,请将解析与正则表达式检查结合起来:

import re
import datetime

def validate(date_text):
    """Validates the overall structure with regex and parses the datetime using 
    strptime to test for "existing" months and times. """
    try:
        dt = datetime.datetime.strptime(date_text, '%Y-%m-%d-%H-%M-%S')
        if re.match(r"\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}", date_text) is None:
            raise ValueError()
    except ValueError:
        raise ValueError("Incorrect data format, should be YYYY-MM-DD-HH-MI-SS")    

v = ["2018-06-01-10-20-30", "2018-6-01-10-20-30", "2018-21-01-10-20-30"]
for k in v:
    try:
        print("Validating: ", k)
        validate(k)
        print("ok")
    except ValueError as e:
        print(e)

输出:

Validating:  2018-06-01-10-20-30
ok
Validating:  2018-6-01-10-20-30       # missing 0
Incorrect data format, should be YYYY-MM-DD-HH-MI-SS
Validating:  2018-21-01-10-20-30      # no 21 month possible
Incorrect data format, should be YYYY-MM-DD-HH-MI-SS