I have a small script that takes a list of objects from an SQL table and groups them if the date-time on the object has less than 60 second difference with the last object.
It does this by converting the date-time to epoch and then subtracting the epoch of the previous object from the epoch of the current object. The code works but I feel as if it is too convoluted for such a simple task.
rows = cur.fetchall() #gets all the objects from table
source = []
list1 = []
old_epoch = 1404413062 #I use the same epoch time as the first object but this isn't very pythonic
for a in rows:
date_time = a[12] #gets date_time
#strips date_time with regex to match the proper pattern format
#sample date_time from db "2014-07-07 11:10:18.867024-04"
date_time = re.match(r'^.*?\.', date_time).group(0)
date_time = date_time.replace(".", "")
pattern = '%Y-%m-%d %H:%M:%S'
#converts date_time to epoch
epoch = int(time.mktime(time.strptime(date_time, pattern)))
#had to add this small part to force the iterator to append the last chunk since no new epoch_time to compare and get difference as difference would be zero
if a == rows[-1]:
source.append(a[11])
list1.append(source)
else:
if epoch - old_epoch < 60:
source.append(a[11])
else:
list1.append(source)
source = []
source.append(a[11])
old_epoch = epoch
EDIT: Updated this post for those asking what it does. It returns a list of categorized groups based on the timestamp as displayed below when printing out list1. I replaced the actual objects with only their timestamp property for readability purposes. :
['2014-07-07 06:21:51.011377-04', '2014-07-07 06:21:51.347373-04', '2014-07-07 06:21:51.678615-04']
['2014-07-07 06:26:54.01491-04', '2014-07-07 06:26:54.347479-04', '2014-07-07 06:26:54.671736-04']
['2014-07-07 06:31:57.107409-04', '2014-07-07 06:31:57.437156-04', '2014-07-07 06:31:57.804104-04']
['2014-07-07 06:37:00.178693-04', '2014-07-07 06:37:00.509359-04', '2014-07-07 06:37:00.828529-04']
['2014-07-07 06:42:03.268083-04', '2014-07-07 06:42:03.594742-04', '2014-07-07 06:42:03.921035-04']
['2014-07-07 06:47:06.389844-04', '2014-07-07 06:47:06.717987-04', '2014-07-07 06:47:07.035479-04']
['2014-07-07 06:52:09.516735-04', '2014-07-07 06:52:09.846621-04', '2014-07-07 06:52:10.171093-04']
['2014-07-07 06:57:12.623216-04', '2014-07-07 06:57:12.952604-04', '2014-07-07 06:57:13.278989-04']