【问题标题】:Inputting time in the form HHMM in python在 python 中以 HHMM 形式输入时间
【发布时间】:2015-03-19 15:54:21
【问题描述】:

我想以 HHMM 形式将时间输入到我的 Python 程序之一,但是当我这样做时,我得到了

"SyntaxError: invalid token",

我认为这是因为它不是一个有效的八进制数,正如我在其他网站上看到的那样,for example

我使用的代码是:

time1 = float(input("Please enter time 1:"))

【问题讨论】:

    标签: python time token


    【解决方案1】:

    您应该查看datetime module 以将您的字符串转换为实际的日期时间对象,它有很多有用的方法:

    >>> import datetime
    >>> time = datetime.datetime.strptime(raw_input('specify time in HHMM format: '), "%H%M")
    specify time in HHMM format: 0830
    >>> time
    datetime.datetime(1900, 1, 1, 8, 30)
    >>> time.time()
    datetime.time(8, 30)
    >>> time.hour
    8
    

    在这里使用 Python2.7(因此:raw_input)。

    您正在观察的SyntaxError 也由该链接解释:您在 Python2.x 中使用的是input,而不是raw_input

    【讨论】:

    • 谢谢...我去试试!
    猜你喜欢
    • 2020-12-24
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    • 2020-09-21
    • 2020-08-14
    相关资源
    最近更新 更多