![]() |
Grouping a list of various time into intervals - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Grouping a list of various time into intervals (/thread-22725.html) |
Grouping a list of various time into intervals - paul41 - Nov-24-2019 Hi, I am looking to create a new function that will take in a list of different times and also another input which will split it into x second intervals. The function needs to split the times and group them with a count. So for example I pass to the function the list and the value 10, this means to split each time into 10 second intervals. I then want to count for each value within the list the times that are within each group. So any times within the first 10 seconds this is returned as a count. I count the times within the list for the second 10 seconds and so on. I am thinking i could do this by first getting the min and max times of the values within the list. Use a WHILE time <= max(time) get the min(time) and keep adding x=10 (if we set to 10 second intervals). This will give me a list of each time intervals that will be required. From this point I would need to loop over my list of times and compare it to which group in the time interval list(not quite sure exactly how i would do this) I am thinking there is most likely a module that may already do this as it must be common for graphs and scales? Can someone give me a pointer in how I should get started. Thanks in advance RE: Grouping a list of various time into intervals - buran - Nov-24-2019 what's the start for first 10 seconds interval? the min time in the list? you can find the time difference between start and each time in the list and divide that by interval length. so you can find in which interval is each time. from datetime import datetime from itertools import groupby duration = 10 times = ['10:00:15', '10:00:17', '10:00:29', '10:00:30', '10:00:50'] times = sorted([datetime.strptime(t, '%H:%M:%S') for t in times]) start = times[0] for interval, cnt in groupby(times, lambda t: int((t - start).total_seconds() // duration) + 1): times = [t.strftime('%H:%M:%S') for t in cnt] print (f'interval:{interval}, count:{len(times)}, times:{times}')
|