Search code examples
pythondatedatetimeuser-interfacestrftime

How to get user input as date format


I am trying to create a program to handle my finances, and one issue I always seem to have is not being able to input a date from the user interface, then subtracting or adding it to the current date to determine if it is overdue or coming soon.

How can I achieve this?

I tried converting the string to an int and float, and it comes up with a ValueError: invalid literal for int() with base 10: '(date here)'.

date = datetime.today().strftime('%d/%m/%Y')
show_str("Today's date is:\n-> " + str(date) +"\n")

biller_name = get_str("What is the billers name?\n-> ")

due_date = get_int("When is your bill due?\n(Enter date as \"DD/MM/YYYY\")\n-> ")
if due_date < date:
    userDate = datetime(due_date)
    x = userDate - date
    print(x)

Solution

  • using datetime object you can easily check for due or coming soon.

    Code:

    from datetime import datetime
    date_format = "%d/%m/%Y"
    
    usr_input=input("When is your bill due?\n(Enter date as \"DD/MM/YYYY\")\n-> ")
    
    today_date=datetime.today().strftime(date_format)
    today_date = datetime.strptime(today_date, date_format)
    
    due_date = datetime.strptime(usr_input, date_format)
    
    x = abs(today_date-due_date)
    if due_date<today_date:
        print(f"{x.days} Days Overdue")
    elif due_date>today_date:
        print(f"{x.days} Days: Remaining")
    else:
        print("Today is the last date")
    

    Output:

    When is your bill due?
    (Enter date as "DD/MM/YYYY")
    -> 04/02/2023
    Today is the last date
    
    When is your bill due?
    (Enter date as "DD/MM/YYYY")
    -> 08/09/2023
    216 Days: Remaining
    
    When is your bill due?
    (Enter date as "DD/MM/YYYY")
    -> 12/04/2022
    298 Days Overdue
    

    Note* I obtained in days if you wanted you can change as your desired.. [months, years etc.]