首页 > 解决方案 > 如何以 HHMM 形式将时间作为用户的输入,然后在那时运行一个函数

问题描述

我正在编写一个代码,其中将使用循环多次以 HHMM 的形式向用户询问时间,然后将这个时间附加到一个列表中。现在我希望在用户提供的列表中的不同时间执行一个函数。

标签: pythondatetimetime

解决方案


您可以使用它datetime来执行必要的计算。

在此示例中,使用解析目标时间strptime但未提供日期,因此时间部分正确但日期部分错误。然后将前三个字段(年、月、日)替换为今天的日期,以生成正确表示目标时间的日期时间对象。然后可以减去当前时间,得到一个timedelta对象,该对象表示在可以运行任务之前需要等待的时间量。

import time
import datetime


def hello():
    print("hello")


def run_at_times(func, times):

    today = datetime.date.today()
    
    for hhmm in sorted(times):
        dt = datetime.datetime.strptime(hhmm, "%H%M")
        when = datetime.datetime(*today.timetuple()[:3],
                                 *dt.timetuple()[3:6])

        wait_time = (when - datetime.datetime.now()).total_seconds()

        if wait_time < 0:
            print(f'Time {when} has already passed')
        else:
            print(f'Waiting {wait_time} seconds until {when}')
            time.sleep(wait_time)
            func()


run_at_times(hello, ["1041", "1203", "1420"])

推荐阅读