Python datetime.time比较报错:无法在builtin_function_or_method与datetime.time间使用>=
解决datetime.time比较时的TypeError错误
错误信息
File "c:\Users\xxxxxx\Desktop\pyfiche\code.py", line 33, in timeofweek if (a.time >= d0.time() and a.time() <= d6.time()) or (a.time() >= d21.time() and a.time() <= d23.time()): TypeError: '>=' not supported between instances of 'builtin_function_or_method' and 'datetime.time'
问题根源
报错行里的a.time >= d0.time()存在语法错误:a是datetime对象,time是获取时间部分的方法,必须通过a.time()调用才能得到datetime.time实例;直接写a.time得到的是方法本身(builtin_function_or_method类型),自然无法和datetime.time实例做比较。
这个错误和输入格式改成12小时无关,只是刚好触发了包含该错误的周日判断分支才暴露出来。
修正后的代码
def timeofweek(a): d6 = a.replace(hour=6, minute=0, second=0, microsecond=0) d21 = a.replace(hour=21, minute=0, second=0, microsecond=0) d0 = a.replace(hour=0, minute=0, second=0, microsecond=0) d23 = a.replace(hour=23, minute=0, second=0, microsecond=0) if a.weekday() in range(0,6): print(a.time(),type(a.time())) #for debugging and they are both Datetime.time print(d0.time(),type(d0.time())) #for debugging and they are both Datetime.time if (a.time() >= d6.time() and a.time() < d21.time()): return 1 if (a.time() >= d0.time() and a.time() < d6.time()) or (a.time() >= d21.time() and a.time() <= d23.time()): return 2 if a.weekday() == 6: if (a.time() >= d6.time() and a.time() <= d21.time()): return 2 # 修正此处的a.time为a.time() if (a.time() >= d0.time() and a.time() <= d6.time()) or (a.time() >= d21.time() and a.time() <= d23.time()): return 3
内容的提问来源于stack exchange,提问作者zakblack
相关产品推荐
相关产品推荐

