You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何限制用户输入的时间仅在指定时间段内有效

实现方案

你只需要在原有格式校验的基础上,新增开放时间段的校验逻辑即可,具体修改如下:

  • 首先确保代码开头导入datetime模块(原有代码缺了这行)
  • 在时间格式校验通过后,新增和开放时间08:00、闭园时间22:00的对比判断,不符合时间段要求就提示重新输入

修改后的完整代码如下:

import datetime

def input_time():
    # 预先定义开放、闭园的时间对象
    open_time = datetime.datetime.strptime('08:00', '%H:%M')
    close_time = datetime.datetime.strptime('22:00', '%H:%M')
    while True:
        try:
            input_str = input("请问你计划什么时间到访?(格式HH:MM):")
            user_time = datetime.datetime.strptime(input_str, '%H:%M')
        except ValueError:
            print("时间格式无效,请重新输入")
            continue
        # 新增时间段校验
        if not (open_time <= user_time <= close_time):
            print("动物园开放时间为08:00-22:00,请输入该时间段内的时间")
            continue
        else:
            break
    return user_time

time = input_time()

逻辑说明

  • 我们提前构造了和用户输入同格式的开闭园时间对象,不需要单独拆分小时、分钟做判断,代码更简洁不易出错
  • 只要不符合格式要求、或者不在开放时间段内,都会循环提示用户重新输入,直到获取到有效时间为止
  • 输入输出的提示已经全部替换为中文,适配国内使用场景

内容的提问来源于stack exchange,提问作者David Gallego

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 00:24:02