比较从Python中的字符串连接的Ints

问题描述 投票:0回答:2

因此,我试图使用Python编写一个程序,该程序将在一定时间后发送文本提醒。我试图检查时间是否在一个真实的范围内(即一天不超过或少于24小时),但我在尝试比较时遇到错误。我无法比较从字符串连接的整数。

dur = input("How long do you want to wait (EX: HHMMSS): ")
hours = int(dur[0:1])
minutes = int(dur[2:3])
seconds = int(dur[4:5])
print(hours)
print(minutes)
print(seconds)

for n in range(0, LOOP):
    if(count == 0):
        # Check if hours is realistic
        if(hours > 0 and hours < 24 and str(hours[0]) == 0):
            hours = hours[1]
            count += 1

我得到一个TypeError说> str和int的实例之间不支持。由于我无法将它们与>或<进行比较,我该怎么办呢?

python string int comparison concatenation
2个回答
0
投票

尝试添加此:

hours = int(dur[0:2])
minutes = int(dur[2:4])
seconds = int(dur[4:6])

for n in range(0, LOOP):
    if(count == 0):
        # Check if hours is realistic
        if(hours > 0 and hours < 24 and hours < 10):
            ...

而另一件事你不能使用hours = hours[1]因为'int' object is not subscriptable


0
投票

解析日期和时间不值得手工完成。您的代码尝试使用hours[0]索引到整数。没有强制转换,字符串和整数类型无法比较。

试试Python的datetime模块,特别是strptime函数,它从格式化的字符串中解析日期。您可以使用timedelta提取小时,分钟,秒并轻松执行比较并添加/减去时间。

from datetime import datetime

while 1:
    try:
        dur = input("How long do you want to wait (EX: HHMMSS): ")
        dt = datetime.strptime(dur, "%H%M%S")
        print(dt, " hour:", dt.hour, " min:", dt.minute, " sec:", dt.second)        
        break
    except ValueError:
        print("Invalid time.")

样品运行:

How long do you want to wait (EX: HHMMSS): 012261
Invalid time.
How long do you want to wait (EX: HHMMSS): 012251
1900-01-01 01:22:51  hour: 1  min: 22  sec: 51
© www.soinside.com 2019 - 2024. All rights reserved.