Home > other >  Sort strings in python based on date and time
Sort strings in python based on date and time

Time:11-22

I have a list of strings in this format:

my_strings = [
"10.02.20 time 09.24",  
"06.02.20 time 08.51",  
"10.02.20 time 09.24",  
"10.02.20 time 09.25",  
"10.02.20 time 09.26",  
"10.02.20 time 09.27",  
"10.02.20 time 09.28",  
"10.02.20 time 09.29"   
]

How can I sort them based on date and time, both normally and reversely? I think I should use something like:

my_strings.sort(key=lambda date: datetime.strptime(date, "%d-%b-%y"))

But this doesn't work.

CodePudding user response:

You can just sort the strings directly with my_strings.sort() and it will work. Assuming by "normally and reverse" you mean in ascending and descending order, for the latter you can either reverse the sorted list with my_strings[::-1], or directly while sorting with my_strings.sort(reverse=True).

If you want to use a string parsed datetime object for value comparison, assuming your format is "day.month.year time hour.minute", you need:

# same result as `my_strings.sort()`
my_strings.sort(key=lambda date: datetime.strptime(date, '%d.%m.%y time %H.%M'))

CodePudding user response:

the statement you import into the datetime module may be import datetime, try from datetime import datetime. it is all code

from datetime import datetime

my_strings = [
    "10.02.20 time 09.24",
    "06.02.20 time 08.51",
    "10.02.20 time 09.24",
    "10.02.20 time 09.25",
    "10.02.20 time 09.26",
    "10.02.20 time 09.27",
    "10.02.20 time 09.28",
    "10.02.20 time 09.29"
]
my_strings.sort(key=lambda date: datetime.strptime(date, "%y.%m.%d time %H.%M"))
print(my_strings)

CodePudding user response:

As per the documentation for the strptime function, the correct call for the function is:

strptime(date, "%d.%m.%y time %H.%M")

The %b you put in your code is for "Month as locale’s abbreviated names (Jan, Feb, …, Dec), but the correct is %m for "Month as a zero-padded decimal number", and you also need to include time %H.%M in the string declaring the format for it to work, or else you will get an ValueError: time data '10.02.20 time 09.24' does not match format '%d.%b.%y'

  • Related