更新时间:2023-02-26 20:21:55
# create sample data
from datetime import datetime, timedelta
d = datetime.now()
data = [d + timedelta(minutes=i) for i in xrange(100)]
# prepare and group the data
from itertools import groupby
def get_key(d):
# group by 30 minutes
k = d + timedelta(minutes=-(d.minute % 30))
return datetime(k.year, k.month, k.day, k.hour, k.minute, 0)
g = groupby(sorted(data), key=get_key)
# print data
for key, items in g:
print key
for item in items:
print '-', item
这是此答案的python翻译,它通过将日期时间四舍五入到下一个边界并将其用于分组.
This is a python translation of this answer, which works by rounding the datetime to the next boundary and use that for grouping.
如果您确实需要可能的空组,则可以使用此方法或类似方法将其添加:
If you really need the possible empty groups, you can just add them by using this or a similar method:
def add_missing_empty_frames(g):
last_key = None
for key, items in g:
if last_key:
while (key-last_key).seconds > 30*60:
empty_key = last_key + timedelta(minutes=30)
yield (empty_key, [])
last_key = empty_key
yield (key, items)
last_key = key
for key, items in add_missing_empty_frames(g):
...