I have a list:
timestamp_list = ['1377091800', '1377093000', '1377094500', '1377095500']
Target number:
ptime = 1377091810
I want to find between which pair of timestamp does ptime
lie in. For e.g. in this case, it lies between the first and the second timestamp. So I want to return the value 1377091800
as the desired output.
Similarly, if ptime
was 1377091520
, then I want the third timestamp to be returned i.e. 1377091500
since it lies between third and the fourth timestamp.
My code:
timestamp_list = ['1377091800', '1377093000', '1377094500', '1377095500']
ptime = 1377091810
for idx, value in enumerate(timestamp_list):
val = long(value)
if idx!= len(timestamp_list)-1 and ptime >= val and ptime < long(timestamp_list[idx+1]):
target = val
break
elif (idx == len(timestamp_list)-1) and ptime >= val:
target = val
else:
pass
print target
Output:
1377091800
I wanted to know is there any elegant solution to this? Since I am just starting with python, I am not yet familiar with all the functions in python.
Any help is appreciated.
EDIT:
SOLUTION USED:
import bisect
timestamp_list = ['1377091800', '1377093000', '1377094500', '1377095500']
ptime = str(1377093110)
if ptime in timestamp_list:
target = ptime
else:
index = bisect.bisect_right(timestamp_list, ptime)-1
target = timestamp_list[index]
print target
OUTPUT:
1377093000
Since the timestamps are sorted, you can use bisect
for that:
In [24]: timestamp_list = [1377091800, 1377093000, 1377094500, 1377095500]
In [25]: timestamp_list[bisect.bisect_right(timestamp_list, 1377093100)]
Out[25]: 1377094500
(I've converted the strings to integers to keep the code clear.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With