简体   繁体   中英

Python3 Date Validation

How can I validate this date time in python 3 - 2018-05-30-16-54-00 ?

When I pass this date text to below method , an error is returned.

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

Fix the datetime string - it must match exactly. Read the documentation .

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

Your string '%d-%b-%Y-%H-%M-%S' is parsing day, month name abreviated (locale aware), year, HMS.

If you need to validate to 0 before the months/days etc, combine your parsing with a regex check:

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)

Output:

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

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.

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