在Python中,对日期字段排序,字段有时可能为null
我在想一个简单的方法来处理这个排序问题。我从数据库读取了一些数据,想要按照“会计日期”来排序。但是,有时候“会计日期”可能是空的(也就是null)。我现在的做法是:
results = sorted(results, key=operator.itemgetter('accountingdate'), reverse=True)
但是,这样会出现错误:“TypeError: can't compare datetime.date to NoneType”,因为有些“会计日期”是空的。
那么,处理这个问题的“最正确”或者“最符合Python风格”的方法是什么呢?
2 个回答
13
你可以使用一个自定义的排序函数,特别处理一下 None
的情况:
def nonecmp(a, b):
if a is None and b is None:
return 0
if a is None:
return -1
if b is None:
return 1
return cmp(a, b)
results = sorted(results, cmp=nonecmp, ...)
这样做会把 None
当作比所有的日期时间对象都要小。
33
使用 key=
函数是完全正确的,你只需要决定如何处理 None
值——选择一个你想用来替代 None
的 datetime
值,以便进行排序。例如:
import datetime
mindate = datetime.date(datetime.MINYEAR, 1, 1)
def getaccountingdate(x):
return x['accountingdate'] or mindate
results = sorted(results, key=getaccountingdate, reverse=True)
你会发现,这比定义一个 cmp
函数简单多了——而且如果你做一些性能测试,你会发现它的速度也快得多!使用 cmp
函数没有任何好处,反而用 key
函数会是一个更好的设计选择。