0

So I have the following input prompt:

start_date = input("What is the start date in format mm/dd/yyyy: ")

I want to make it so that if someone does not give an input in the proper format they are simply reprompted to do it again. Format is provided above, so something like January 20, 2020 being 01/20/2020, and the preceding 0 for January is important. I guess you'd also have to make sure they don't input impossible values like a 13th month of a 40th day of the month. I assume it would be something like:

while True:
start_date = input("What is the start date in format mm/dd/yyyy: ")
if ##properly formatted
    break
Jacob
  • 3
  • 2
  • 1
    Does this answer your question? [How do I validate a date string format in python?](https://stackoverflow.com/questions/16870663/how-do-i-validate-a-date-string-format-in-python) – MendelG Jun 22 '20 at 22:40

1 Answers1

0

The datetime module, through its datetime class, provides a very helpful method called strptime(), that it seems like what you need for your case. You can read more about it here

You could use it as follows:

while True:
    try:
        start_date = datetime.datetime.strptime(
            input("What is the start date in format mm/dd/yyyy: "), "%m/%d/%Y"
            )
    except ValueError:
        print("Invalid date")
    else:
        break

# You can keep using the start_date variable from now on
revliscano
  • 2,227
  • 2
  • 12
  • 21