简体   繁体   English

如何根据对象的时间戳值对列表进行排序

[英]how to sort a list based on timestamp value of an object

I have an object called Orders . 我有一个名为Orders的对象。 One of the field in orders is last_modified . 订单中的字段之一是last_modified the format of this field is 01-JAN-16 02.15.49.086630 PM 该字段的格式为01-JAN-16 02.15.49.086630 PM

Then i have a list of these orders ie, orders_list . 然后我有这些订单的列表,即orders_list How can I sort this list based on last_modified value? 如何根据last_modified值对该列表进行排序?

You can use sorted with a custom key. 您可以使用带自定义键的sorted In this case, you need to convert your string field to datetime : 在这种情况下,您需要将字符串字段转换为datetime

from datetime import datetime

date_format = '%d-%b-%y %H.%M.%S.%f %p'

res = sorted(orders_list, key=lambda x: datetime.strptime(x.last_modified, date_format))

See Python's strftime directives to see how to construct date_format . 请参阅Python的strftime指令以了解如何构造date_format

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM