user3841581
user3841581

Reputation: 2747

how to validate a date in python

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?

Upvotes: 2

Views: 15223

Answers (3)

hammadi benjlila
hammadi benjlila

Reputation: 21

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

Upvotes: 2

FredrikHedman
FredrikHedman

Reputation: 1253

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!')

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1122142

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.

Upvotes: 6

Related Questions