【问题标题】:Python3: Continuously update datetime value from inside while loopPython3:从while循环内部不断更新日期时间值
【发布时间】:2016-07-30 23:54:17
【问题描述】:

我在下面的代码中遇到问题,它要求用户输入“唤醒”时间,python 脚本随后将使用该时间来计算时钟到达零之前的时间。从下面的内容来看,我认为我需要将 tdelta 计算放在 while 循环中,以便它不断检查 当前 时间。

目前,tdelta 似乎会以秒为单位检查当前时间,然后使用相同的值运行 while 循环。因此永无止境,因为它一遍又一遍地使用相同的时间。我应该在 while 循环中使用 函数 来不断检查新值,然后评估 true 还是 false?

from datetime import datetime
import time
now = datetime.now()
hms = "%s:%s:%s" % (now.hour, now.minute, now.second)

ans = input('Enter hour:minute:seconds')

s1 = hms
s2 = ans # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)

if tdelta.days < 0:
    tdelta = timedelta(days=0,
                seconds=tdelta.seconds, microseconds=tdelta.microseconds)


while tdelta.seconds != 0:
    # Use this to see what is happening inside the loop. Here it continuously prints the same time in seconds so is a continuous loop. I need to somehow update the tdelta time.
    if tdelta.seconds != 0:
        print(tdelta.seconds)
        time.sleep(1)

    else:
        print('time up...do something')

我已经尝试了上述代码的几十种变体,但都没有成功。我很感激任何提示。谢谢。

【问题讨论】:

标签: function loops python-3.x date time


【解决方案1】:

感谢 Padraic Cunningham,他提供了缺失的代码来完成这项工作。

第一步:datetime导入timedelta 第二步:tdelta -= timedelta(seconds=1)添加到while循环下的第一行。

from datetime import datetime
from datetime import timedelta

import time
now = datetime.now()
hms = "%s:%s:%s" % (now.hour, now.minute, now.second)

ans = input('Enter hour:minute:seconds')

s1 = hms
s2 = ans # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)

if tdelta.days < 0:
    tdelta = timedelta(days=0,
                seconds=tdelta.seconds, microseconds=tdelta.microseconds)


while tdelta.seconds != 0:
    tdelta -= timedelta(seconds=1)
    """Use this to see what is happening inside the loop. Here it continuously prints the same time in seconds so is a continuous loop. I need to somehow update the tdelta time."""
    if tdelta.seconds != 0:
        print(tdelta.seconds)
        time.sleep(1)

    else:
        print('time up...do something')

最终结果是命令行将倒计时到零,一旦tdelta IS 等于 0,它将从 else 语句打印。

【讨论】:

    猜你喜欢
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 2016-06-21
    • 2014-03-22
    相关资源
    最近更新 更多