Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list : How to sort by timestamp? ( App Engine related )

I have ten entities in my Feed model ( this is an App Engine model)

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

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

so i call my entities using db.key() method:

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

but now, how do I sort the feeds according to timestamp? ( I want the newest feeds at the top and the oldest ones at the bottom)

any sort function I can use on the raw timestamp? ( my rough plan is to sort according to the raw timestamp, then humanize the time difference )

PS: I don't plan to use GQL query to query my entities according to timestamp, because I get my input in the form of a list of keys. And using db.key() is a faster method.

hope I supplied enough info. wish to hear your thoughts/solutions.

like image 441
fooyee Avatar asked May 25 '26 11:05

fooyee


1 Answers

import operator

   ...

for feed in sorted(feeds, key=operator.attrgetter('timestamp'), reverse=True):
   print humanizeTimeDiff(feed.timestamp) 
like image 128
Alex Martelli Avatar answered May 27 '26 23:05

Alex Martelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!