简体   繁体   中英

How to sort data according to timeformat in python3

This is my data:

k = {'10-06-2021': [1,2,3], '09-06-2021': [2,3,4], '08-06-2021': [5,6,7], '01-06-2021': [8,9,10], '31-05-2021': [11,12,13], '11-06-2021': [14,15,16], '07-06-2021': [17,18,19]}
print(k)

p = sorted(k.items())
print(p)

I want to sorted according to date key and my date format is "dd-mm-yy". when printing data is not comming in order.The issue is sorted function compares data in "yy-mm-dd" format.

I want data to be sorted in ascending date key format. And using sorted() only.

If i write "10-06-2021" as "2021-06-10" result is perfect but this k value is going to db so i don't want to change it.

The key=... parameter in sorted() function will help you here. It basically takes a function or an anonymous lambda function as an argument.

This will be the code for your problem:

k = {'10-06-2021': [1,2,3], '09-06-2021': [2,3,4], '08-06-2021': [5,6,7], '01-06-2021': [8,9,10], '31-05-2021': [11,12,13], '11-06-2021': [14,15,16], '07-06-2021': [17,18,19]}
p = sorted(k.items(), key=lambda x: "".join(reversed(x[0].split("-"))))
print(p)

Explanation

as you said your function works on yyyy-mm-dd format so i converted the string as that format but without '-' . So it sorts according to the format but returns the desired string.

Example:

"12-08-2021" is converted to: "20210812"

You can also use the datetime module:

  • If you don't need to work with datetimes but may need to include hours in the string in the future:
import datetime
k = {'10-06-2021': [1,2,3], '09-06-2021': [2,3,4], '08-06-2021': [5,6,7], '01-06-2021': [8,9,10], '31-05-2021': [11,12,13], '11-06-2021': [14,15,16], '07-06-2021': [17,18,19]}
p = sorted(k.items(), key=lambda x: datetime.datetime.strptime(x[0], "%d-%m-%Y"))
  • If you want to work with datetime operators:
import datetime
k = {'10-06-2021': [1,2,3], '09-06-2021': [2,3,4], '08-06-2021': [5,6,7], '01-06-2021': [8,9,10], '31-05-2021': [11,12,13], '11-06-2021': [14,15,16], '07-06-2021': [17,18,19]}
# Use datetimes instead of strings in the dictionary
k = {datetime.datetime.strptime(k): v for k, v in k.items()}
p = sorted(k.items(), key=lambda x: x[0])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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