2

hi i would like to validate some date in python. but the problem is that i have a praticular range, for example, my date goes from 1/1/2014to 08/07/2014 . So my question is how do i validate both the format and the value. i looked at this link but it only validates the format but not the specific values.

import time
date = input('Date (mm/dd/yyyy): ')enter date here
try:
    valid_date = time.strptime(date, '%m/%d/%Y')
except ValueError:
    print('Invalid date!')

How can I validate a date in Python 3.x?

3 Answers 3

6

Rather than use time.strptime(), use datetime.datetime.strptime() and then validate the resulting object to be within your range:

from datetime import datetime, date
date_input = input('Date (mm/dd/yyyy): ')
try:
    valid_date = datetime.strptime(date_input, '%m/%d/%Y').date()
    if not (date(2014, 1, 1) <= valid_date <= date(2014, 8, 7)):
        raise ValueError('Date out of range')
except ValueError:
    print('Invalid date!')

If no exception is thrown, valid_date is bound to a datetime.date() instance.

Sign up to request clarification or add additional context in comments.

9 Comments

in your testing(if not) does the order matter? like isnt supposed to be date(1,1,2014)? just curious
@user3841581: The date() constructor always takes year, month, day as the arguments; see the linked documentation.
i tested it and i am having a problem:TypeError: 'str' object is not callable . what i did is that input: 1/1/2014 but that is the error i got
using date as a variable name?
@user3841581: then you are using date as a variable name elsewhere in your code and have rebound the name to a string somewhere.
|
2

I would like to suggest putting this into a function:

from datetime import datetime


def validate_date(input_date, first=datetime(2014, 1, 1),
                              last=datetime(2014, 8, 7),
                              fmt='%m/%d/%Y'):
    """Return a validated datetime.datetime or None.

    If the date has the wrong format return None, or if it is not in
    the range [first,last] also return None.  Otherwise return the
    input_date as a datetime.datetime object.

    """
    try:
        d = datetime.strptime(input_date, fmt)
        if not (first <= d <= last):
            raise ValueError
    except ValueError:
        return None
    else:
        return d


# Example usage...
valid_date = validate_date(input('Date mm/dd/yyyy: '))
if valid_date is not None:
    print(valid_date)
else:
    print('Date not ok!')

2 Comments

what does this function return? i would like to input a string with a date format and return turn if it is the correct format and within the specified range and false if not.
Updated solution with more detailed explanation.
2
import datetime

inputDate = input("Enter the date in format 'dd/mm/yy' : ")

day,month,year = inputDate.split('/')

isValidDate = True
try :
    datetime.datetime(int(year),int(month),int(day))
except ValueError :
    isValidDate = False

if(isValidDate) :
    print ("Input date is valid ..")
else :
    print ("Input date is not valid..")

1 Comment

It would be helpful if you could explain how this code solves the issue with a couple sentences of explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.