import datetime
class Element(object):
name: str
datetime: datetime.datetime
def __init__(self, *args, **kwargs):
self.name = args[0]
self.datetime = args[1]
def __str__(self):
return self.name " " self.datetime.strftime("%d-%m-%Y %H:%M:%S")
e = Element("Name 1", datetime.datetime(2022, 1, 5, 20, 20, 20))
e2 = Element("Name 1", datetime.datetime(2022, 1, 5, 20, 20, 23))
e3 = Element("Name 2", datetime.datetime(2022, 2, 5, 19, 11, 10))
e4 = Element("Name 3", datetime.datetime(2022, 3, 5, 10, 15, 10))
e5 = Element("Name 3", datetime.datetime(2022, 3, 5, 10, 15, 8))
e6 = Element("Name 4", datetime.datetime(2022, 4, 7, 12, 12, 8))
e7 = Element("Name 4", datetime.datetime(2022, 4, 7, 12, 12, 20))
array = [e, e2, e3, e4, e5, e6, e7]
new_array = []
I need to generate a new array with this rule: there were no elements with the same name if they have a datetime difference of less than 5 seconds
CodePudding user response:
Perhaps try using another class to determine and store arrays
from datetime import datetime
class Arrays:
def __init__(self):
self.nodes = {}
def push(self, node):
if node.name in self.nodes:
for item in self.nodes[node.name]:
delta = node.time - item.time
seconds = 3600*24*abs(delta.days) - delta.seconds if delta.days < 0 else delta.seconds
if seconds >= 5:
self.nodes[node.name].append(node)
else:
self.nodes[node.name] = [node]
def get_array(self):
return [item for value in self.nodes.values() for item in value]
class Element(object):
def __init__(self, *args, **kwargs):
self.name = args[0]
self.time = args[1]
def __repr__(self):
return self.name " " self.time.strftime("%d-%m-%Y %H:%M:%S")
arr = Arrays()
for ele in [Element("Name 1", datetime(2022, 1, 5, 20, 20, 20)),
Element("Name 1", datetime(2022, 1, 5, 20, 20, 23)),
Element("Name 2", datetime(2022, 2, 5, 19, 11, 10)),
Element("Name 3", datetime(2022, 3, 5, 10, 15, 10)),
Element("Name 3", datetime(2022, 3, 5, 10, 15, 8)),
Element("Name 4", datetime(2022, 4, 7, 12, 12, 8)),
Element("Name 4", datetime(2022, 4, 7, 12, 12, 20))]:
arr.push(ele)
print(arr.get_array())