【问题标题】:Python: How to create a program that reads in a time in 24 hr format and displays the time after adding 1 second to the time?Python:如何创建一个以 24 小时格式读取时间并在时间增加 1 秒后显示时间的程序?
【发布时间】:2020-07-27 16:36:27
【问题描述】:
hr = int(input("Enter current hr:"))
min= int(input("Enter current min:"))
sec = int(input("Enter current sec:"))
print("Clock time now is",hr,":",min,":",sec)
sec= sec+1
print("After 1 second, the time is",hr,":",min,":",sec)

我如何也将输入限制在一定范围内?像小时的输入只接受0-23和分钟0-50秒0-59的范围?以及如何使 sec + 1 自动更新小时和分钟的结束时间?假设 23 : 59 : 59+1 = 00:00:00

【问题讨论】:

标签: python python-3.x datetime python-requests pycharm


【解决方案1】:

您可以使用 datetime 包来实现这一点。虽然你不能阻止用户输入错误的值,但同样可以通过 try-exception 引发错误。

from datetime import time
time_input = input('Enter a time in the format HH:MM:SS \n')
# input 15:25:23
try:
    h, m, s = map(int, time_input.split(':'))
    res = time(hour=h, minute=m, second=s+1)
    print(res)
except ValueError as e:
    print(e)

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 2020-02-23
    • 2011-10-28
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多