Home > Software design >  How to compare and get data from less than 5 minutes only?
How to compare and get data from less than 5 minutes only?

Time:08-19

I have large amount of json data. how to compare less than three minutes of data. how to get the results for the last three minutes of data and otherwise skip the data.

How to compare hours as minutes using datetime module?

confused compare minutes and hour based value should i use datetime module string based compare value?

sample:

data = [{'EventTime': '08/18/2022 08:06:52', 'Password_change': 'Success'},
        {'EventTime': '08/18/2022 08:05:10', 'Password_Change': 'Success'},
        {'EventTime': '08/18/2022 08:04:23', 'Password_Change': 'Success'},
        {'EventTime': '08/18/2022 05:06:52', 'Password_Change': 'Success'}]

code:

data = [{'EventTime': '08/18/2022 08:06:52', 'Password_change': 'Success'},
        {'EventTime': '08/18/2022 08:04:10', 'Password_Change': 'Success'},
        {'EventTime': '08/18/2022 08:03:23', 'Password_Change': 'Success'},
        {'EventTime': '08/18/2022 05:06:52', 'Password_Change': 'Success'}]
for i in data:
    split_time = i['EventTime'].split(' ')[1]
    time_detail = split_time
    print(time_detail)
    

CodePudding user response:

you don't need to split time string to get time information. Python provides us with datetime utilties

You can do something like below

from datetime import datetime, timedelta

data = [{'EventTime': '08/18/2022 08:06:52', 'Password_change': 'Success'},
        {'EventTime': '08/18/2022 08:04:10', 'Password_Change': 'Success'},
        {'EventTime': '08/18/2022 08:03:23', 'Password_Change': 'Success'},
        {'EventTime': '08/18/2022 05:06:52', 'Password_Change': 'Success'}]

result = []
ref_time = datetime.now()
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 <= 300:
        result.append(item)

print(result)

Note: Please make sure you specify the timezone in your code based on your data. Currently ref_date is in UTC format.

  • Related