我将如何进行这个过程?假设有人输入“3:5”,我应该能够得到输出“3:05 AM”。或者如果有人输入“00:00”,我应该得到“12:00 AM”。如果将时间格式简单地输入为“hhmm”,我意识到有很多方法可以解决这个问题,但输入的范围可以从“h:m”、“hh:m”、“hh:m”和“hh:毫米”。所以这是非常有情况的。
def timeConvert():
miliTime = int(input("Enter a time in hh:mm (military) format: "))
miliTime.split(":")
if len(miliTime) == 3:
hours = miliTime[0]
minutes = miliTime[2]
if hours < 0:
print("Hours can't be less than 0.")
elif len(miliTime) == 4:
if miliTime[0:2] >= 10:
hours = militime[0:2]
minutes = militime[3]
if minutes < 0:
print("Minutes can't be less than 0.")
if minutes < 10:
minutes = 0 + minutes
else:
hours = miliTime[0]
minutes = militime[2:]
if minutes >= 60:
print("Too big of a number for minutes.")
else:
hours = miliTime[0:2]
minutes = miliTime[3:]
setting = AM
if hours > 12:
setting = PM
hours -= 12
print(hours + ":" + minutes + setting)
timeConvert()
最佳答案
通过 :
分割输入,最后使用格式化输出:
def timeConvert():
miliTime = input("Enter a time in hh:mm (military) format: ")
hours, minutes = miliTime.split(":")
hours, minutes = int(hours), int(minutes)
setting = "AM"
if hours > 12:
setting = "PM"
hours -= 12
print(("%02d:%02d" + setting) % (hours, minutes))
关于python - 0-23 小时军用时钟到标准时间 (hh :mm),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31691007/