Reputation: 1200
I need to ensure the user enters the date in the following format -
12/23/1993
If it's a single digit month or day, I need a leading zero included.
I need 02/04/1998 not 2/4/1998
How can I ensure that leading zeros or 2 digits are present?
This is what I have so far
from datetime import datetime
def validate_date(d):
try:
datetime.strptime(d, '%m/%d/%Y')
return True
except ValueError:
return False
print validate_date('02/26/2009') # prints False
However, this will print true even if a single digit is entered for month/day.
Upvotes: 2
Views: 7247
Reputation: 27
Whatever user input is, you can convert it to your required format.
>>> date_string = '2/4/1998'
>>> datetime.datetime.strptime(date_string, '%m/%d/%Y').strftime('%m/%d/%Y')
'02/04/1998'
and to ensure user entered format as follows
def validate_date_format(date_string):
try:
datetime.datetime.strptime(date_string, '%m/%d/%Y')
except ValueError:
raise ValueError("Date format should be MM/DD/YYYY")
Upvotes: 1
Reputation: 3464
Not to over engineer... you can probably just check the length of the string. This will work for years between 1000-9999
from datetime import datetime
def validate_date(d):
try:
if len(d) == 10:
datetime.strptime(d, '%m/%d/%Y')
return True
else: return False
except ValueError:
return False
print(validate_date('2/26/1000'))
Upvotes: 4
Reputation: 15397
I am not aware of a way to force strptime
to validate that there is a leading 0. As you said, it's happy with both 2/4/1998 and 02/04/1998. I don't know of any way to do this other than a regular expression:
import re
regex = r'\d{2}/\d{2}/\d{4}'
if re.match(d):
# then it matches the syntax you want
But you still want to use strptime to validate the input, so you don't get some mess like '99/99/0123'.
When you put it all together, you'd need something like this:
from datetime import datetime
import re
def validate_date(d):
try:
regex = r'\d{2}/\d{2}/\d{4}'
if re.match(d):
datetime.strptime(d, '%m/%d/%Y')
return True
except ValueError:
return False
return False
If you're not familiar with regexes, this is a relatively simple one. The leading r
tells python this is a raw string, and it shouldn't process backslashes. \d
means any digit, and the {2}
and {4}
says that it should repeat (any digit) 2 and 4 times respectively.
Upvotes: 0
Reputation: 4539
I'd handle this with a loop to get input from the user.
Prompt the user for a value (let them know how it should be formatted) and then try to cast it like you're doing.
If the cast succeeds then you break the loop and continue. If it fails...
You catch the error and display the message about an invalid format and repeat step 1. Loop until you get a valid value.
good_value = false
value = ""
while good_value == false:
value = input("Insert Date in format...")
try:
datetime.strptime(d, '%m/%d/%Y')
good_value = true
except ValueError:
print("Error: Date format invalid.")
Upvotes: 0