You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 01:55:22