【问题标题】:Storing datetime user input in list在列表中存储日期时间用户输入
【发布时间】:2021-11-17 21:24:18
【问题描述】:

背景 -
我是一个新手,我的功能是在用于我的程序中的其他功能之前,将 4x 用户输入存储在各个列表中。

问题 -
虽然我已经能够将 entities_listviews_list 包装在 [ ] 中以将它们保存在列表中,但当我尝试对 @987654323 应用相同的逻辑时@ 和 end_date 并运行函数,我得到了一个 TypeError: strptime() argument 1 must be str, not list

我试图通过使用list() 来解决这个问题。 (例如,start_date = list(start_date))。这种方法的问题在于,列表随后将输入日期中的每个字符作为列表中的单独值输出。例如。如果用户输入2020-01-01,则列表为['2', '0', '2', '0', '-', '0', '1', '-', '0', '1']

如何确保列表包含用户输入的完整日期?例如。 ['2', '0', '2', '0', '-', '0', '1', '-', '0', '1'] 变为 ['2020-01-01']。提前感谢您的任何提示!

代码(完整功能)-

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()

【问题讨论】:

  • end_date = [end_date] 呢?

标签: python list datetime


【解决方案1】:

如何确保列表包含完整的用户输入日期?例如。 ['2', '0', '2', '0', '-', '0', '1', '-', '0', '1'] 变为 ['2020-01-01' ].

您可以使用join() method,然后将返回的字符串包装在一个列表中。

["".join(myList)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多