iamkk
iamkk

Reputation: 135

Nearest timestamp in python

I have a list of timestamps and a key timestamp to find the nearest one, both are in the format '2019-11-22T11:37:52.338Z'

I have tried this solution Python - Locating the closest timestamp but since my timestamps are in string leads me with an error. When I tried to typecast them as shown below

def nearest(ts):
s = sorted(timestamp_list)
i = bisect_left(s, ts)
return min(s[max(0, i-1): i+2], key=lambda t: abs(int(ts) - int(t)))

ends up with ValueError: invalid literal for int() with base 10: '2019-11-22T11:37:52.338Z'

Any suggestions on how to overcome this error?

Upvotes: 0

Views: 542

Answers (1)

Käseknacker
Käseknacker

Reputation: 271

You can try strptime() from the datetime module to convert your string to a datetime object:

from datetime import datetime

ts = '2019-07-22T11:37:52.338Z'
datetime_object = datetime.strptime(ts, '%Y-%m-%dT%H:%M:%S.%fZ')

print(datetime_object)

Output:

2019-07-22 11:37:52.338000

https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior


And here the full example:

from bisect import bisect_left
from datetime import datetime


ts_list_str = ['2010-11-22T11:37:52.338Z', '2018-11-22T11:37:52.338Z', '2017-11-22T11:37:52.338Z']
ts_list = [datetime.strptime(ts, '%Y-%m-%dT%H:%M:%S.%fZ') for ts in ts_list_str]

def nearest(ts):
    s = sorted(ts_list)
    i = bisect_left(s, ts)
    return min(s[max(0, i-1): i+2], key=lambda t: abs(ts - t))

ts_str = '2019-07-22T11:37:52.338Z'
ts = datetime.strptime(ts_str, '%Y-%m-%dT%H:%M:%S.%fZ')

print(nearest(ts))

Upvotes: 1

Related Questions