【问题标题】:How to limit the time input to only be accpetable within a timeperiod in Python如何将时间输入限制为仅在 Python 中的某个时间段内可接受
【发布时间】:2021-12-25 18:17:52
【问题描述】:

我已经成功创建了一个函数,通过导入模块 Datetime 来询问用户有效时间。如果用户没有输入有效时间,则将询问该问题,直到他/她输入。 但问题是我目前经营的动物园在 08:00 - 22:00 之间开放。如何扩展我的代码,以便用户只能输入该时间段之间的有效时间?帮助将不胜感激。

代码:

def input_time():

    while True:
        try:
            time = input("What time do you plan to be here? (HH:MM): ")
            pattern_time = ('%H:%M')
            time = datetime.strptime(time, pattern_time)
        except ValueError:
            print("Not a valid time,try again")
            continue
        else:
            break
    return time

time = input_time()

【问题讨论】:

  • 我猜这是 Python 吧?
  • 是的,我没有说明它是 Python

标签: python datetime input time range


【解决方案1】:

对不起,没有人回答这个问题。 time_struct 提供了可以测试的成员字段:

while True:
  try:
    t = input("What time do you plan to be here? (HH:MM): ")
    pattern_time = ('%H:%M')
    t = time.strptime(t, pattern_time)
    if not (8 <= t.tm_hour <= 22):
      print("The zoo is only open from 8:00 to 22:00")
      continue
  except ValueError:
    print("Not a valid time, try again")
    continue
  else:
    break
return t

另外,请注意变量名。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多