Checking for valid date input and convert appropriately
python at mrabarnett.plus.com
Thu Feb 21 22:46:34 CET 2013
On 2013-02-21 21:22, Ferrous Cranus wrote:
> Τη Πέμπτη, 21 Φεβρουαρίου 2013 10:14:13 μ.μ. UTC+2, ο χρήστης MRAB έγραψε:
>> 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.
Correction: the datetime object has the 'strftime' for formatting the
> I don't need to store the date i just want to make sure is entered correctly.
> I would like to have the user type the date like
> 21 02 2013
> and then convert it to 2013-02-21 because thats how mysql wants the date in order to store it.
> Please show me how to write this.
The 'strptime' method parses the string and returns a datetime object,
and you can then use that object's 'strftime' method to format it to
the desired string.
> Also, can you show me how to write it that if so even if the user entered date is wrong it doesn't just crash the cgi-script?i know i can use tr: expect: but i want to avoid it, somehow i need to check the date in the same if statemnt like i do with the other user defined varibles for validity.
It _doesn't_ crash the cgi-script.
You're telling it to exit if an exception is raised.
If you don't want the cgi-script to exit, don't call 'exit'.
> if( task and ( price and price.isdigit() and price.__len__() <= 3 ) and ( date and datetime.strptime(date, '%Y-%m-%d') ) ):
More information about the Python-list