-1

I have a list of times and I need to get all the elements in the list that have the same hour or minute or second and form them into new lists.

example: list

['10:20:01', '10:20:02', '10:21:00', '10:21:01', '10:22:00', '10:22:01']

out

['10:20:01', '10:20:02']
['10:21:00', '10:21:01']
['10:22:00', '10:22:01']
zckun
  • 3
  • 2
  • Your question is a combination of "how can I turn a string into a date-time value" https://stackoverflow.com/questions/466345/converting-string-into-datetime, "how can I get the hour or minutes from a datetime" https://stackoverflow.com/questions/25754405/how-to-extract-hours-and-minutes-from-a-datetime-datetime-object/38439409 and "how can I group a list into multiple lists" https://stackoverflow.com/questions/45539328/how-to-divide-a-list-into-a-list-of-smaller-lists-based-on-a-predicate/45539371 – Grismar Jan 29 '20 at 06:44

1 Answers1

0
from datetime import datetime
from collections import defaultdict
q = ['10:20:01', '10:20:02', '10:21:00', '10:21:01', '10:22:00', '10:22:01']
t = []
for i in q:    
    w = (datetime.strptime(i,"%H:%M:%S").time()) # Converting str to time
    t.append((w.hour,w.minute)) # Storing only hours and minutes
buckets = defaultdict(list)
for tup in t:
    buckets[tup].append(tup) # Check time and append to coressponding dict key(Hour,minute)
buckets = list(buckets.values())
Yash Kanojia
  • 154
  • 10