TypeError:无法将datetime.timedelta与float进行比较

时间:2014-09-07 20:50:24

标签: python datetime timedelta

我正在使用我的python脚本来计算开始日期和结束日期格式之间的持续时间,例如2014052016000020140520170000,这样我就可以获得时间。

我遇到了这段代码的问题:

if epgDuration >= 0.10 and epgDuration <= 0.30:
   epgwidth = "250"

当我试图比较0.10分钟和0.30分钟之间的时间范围时,我收到错误。

我得到的错误是:TypeError:无法将datetime.timedelta与float进行比较。

错误是跳到这一行:

if epgDuration >= 0.10 and epgDuration <= 0.30:

结果如下:

14:44:55 T:1580  NOTICE: 0:30:00
14:44:55 T:1580  NOTICE: 2:30:00
14:44:55 T:1580  NOTICE: 3:00:00
14:44:55 T:1580  NOTICE: 1:00:00
14:44:55 T:1580  NOTICE: 0:30:00
14:44:55 T:1580  NOTICE: 0:30:00
14:44:55 T:1580  NOTICE: 0:30:00
14:44:55 T:1580  NOTICE: 0:30:00
14:44:55 T:1580  NOTICE: 0:30:00
14:44:55 T:1580  NOTICE: 0:30:00
14:44:55 T:1580  NOTICE: 1:00:00
14:44:55 T:1580  NOTICE: 0:30:00
14:44:55 T:1580  NOTICE: 0:30:00
14:44:55 T:1580  NOTICE: 0:30:00

以下是我用来持续时间的代码:

for row in programs:
    program_startdate = str(row[2])
    program_endDate = str(row[3])

    try:
       start_date = datetime.datetime.strptime(program_startdate, "%Y%m%d%H%M%S")
       end_date = datetime.datetime.strptime(program_endDate, "%Y%m%d%H%M%S")
    except TypeError:
       start_date = datetime.datetime.fromtimestamp(time.mktime(time.strptime(program_startdate, "%Y%m%d%H%M%S")))
       end_date = datetime.datetime.fromtimestamp(time.mktime(time.strptime(program_endDate, "%Y%m%d%H%M%S")))

    #workout the duration times to get the program time
    epgDuration = end_date - start_date

    if epgDuration >= 0.10 and epgDuration <= 0.30:
       epgwidth = "250"

    elif epgDuration >= 1.00 and epgDuration <= 1.29:
         epgwidth = "500"
    print epgwidth

2 个答案:

答案 0 :(得分:8)

实际上,您无法将timedelta与浮点值进行比较。

可以将对象转换为秒:

if 600 <= epgDuration.total_seconds() <= 1800:

其中10分钟是600秒,30分钟是1800。

或者创建要与之比较的新timedelta()个对象:

epgwidth = "0"

if timedelta(minutes=10) <= epgDuration <= timedelta(minutes=30):
    epgwidth = "250"

elif timedelta(hours=1) <= epgDuration <= timedelta(hours=1.5):
    epgwidth = "500"

对于时间差不在10-30分钟或1-1.5小时范围内的情况,我在epgwidth语句之前给了if一个默认值。

答案 1 :(得分:1)

要从timedetla对象获取分钟数,您可以使用total_seconds()并除以60:

epgDurationMin = epgDuration.total_seconds()/60.
if 0.10 <= epgDurationMin <= 0.30:
   ...

另请注意,您可以使用python的酷comparison-chaining(例如a <= b <= c