【问题标题】:Add date time to list without it re ordering the date and time value将日期时间添加到列表而不重新排序日期和时间值
【发布时间】:2019-12-17 22:36:53
【问题描述】:

嘿,伙计们,我有这个用户输入,在输入后它会将其添加到列表中,并将其从最新条目排序到之前的条目并打印出来。我想要做的是处理我想要的每个用户条目添加时间和日期,以便我知道输入的时间。现在发生的情况是它重新排列日期和时间条目,因此格式在列表中不可读。有谁知道我怎样才能阻止这种情况发生,但仍会随每个条目附加到列表中,因此格式正确?非常感谢你

from datetime import datetime 

def status():

    all_status_updates = []
    today = datetime.now()
    while True: 
        stat = input("Type Status Update Here...\n")
        if stat != "exit":
            #all_status_updates.append(stat)
            all_status_updates.extend((today, stat))
            print(all_status_updates[::-1])
        elif stat == "exit":
            break

status()

【问题讨论】:

  • 在我们当前的代码中,您为每个条目设置相同的日期
  • 您具体想要什么格式?您可以使用 datetime.now().strftime("%d/%m/%Y %H:%M:%S") 等限定符修改日期时间对象
  • 这很有效,非常感谢你,但它显示每个帖子的修复时间都是相同的?

标签: python python-3.x list datetime append


【解决方案1】:

目前,您的代码在 while 循环之外实例化日期时间。这意味着每次您在输入字段中输入一个新字符串时,它都会采用预设的日期时间而不是创建一个新的日期时间。简单修复:

from datetime import datetime 

def status():

    all_status_updates = []
    while True: 
        stat = input("Type Status Update Here...\n")
        if stat != "exit":
            today = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
            all_status_updates.extend((today, stat))
            print(all_status_updates[::-1])
        elif stat == "exit":
            break

status()

我还添加了.strftime("%d/%m/%Y %H:%M:%S") 后缀,使日期时间更易于阅读。您可以更改这些修饰符以满足您的需要。

这里,在上面的代码示例中,日期时间仅在用户输入不是“退出”的文本字符串时才被调用。您也可以将其放入 while 循环的主体中,但大部分时间都不会使用它。

【讨论】:

  • 啊,我知道这很简单,非常感谢
  • 嘿,不用担心,很高兴为您提供帮助。欢迎来到 SO
猜你喜欢
  • 2017-11-17
  • 1970-01-01
  • 1970-01-01
  • 2016-08-09
  • 2015-09-21
  • 2021-12-09
  • 2020-12-01
  • 1970-01-01
  • 2015-10-13
相关资源
最近更新 更多