python - Define a sorted function for timestamps/time objects by key -
this question has answer here:
i have dictionary of times , counts. need sort dict in ascending order time. need getting sort useful. right dropping am/pm remove complexity aware i'm running problem there since i'm losing information.
calling
sorted(mydict, key = bytime_key)
with
def bytime_key(input): shorter_input = re.match(r'^(.*) \w\w$', input).group(1) time = datetime.strptime(shorter_input, '%m/%d/%y %h:%m:%s') return(time)
is fine, save doesn't change order, i'm missing fundamental here.
sample dictionary
mydict = {'1/15/2016 10:41:00 am': 11, '1/15/2016 10:43:00 am': 4, '1/15/2016 10:22:00 am': 46, '1/15/2016 10:30:00 am': 15, '1/15/2016 10:59:00 am': 34, '1/15/2016 12:06:00 pm': 12, '1/15/2016 11:42:00 am': 11, '1/15/2016 12:22:00 pm': 1, '1/15/2016 12:18:00 pm': 5, '1/15/2016 10:52:00 am': 6}
strptime allows %p
directive.
%p
locale’s equivalent of either or pm. am, pm (en_us); am, pm (de_de) (1), (2)
key function may simplified to:
from datetime import datetime result = sorted(mydict, key=lambda s: datetime.strptime(s, "%m/%d/%y %h:%m:%s %p")) expected = ['1/15/2016 10:22:00 am', '1/15/2016 10:30:00 am', '1/15/2016 10:41:00 am', '1/15/2016 10:43:00 am', '1/15/2016 10:52:00 am', '1/15/2016 10:59:00 am', '1/15/2016 11:42:00 am', '1/15/2016 12:06:00 pm', '1/15/2016 12:18:00 pm', '1/15/2016 12:22:00 pm'] assert result == expected
note dictionaries inherently unsorted structures. can perform sorting of keys / values / key-value pairs , create ordered representation of data sorted in dictionary. , that's code - sorts keys.
Comments
Post a Comment