Checking for valid date input and convert appropriately

MRAB python at
Thu Feb 21 21:14:13 CET 2013

On 2013-02-21 19:38, Ferrous Cranus wrote:
> import datetime from datetime

Should be:

from datetime import datetime

> try:
>      datetime.strptime( date, '%d %m %Y' )

That parses the date and discards the result.

>      date = date.strptime( '%Y-%m-%d' )

'date' is a string, it doesn't have a 'strptime' method.

When you parsed the date you got a datetime object; _that_ has the
'strptime' method.

> except ValueError:
>      print( "<h2><font color=red>H ημερομηνία πρέπει να εισαχθεί στην σωστή μορφή => 21 05 2013!" )
>      sys.exit(0)
> ================================
> Hello, a have an html that among other thing require the user to insert a valid date.
> The user must enter a date like "21 02 2013"
> a) first i need to check if the entered date was inserted properly as above
> b) convert the entered date to '%Y-%m-%d' which is an appropriate mysql date type format.
> Also it would be nice if i could check the user entered date within an if statement like i check all my other fields instead of creating an extra ;try' statemnt just for checking tha date
> =================================
> if( task and ( price and price.isdigit() and price.__len__() <= 3 ) and ( date and datetime.strptime(date, '%Y-%m-%d') ) ):
> =================================
> I want it to be written like the above, but if the user entered date is not valid somehow i need to catch the exception otherwise the cgi-script displays python errors.

More information about the Python-list mailing list