Home > database >  Storing datetime user input in list
Storing datetime user input in list

Time:11-21

Background -
I am a novice, with a function who's objective is to take and store 4x user inputs in respective lists, before being used in other functions in my program.

Problem -
Whilst I have been able to wrap entities_list and views_list in [ ] to have them saved in lists, when I tried to apply the same logic to start_date and end_date and run the function, I got a TypeError: strptime() argument 1 must be str, not list.

I attempted to overcome this issue by using list(). (e.g., start_date = list(start_date)). The problem with that approach, is that the list then outputs each character from the inputted date as individual values in the list. E.g. if the user enters 2020-01-01 the list is ['2', '0', '2', '0', '-', '0', '1', '-', '0', '1']

How would I ensure that the list contains the complete user inputted date? E.g. ['2', '0', '2', '0', '-', '0', '1', '-', '0', '1'] becomes ['2020-01-01']. Thank you in advance for any hints!

Code (complete function) -

def user_inputs():
    while True:
        try:
            entities_list = [int(x) for x in input("Entities for API Call:\n").split(', ')]
        except ValueError:
            print("---ERROR: MUST BE COMMA SEPERATED VALUES---")
            continue
        break
    while True:
        try:
            views_list = [int(x) for x in input("Views for API Call:\n").split(', ')]
        except ValueError:
            print("---ERROR: MUST BE COMMA SEPERATED VALUES---")
            continue
        break
    while True:
        try:
            start_date = input("Enter time in this format yyyy-mm-dd")
            time=datetime.datetime.strptime(start_date, "%Y-%m-%d")
            start_date = list(start_date)
        except ValueError:
            print("---ERROR: MUST BE YYYY-MM-DD FORMAT ---")
            continue
        break
    while True:
        try:
            end_date = input("Enter time in this format yyyy-mm-dd")
            time=datetime.datetime.strptime(end_date, "%Y-%m-%d")
            end_date = list(end_date)
        except ValueError:
            print("---ERROR: MUST BE YYYY-MM-DD FORMAT ---")
            continue
        break        
    return entities_list, views_list, start_date, end_date
user_inputs()

CodePudding user response:

How would I ensure that the list contains the complete user inputted date? E.g. ['2', '0', '2', '0', '-', '0', '1', '-', '0', '1'] becomes ['2020-01-01'].

You could use the join() method and then wrap the returned string in a list.

["".join(myList)]
  • Related