Checking for valid date input and convert appropriately

Ferrous Cranus nikos.gr33k at gmail.com
Fri Feb 22 05:06:31 EST 2013


Τη Παρασκευή, 22 Φεβρουαρίου 2013 8:20:20 π.μ. UTC+2, ο χρήστης rob.mar... at gmail.com έγραψε:
> The datetime function: strptime() DOES check the date for validity. So try something like:
> 
> 
> 
> from datetime import datetime
> 
> 
> 
> def get_date():
> 
>   while True:
> 
>     try:
> 
>       date_in = raw_input("Enter date (dd mm yyyy): ")
> 
>       date_out = datetime.strptime(date_in,"%d %m %Y").strftime("%Y-%m-%d")
> 
>       return date_out
> 
>     except ValueError:
> 
>       print "Invalid date: {}, try again...".format(date_in)

Thank you very very much!! i cannot beleive that it was so easy, a matter of one line of coding!

date = datetime.strptime(date,"%d %m %Y").strftime("%Y-%m-%d")

Cna you please explain in to me?
This line checks the date variable for valid pattern entry and then also tranforms the date to the othjer pattern?

And if there is a way to embed this line to the existing if() statemtn along with the othwr variables check that would be perfect!!




More information about the Python-list mailing list