为了账号安全,请及时绑定邮箱和手机立即绑定

如何以 HHMM 形式将时间作为用户的输入,然后在当时运行一个函数

如何以 HHMM 形式将时间作为用户的输入,然后在当时运行一个函数

斯蒂芬大帝 2023-07-18 16:48:53
我正在编写一个代码,其中将使用循环多次以 HHMM 的形式询问用户时间,然后将这次时间附加到列表中。现在我希望在用户提供的列表中的不同时间执行一个函数。
查看完整描述

1 回答

?
达令说

TA贡献1821条经验 获得超6个赞

您可以使用它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"])


查看完整回答
反对 回复 2023-07-18
  • 1 回答
  • 0 关注
  • 64 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信