Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating date format with Python regex

Tags:

python

regex

I want to check if the format of the date input by user matches the below:

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

I'm using the below regex and trying to match:

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

But, even for the correct format it gives a syntax wrong error. What am I doing wrong.

like image 984
dig_123 Avatar asked Jul 12 '26 09:07

dig_123


2 Answers

I would not use regex for that, as you have no way to actually validate the date itself (eg, a regex will happily accept Abc 99 9876 9:99 PM).

Instead, use strptime:

from datetime import datetime

string = 'Jan 5 2018 6:10 PM'
datetime.strptime(string, '%b %d %Y %I:%M %p')

If the string would be in the "wrong" format you'd get a ValueError.

The only apparent "problem" with this approach is that for some reason you require the day and hour not to be zero-padded and strptime doesn't seem to have such directives.

A table with all available directives is here.

like image 118
DeepSpace Avatar answered Jul 15 '26 05:07

DeepSpace


You could use a function which parses the input string and tries to return a datetime object, if it can't it raises an 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)
like image 37
AnythingIsFine Avatar answered Jul 15 '26 04:07

AnythingIsFine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!