gpt4 book ai didi

python - 将时间作为 HHMM 格式的用户输入

转载 作者:太空宇宙 更新时间:2023-11-04 08:45:45 24 4
gpt4 key购买 nike

我在树莓派终端遇到了一个问题。

>>> alarm = input('Please input the time for the alarm in format HHMM: \n ')
>>> print(alarm)

我输入 0700,按回车键,但它打印出 448 而不是 0700。当我在 IDLE 中尝试它时,它输出 0700。为什么它不会在 raspberry pi 终端中输出 0700?我怎样才能让终端发出 0700?

最佳答案

input() 函数会将您的输入转换为字符串。

0070 被认为是一个八进制数。它先转换为十进制数,然后再转换为字符串。

print str(0070)
>>> 56

import time
alarm = str(raw_input('Please input the time for the alarm in format HHMM: \n '))
print alarm

>>> Input: 0080
>>> Output: 0080

您应该验证用户输入的时间。例如,您不应允许用户输入类似 4012 的时间。您可以使用 datetime 模块验证时间,如下所示:

import datetime
try:
a = datetime.datetime.strptime(raw_input('specify time in HHMM format: '), "%H%M")
print a.strftime("%H%M")
except:
print "Please enter correct time in HHMM format"

使用日期时间对象还有其他优点。您可以根据自己的时间执行各种操作。例如。向其中添加时间,从中减去时间,将其转换为各种格式等。阅读此内容以获取更多信息:https://docs.python.org/2/library/datetime.html

关于python - 将时间作为 HHMM 格式的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40796769/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com