tripkane
tripkane

Reputation: 939

Python:Continuing try loop until first item in list is found

I would like to use a try statement or any other method to find the closest item after the given variable in a list: I have the following code. In this example I want the code to keep adding one day to d1 until the first datetime object in list pj is found and then return the index of that corresponding list element. So here d1 should equal datetime.datetime(1922,01,06) and d1_index = 1. The range function yields the last element in the list, so obviously I need to change that condition but not sure what the right way forward is, Thanks heaps,

Kane

import datetime
import numpy as np
import dateutil.relativedelta as rd


pj = [datetime.datetime(1921,12,31), datetime.datetime(1922,01,06), datetime.datetime(1922,01,07), datetime.datetime(1922,01,10), datetime.datetime(1922,01,12)]

d1 = datetime.datetime(1922,01,02)
d2 = datetime.datetime(1929,12,31)

for i in range(0,50):
    try: 
        d1_index = pj.index(d1)

    except ValueError:
        d1 = d1 +rd.relativedelta(days = +i)

        continue
    break

Upvotes: 0

Views: 335

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799044

Goodness no.

>>> bisect.bisect_left(pj, d1)
1
>>> pj[bisect.bisect_left(pj, d1)]
datetime.datetime(1922, 1, 6, 0, 0)

Upvotes: 1

Related Questions