Checking for valid date input and convert appropriately

rob.marshall17 at rob.marshall17 at
Fri Feb 22 07:20:20 CET 2013

The datetime function: strptime() DOES check the date for validity. So try something like:

from datetime import datetime

def get_date():
  while True:
      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)

More information about the Python-list mailing list