【问题标题】:append every new time into list将每个新时间附加到列表中
【发布时间】:2021-12-27 09:51:50
【问题描述】:

如何将新时间添加到列表中?

import time

time_status = time.strftime('%H:%M:%S')
time_list = []
while True:
    time_list.append(time_status)
    print(time_list)
    time.sleep(59)

输出应该是:

['17:48:50','17:48:51','17:48:52','17:48:53']

【问题讨论】:

  • 你想如何结束循环?此外,对于任何时间范围而言,输出过于规律和可预测,无法进行任何急切的等待。
  • 按Ctrl+C
  • 你不能等待用户输入并在最后建立列表。或者您是否需要每秒拍摄一次快照?
  • 我每秒都需要那个快照。

标签: python-3.x list time


【解决方案1】:

一方面,您必须在循环中更新time_status。然后你应该等待不到一秒钟,不要做太多急切的等待:

import time

time_list, crnt = [], None
while True:
    while (time_status := time.strftime('%H:%M:%S')) == crnt:
        pass
    time_list.append(crnt := time_status)
    print(time_list)
    time.sleep(0.95)

['11:36:40']
['11:36:40', '11:36:41']
['11:36:40', '11:36:41', '11:36:42']
['11:36:40', '11:36:41', '11:36:42', '11:36:43']
['11:36:40', '11:36:41', '11:36:42', '11:36:43', '11:36:44']

【讨论】:

    猜你喜欢
    • 2012-12-20
    • 2022-11-16
    • 2019-03-03
    • 2014-07-28
    • 2019-03-29
    • 2021-12-13
    • 1970-01-01
    • 2016-06-25
    • 2016-02-12
    相关资源
    最近更新 更多