How to make sure MM/DD/YYYY format actually works and prints in other file?

I have been having issues in Python making this code work. I am trying to make a loop in which I receive a birthdate and make sure it is in the MM/DD/YYYY format. But, whenever I try to run the program with the input formatted I still receive the Error message I coded to print out.

    from datetime import datetime

    a1 = open(to_file,'a')
    def confirm_date(d):  
        a_value = False
        value = ""
        while a_value == False:
            value = input("Insert BIRTHDDATE in  MM/DD/YYYY format including slashes: ")
                datetime.strptime(d, '%m/%d/%Y')
                a_value = True
                if a_value == True:
                  c1 = value
                    c1 != value
                except ValueError:
                       print("Error: Date format invalid.")
    c = confirm_date(d)
    print("Thank you! Goodbye!")

>Solution :

As presented, your code has several indentation issues that will prevent it from running at all. Remember in Python indentation is used to represent a code block.

It’s also good practice (pythonic) to use descriptive variable names to keep track of everything.

I’ve rewritten your script in line with this, assuming you’ve got a formatting issue that hasn’t been properly transferred to StackOverflow.

from sys import argv
from datetime import datetime

script, to_file = argv

output_file = open(to_file, "a")

first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
city = input("Enter city you are in: ")
state = input("Enter state you are in: ")

def get_date():
    is_valid_date = False
    date_str = ""

    while not is_valid_date:
        date_str = input("Insert BIRTHDDATE in  MM/DD/YYYY format including slashes: ")

            datetime.strptime(date_str, "%m/%d/%Y")
            # if the previous line does not throw an error, it can be parsed as a valid date,
            # so we'll exit the loop
            is_valid_date = True

        except ValueError:
            print("Error: Date format invalid.")

    return date_str

birthday = get_date()

    first_name + " " + last_name + " " + city + " " + state + " " + birthday + "\n"
print("Thank you! Goodbye!")


Note the indentation within the get_date function. The try-except block is now aligned. You could also use an infinite while loop with a break statement, but I’ve kept it in line with the way you’ve written it.

You’ve made a good start. Hopefully that clarifies things for you. If not, please add more information to your question.

Leave a Reply