【问题标题】:Need help passing timestamp to dictionary correctly需要帮助将时间戳正确传递给字典
【发布时间】:2020-02-29 17:21:17
【问题描述】:

我目前正在尝试制作一个请求用户输入的程序,该程序被存储到字典和嵌套字典中。

一切正常,但让我感到困惑的一件事是创建一个键,该键存储字典存储在 while 循环中的日期时间。

from datetime import datetime

now = datetime.now()
user_list = {}
list_of_users = {}

while True: 

    print("Please enter your desired username below")
    username = input("What is your username? ")

    if username == 'print':
        break

    else:
        first = input("What is your first name? ")

        list_of_users.update({username : user_list})
        user_list['given name'] = first
        user_list['given name'] = username
        user_list['date'] = now.strftime("%Y-%m-%d %H:%M:%S")

print(list_of_users)

这是一个示例输出。如您所见,字典的日期值具有相同的确切时间。我希望时间基于数据存储在 while 循环中的时间:

Please enter your desired username below
What is your username? monkey
What is your first name? john
Please enter your desired username below
What is your username? simon
What is your first name? whistler
Please enter your desired username below
What is your username? print
{'monkey': {'given name': 'simon', 'date': '2019-11-04 13:16:35'}, 'simon': {'given name': 'simon',     'date': '2019-11-04 13:16:35'}}

提前感谢您的帮助!

【问题讨论】:

    标签: python datetime dictionary input while-loop


    【解决方案1】:

    您需要在每次迭代中分别创建now。 现在您只在程序开始时创建日期对象,因此它在其余的执行过程中保持不变。

    from datetime import datetime
    
    user_list = {}
    list_of_users = {}
    
    while True: 
    
      print("Please enter your desired username below")
      username = input("What is your username? ")
    
      if username == 'print':
        break
      else:
        first = input("What is your first name? ")
        now = datetime.now()
        list_of_users.update({username : user_list})
        user_list['given name'] = first
        user_list['given name'] = username
        user_list['date'] = now.strftime("%Y-%m-%d %H:%M:%S")
    
        print(list_of_users)
    

    【讨论】:

    • 嘿,谢谢你给我发消息。我运行了您提供的代码。在第一次迭代中,时间是正确的。但是如果我在第一次迭代后输入更多的字典值,那么两个字典输入的日期值是相同的。我的意图是每次迭代或字典键的日期值都是唯一的。
    【解决方案2】:

    您在代码开头初始化了变量now,并在while循环中使用它。

    如果你想要正确的输出,你需要删除

    now = datetime.now()
    

    并使用

    user_list['date'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    

    【讨论】:

    • 谢谢。我从文件开头删除了 'now = datetime.now()',现在只使用 'user_list['date'] = datetime.now().strftime("%Y-%m-%d %H :%M:%S")' 在循环内部,但在 else 语句中。我发布的其他解决方案也有同样的问题,如果我运行迭代两次,那么两个字典键的日期值(更具体地说是时间)保持不变。
    猜你喜欢
    • 1970-01-01
    • 2018-11-15
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多