# 如何排序不同的日期时间格式？

##### 问题描述投票：1回答：2

``````comments = sorted(comments, key=lambda k: k['time_created'])
``````

``````comments = sorted(comments, key=lambda k: self.unix_time_millis(k['time_created']), reverse=True)

@staticmethod
def unix_time_millis(dt):
epoch = datetime.datetime.utcfromtimestamp(0)
return (dt - epoch).total_seconds() * 1000.0
``````
python algorithm python-3.x
##### 2个回答
1

Python `datetime`对象具有可比性，因此可以排序。我假设您目前不使用日期时间对象，而是使用字符串。以下示例代码取自How to format date string via multiple formats in python

``````import dateutil.parser
dateutil.parser.parse(date_string)
``````

``````list_of_dt_objs = [dateutil.parser.parse(str) for str in list_of_strings]
``````

0

``````import re
import operator

def convert_to_secs(date_string):
multipliers = [31557600,2592000,86400,3600,60]
date_in_secs = 0
index = 0
for v in re.split(':|-|T|\.|\+|\ ',date_string):
if index < len(multipliers):
date_in_secs = date_in_secs + int(v) * multipliers[index]
index += 1
else:
break
return date_in_secs

def sort_dates(my_dates_in_string):
my_dates_dict = {}
for string_date in my_dates_in_string:
my_dates_dict[string_date] = convert_to_secs(string_date)
return sorted(my_dates_dict.items(), key=operator.itemgetter(1))

print sort_dates(["2017-12-14T17:42:30.345244+0000", "2017-12-14 00:23:23.468560"])
``````