How would I limit the user input() to only entering data once per day? I was thinking maybe the datetime stamp but unsure how to implement this

Viewed 116

here is my code for retrieving the user input:

def inputQ1():
while True:
    try:
        Q1A = int(input("Rate your exercise today on scale 1-100: "))
    except ValueError:
        print("invalid value")
        continue
    else:
        return Q1A

and my code for recording the input into a list:

ansQ1 = []
ansQ1.append(inputQ1())
print(ansQ1)

how do I now ask for this user input again, just once per day?

1 Answers

You can use datetime.datetime.now():

from datetime import datetime

def inputQ1():
    while True:
        try:
            Q1A = int(input("Rate your exercise today on scale 1-100: "))
        except ValueError:
            print("invalid value")
            continue
        else:
            return Q1A

dates = []
ansQ1 = []
while True:
    today = datetime.now().strftime("%Y-%m-%d")
    if today not in dates:
        ansQ1.append(inputQ1())
        dates.append(today)
        print(ansQ1)

Where datetime.now().strftime("%Y-%m-%d") returns the current date in the from of 2020-05-21.

One thing to note, it isn't a very good practice to rely on try - except to convert an input into an int. Instead, use the str.isdigit() method:

def inputQ1():
    while True:
        Q1A = input("Rate your exercise today on scale 1-100: ")
        if Q1A.isdigit():
            return int(Q1A)
        print("invalid value")
Related