In python, sorting on date field, field may sometimes be null

后端 未结 2 1371
粉色の甜心
粉色の甜心 2021-02-05 06:00

I am having a hard time coming up with a slick way to handle this sort. I have data coming back from a database read. I want to sort on the accoutingdate. However, accoutingd

2条回答
  •  独厮守ぢ
    2021-02-05 06:10

    You could use a custom sorting function that treats None specially:

    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, ...)
    

    This treats None as being smaller than all datetime objects.

提交回复
热议问题