Search code examples
python-3.xdatetimetimeuser-inputdays

Python: Adding Input To A Time Elapsed Calculator


I wrote a program that calculates the number of days between two dates. I'm having trouble writing the program so that it asks for user input. How can I do this without raising any errors?

import datetime     

class User:  

    def __init__(self, date_one, date_two):
        self.date_one = date_one
        self.date_two = date_two

    def age(self):

        yyyy = int(self.date_one[0:4])
        mm = int(self.date_one[4:6])
        dd = int(self.date_one[6:8])

        yyyy2 = int(self.date_two[0:4])
        mm2 = int(self.date_two[4:6])
        dd2 = int(self.date_two[6:8])

        d1 = datetime.date(yyyy, mm, dd)
        d2 = datetime.date(yyyy2, mm2, dd2)

        time_elapsed = (d1 - d2).days

        return int(time_elapsed)


user = User("19991212", "20001212")
print(user.age())

Solution

  • date1 = input("Enter Date")
    date2 = input("Enter 2nd Date")
    user = User(date1, date2)
    print(user.age())
    

    input() will return a string and you can store it in a variable which you can use as the parameter for the User constructor.