George George - 1 month ago 5
Python Question

Validating date (both format and value)

I read this and got really interested: Validating date format using regular expression

so I started writing my own version of the date validation function, I think I am close, but not quite, and I would like some suggestion as well as tips. I have spend a lot of time trying to tweak the function.

import re
import datetime

# Return True if the date is in the correct format
def checkDateFormat(myString):
isDate = re.match('[0-1][0-9]\/[0-3][0-9]\/[1-2][0-9]{3}', myString)
return isDate

# Return True if the date is real date, by real date it means,
# The date can not be 00/00/(greater than today)
# The date has to be real (13/32) is not acceptable
def checkValidDate(myString):
# Get today's date
today = datetime.date.today()
myMaxYear = int(today.strftime('%Y'))

if (myString[:2] == '00' or myString[3:5] == '00'):
return False

# Check if the month is between 1-12
if (int(myString[:2]) >= 1 or int(myString[:2]) <=12):
# Check if the day is between 1-31
if (int(myString[3:5]) >= 1 or int(myString[3:2]) <= 31):
# Check if the year is between 1900 to current year
if (int(myString[-4:]) <= myMaxYear):
return True
else:
return False

testString = input('Enter your date of birth in 00/00/0000 format: ')

# Making sure the values are correct
print('Month:', testString[:2])
print('Date:', testString[3:5])
print('Year:', testString[-4:])

if (checkDateFormat(testString)):
print('Passed the format test')
if (checkValidDate(testString)):
print('Passed the value test too.')
else:
print('But you failed the value test.')
else:
print("Failed. Try again")


Question 1: Is there other way (better) to do
int(myString[3:5])
when I want to compare if it is valid? I feel my method is very repetitive, and this function must require 00/00/0000, otherwise it will break. So the function isn't all that useful in that sense. Especially the way I handle my
00/01/1989
, it is just simply comparing
if
they are indeed
00
.

Question 2: There are many
if
statement, I wonder are there better way to write this test?

I would like to learn more about programming in python, any suggestion or advice will be greatly appreciated. Thank you very much.

Answer

Like many things in python there's already underlying capabilities to check dates. Assuming you aren't just doing this as an academic exercise the most straightforward way to validate a date is to try and create it.

import datetime

minyear = 1900
maxyear = datetime.date.today().year

mydate = '12/12/2000'
dateparts = mydate.split('/')
try:
    if len(dateparts) != 3:
       raise ValueError("Invalid date format")
    if int(dateparts[2]) > maxyear or int(dateparts[2]) < minyear:
       raise ValueError("Year out of range")
    dateobj = datetime.date(int(dateparts[2]),int(dateparts[1]),int(dateparts[0]))
except:
    // handle errors

if datetime.date is given an invalid date it will complain, eg:

datetime.date(2000,45,23)

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    datetime.date(2000,45,23)
ValueError: month must be in 1..12
Comments