Reputation: 8376
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:
2009-11-10T23:00:02Z
I want to return: {'timestamp': '2009-11-10T23:00:01Z', 'value': 1}
2009-11-10T23:00:04Z
I want to return: {'timestamp': '2009-11-10T23:00:05Z', 'value': 2}
2009-11-10T23:00:15Z
I want to return: {'timestamp': '2009-11-10T23:00:15Z', 'value': 3}
etc.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
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