How to compare the current UTC datetime with only the last three mint data?

Question:

my script is running comparing the current time with less than three minutes of data output and received the remaining data,

but how to get only the last 3 minutes, the most recent data from this remaining data and skip if the datetime does not match 3 minutes recently

from datetime import datetime, timedelta

data = [{'EventTime': '08/22/2022 07:45:10', 'Password_change': 'Success'},
        {'EventTime': '08/22/2022 03:40:10', 'Password_Change': 'Success'},
        {'EventTime': '08/21/2022 07:32:23', 'Password_Change': 'Success'},
        {'EventTime': '08/17/2022 07:31:52', 'Password_Change': 'Success'}]

result = []
ref_time = datetime.utcnow()
# print(ref_time.strftime('%Y/%m/%d %H:%M:%S'))
for item in data:
    event_time = item.get('EventTime')
    event_time_obj = datetime.strptime(event_time, '%m/%d/%Y %H:%M:%S')
    diff = (ref_time - event_time_obj).total_seconds()

    if diff >= 180:
        result.append(item)

for i in result:
    print(i)

but this output is received after 3 minutes all output but i need to skip and i only need the latest output of 3 minutes

how to match with proper data and not just minutes

Asked By: Angeline

||

Answers:

You clarified that you need all log entries within 3 minutes of program execution time. In that case, you need to add data where diff <= 180 to your list. Currently (if diff >= 180:), your code adds all data where the log time is more than 3 minutes ago. Change that line to if diff <= 180: and your code should work fine.

Answered By: David
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.