1

I have the following code:

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

How to sort correctly if some elements have the different format, like 2017-12-14T17:42:30.345244+0000 and 2017-12-14 00:23:23.468560 and my code fail when trying to compare?

I need to save seconds accuracy.

Is it the good solution?

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
8
  • you could map the timestamp to a datetime object and sort these. Commented Dec 14, 2017 at 21:43
  • how to do this? could you provide some code please? Commented Dec 14, 2017 at 21:44
  • Did you try converting them all into one date time format? Commented Dec 14, 2017 at 21:45
  • In your place, I will convert everything to ms ans make the sort Commented Dec 14, 2017 at 21:47
  • @WalidDaboubi how to do this? Commented Dec 14, 2017 at 21:48

2 Answers 2

1

Python datetime objects are comparable and therefore sortable. I assume that you currently don't use datetime objects but Strings. The following example code is taken from How to format date string via multiple formats in python

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

You would then convert a list of strings to datetime objects via

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

Please note that dateutil is an extension lib. So you have to install it, for instance via pip.

Sign up to request clarification or add additional context in comments.

Comments

0

Something like this:

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"])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.