Avión
Avión

Reputation: 8376

Find the closest timestamp (from a array of dictionaries) to a given timestamp

Having the following list of dictionaries, which includes a timestamp (in string value) and a value:

my_example = [{'timestamp': '2009-11-10T23:00:01Z', 'value': 1}, {'timestamp': '2009-11-10T23:00:05Z', 'value': 2}, {'timestamp': '2009-11-10T23:00:20Z', 'value': 3}]

I want for a given timestamp value (in string format), find the closest value.

This means that:

Can someone give me a hand?

I know there's a built-in function that makes this magic for a list of integers, for example, but I dont know how to make it work with dates:

min(myList, key=lambda x:abs(x-myNumber)).

Thanks in advance

Upvotes: 2

Views: 610

Answers (1)

Rakesh
Rakesh

Reputation: 82755

Use datetime to convert string to datetime object and the use min

Ex:

import datetime
my_example = [{'timestamp': '2009-11-10T23:00:01Z', 'value': 1}, {'timestamp': '2009-11-10T23:00:05Z', 'value': 2}, {'timestamp': '2009-11-10T23:00:20Z', 'value': 3}]

myNumber = "2009-11-10T23:00:02Z"
myNumber = datetime.datetime.strptime(myNumber, "%Y-%m-%dT%H:%M:%SZ")
print(min(my_example, key=lambda x:abs(datetime.datetime.strptime(x["timestamp"], "%Y-%m-%dT%H:%M:%SZ") - myNumber)))

Upvotes: 2

Related Questions