Python列表:如何按时间戳排序?(与App Engine相关)

2 投票
1 回答
1774 浏览
提问于 2025-04-15 18:07

我在我的Feed模型里有十个实体(这是一个App Engine模型)

class Feed(db.Model):
  sometext = db.StringProperty()
  timestamp = db.DateTimeProperty(auto_now=True)

list_of_keys = ["key1","key2","key3".... "key10"]

所以我用db.key()方法来调用我的实体:

feeds = db.keys(list_of_keys)
# this loop below prints the feed 
for feed in feeds:
  print humanizeTimeDiff(feed.timestamp) 

# humanizeTimeDiff is a function to change the raw timestamp into a human friendly
# version: eg-> 10 mins ago, 20 seconds ago

但是现在,我该怎么根据时间戳来排序这些Feed呢?(我想把最新的Feed放在最上面,最旧的放在最下面)

有没有什么排序函数可以用在原始时间戳上?(我的大致计划是先根据原始时间戳排序,然后再把时间差转换成更容易理解的格式)

另外,我不打算用GQL查询来根据时间戳查询我的实体,因为我得到的输入是一个键的列表。而使用db.key()的方法更快。

希望我提供的信息足够。期待听到你的想法和解决方案。

1 个回答

10
import operator

   ...

for feed in sorted(feeds, key=operator.attrgetter('timestamp'), reverse=True):
   print humanizeTimeDiff(feed.timestamp) 

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。

撰写回答