Python类型错误:str与tuple无法比较,如何实现时间直接比较?
问题解决:实现时间的直接比较
错误原因
你代码里的exit_time是元组('19:00:00','%H:%M:%S'),而current_time是字符串类型,不同类型的变量无法用>=直接比较,这就是触发TypeError的原因。
方法一:用同格式时间字符串直接比较
因为%H:%M:%S格式的时间字符串是按两位数字排列的,字典序比较逻辑和时间先后逻辑完全一致,只需把exit_time改成对应格式的字符串即可:
import time current_time = time.strftime('%H:%M:%S') exit_time = '19:00:00' # 改为和current_time同格式的字符串 hour = time.strftime('%H') minute = time.strftime('%M') second = time.strftime('%S') if current_time >= exit_time: print("It's time to go home") else: print("{} hours, {} minutes and {} seconds to go home".format(18-int(hour), 59-int(minute), 59-int(second)))
方法二:用datetime对象比较(更规范)
如果后续涉及跨天、带日期的时间比较,用datetime模块转换为时间对象会更可靠,还能自动计算剩余时间:
from datetime import datetime # 获取当前时间的datetime对象 current_time = datetime.now() # 构造当天19:00:00的datetime对象 exit_time = current_time.replace(hour=19, minute=0, second=0, microsecond=0) if current_time >= exit_time: print("It's time to go home") else: # 自动计算时间差 time_diff = exit_time - current_time hours = time_diff.seconds // 3600 minutes = (time_diff.seconds % 3600) // 60 seconds = time_diff.seconds % 60 print("{} hours, {} minutes and {} seconds to go home".format(hours, minutes, seconds))
内容的提问来源于stack exchange,提问作者user215072
相关产品推荐
相关产品推荐

