需要帮助将时间戳正确传递到字典

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

一切正常,但是令我困惑的一件事是创建一个密钥,该密钥存储在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'}}

谢谢您的帮助!

inlove2100 回答:需要帮助将时间戳正确传递到字典

您需要在每次迭代中分别创建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)
,

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

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

now = datetime.now()

并使用

user_list['date'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
本文链接:https://www.f2er.com/3167091.html

大家都在问