<<<TimeString for format converting in 24-hour notation is 15:20 >>>Time in 12-hour notation is: 03:20 PM === <<<TimeString for format converting in 24-hour notation is 27:10 TimeFormatException: Invalid Value for Hour! === <<<TimeString for format converting in 24-hour notation is 16:78 TimeFormatException: Invalid Value for Minute! === <<<TimeString for format converting in 24-hour notation is abc TimeFormatException: Invalid Value for Time! === <<<TimeString for format converting in 24-hour notation is 6:30 >>>Time in 12-hour notation is: 06:30 AM End of program根据输出重新编写代码
时间: 2023-06-18 07:07:40 浏览: 119
cyrillic-to-translit-js:用于将 Cyrillic 符号转换为 Translit 的超轻量级 JavaScript 库,反之亦然
```python
class TimeFormatException(Exception):
pass
def convert_time(time_string):
try:
hour, minute = time_string.split(":")
hour, minute = int(hour), int(minute)
if hour < 0 or hour > 23:
raise TimeFormatException("Invalid Value for Hour!")
if minute < 0 or minute > 59:
raise TimeFormatException("Invalid Value for Minute!")
if hour < 12:
am_pm = "AM"
if hour == 0:
hour = 12
else:
am_pm = "PM"
if hour > 12:
hour -= 12
return "{:02d}:{:02d} {}".format(hour, minute, am_pm)
except ValueError:
raise TimeFormatException("Invalid Value for Time!")
print("<<<TimeString for format converting in 24-hour notation is 15:20 >>>Time in 12-hour notation is:", convert_time("15:20"))
print("<<<TimeString for format converting in 24-hour notation is 27:10", end=" ")
try:
print(">>>TimeFormatException:", end=" ")
print(convert_time("27:10"))
except TimeFormatException as e:
print(e)
print("<<<TimeString for format converting in 24-hour notation is 16:78", end=" ")
try:
print(">>>TimeFormatException:", end=" ")
print(convert_time("16:78"))
except TimeFormatException as e:
print(e)
print("<<<TimeString for format converting in 24-hour notation is abc", end=" ")
try:
print(">>>TimeFormatException:", end=" ")
print(convert_time("abc"))
except TimeFormatException as e:
print(e)
print("<<<TimeString for format converting in 24-hour notation is 6:30 >>>Time in 12-hour notation is:", convert_time("6:30"))
print("End of program")
```
输出:
```
<<<TimeString for format converting in 24-hour notation is 15:20 >>>Time in 12-hour notation is: 03:20 PM
<<<TimeString for format converting in 24-hour notation is 27:10 >>>TimeFormatException: Invalid Value for Hour!
<<<TimeString for format converting in 24-hour notation is 16:78 >>>TimeFormatException: Invalid Value for Minute!
<<<TimeString for format converting in 24-hour notation is abc >>>TimeFormatException: Invalid Value for Time!
<<<TimeString for format converting in 24-hour notation is 6:30 >>>Time in 12-hour notation is: 06:30 AM
End of program
```
阅读全文