Search code examples
python-3.xdatetimetimeuser-input

How to make a datetime object from user input?


I am trying to make an alarm clock. How to make a datetime object from user-input, where the user-input is hours, minutes, and secs seperately. For example:

from datetime import datetime

# user-input: at 2:30
hr = "2"
m = "30"
s = "0"

Solution

  • from datetime import datetime
    def GetDate():
        isValid=False
        while not isValid:
            userIn = input("Type Date dd/mm/yy: ")
            try: # strptime throws an exception if the input doesn't match the pattern
                d = datetime.datetime.strptime(userIn, "%d/%m/%y")
                isValid=True
            except:
                print("Invalid")
        return d
    
    #test the function
    print(GetDate())