python - 如何使用日期时间计算持续时间和停止时间?

标签 python python-2.7 datetime

我正在使用 Python 2.7,并希望使用日期时间函数来计算用户定义的时间来运行小型泵。我知道我遗漏了一些明显的东西,但我一直在搜索,直到我看不清为止。我有一个 textCtrl,用户将输入他希望泵运行的分钟数。然后单击按钮将启动调度程序并检查是否到了关闭泵的时间:

def timedPump(val):
    now = datetime.datetime.now()
    timeOff = now + datetime.timedelta(minutes=int(val))
    if timeOff > now:
        print 'pumpOn'
    else:
        print 'pumpOff'
    return True

问题是 datetime.datetime.now() 每次都会更新。我如何才能使 now = 单击按钮的时间?

最佳答案

这将是我对问题的解决方案:

from time import sleep

def pumpcheck(timer_in_minutes):
    time_clicked = datetime.datetime.now()
    now = time_clicked
    timeDiff = datetime.timedelta(minutes=int(timer_in_minutes))
    while (time_clicked + timeDiff > now):
        print 'pumpOn'
        now = datetime.datetime.now()
        sleep(2)
    print 'pumpOff'

它保存按下按钮的时间,然后循环检查,如果时间被读取,如果没有,它会更新当前时间,表示泵仍处于打开状态并休眠一会儿,以免阻塞 cpu 资源.当时间到了时,它会说 pumpoff

关于python - 如何使用日期时间计算持续时间和停止时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42169340/

相关文章:

python - 使用 Flexmock datetime.datetime.now 模拟

javascript - 将日期字符串转换为另一种字符串格式

python - 印度语 NLTK CorpusReader

python - 通过回调更新 Dash 数据表

python - 如何获取 DataFrame GroupBy 对象的列名?

python - 使用 Unicode 发送 HTML 邮件

python - 在 Ubuntu 14.04 上使用 Python 连接到 Microsoft Azure SQL 数据库

python-2.7 - python map 和 numpy vectorize 的不同结果

python - 为什么 dicts 比任何 int 都大?

php - 当 PHP 是您的主要语言时,在 SQL Server 数据库中存储日期/时间的首选格式是什么?