search date in list of dates

0

I have a list of dates that is in datetime.date format (year, month, day). I want to know the position that has a datex (which also has the format datetime.date (year, month, day) in the list with the following code: posicion = lista.index(fechax) .

python throws me the error:

  

ValueError: datetime.date (year, month, day) is not in list

The issue is that both the list and the date searched have the same format and I made sure that datex was on the list of course.

What could be happening? or does the function the index method not work with dates?

EDIT:

Wb = load_workbook(filename = 'C:\ICP.xlsx')
sheet_ranges = wb["Simple"] 
fecha_icp=[(c.value).date() for c in sheet_ranges['A'][3:3804]]#.date() no agrega tiempo solo la fecha.

With this code I get dates from an excel where they are with date format. to build the list I read the value with .date () to not add hours or minutes.

As you can see in the image, it's what the list looks like in python. then I occupy this code: v = icp_value.index(valuation_date) . the variable valuation_date the entry like this:

valuation_date= input('ingrese la fecha de valorizacion en formato yyyy-mm-dd')# ingresar fecha de contrato

valuation_date= dt.datetime.strptime(valuation_date.rstrip(), "%Y-%m-%d").date() 

and in python it looks like this:

.

As you can see, the date sought and the list have the same format and the formula does not work.

I leave the excel: link

regards,

    
asked by Richie 24.11.2017 в 15:59
source

1 answer

-1

In principle you do not do anything wrong, if you use Openpyxl to address the xlsx you should not have any problem while the date exists:

import datetime as dt
from openpyxl import load_workbook


wb = load_workbook(filename = 'C:\ICP.xlsx')
sheet_ranges = wb["Simple"] 
fecha_icp=[(c.value).date() for c in sheet_ranges['A'][3:3804]]
valuation_date= input('ingrese la fecha de valorizacion en formato yyyy-mm-dd')
valuation_date= dt.datetime.strptime(valuation_date.rstrip(), "%Y-%m-%d").date()
posicion = fecha_icp.index(valuation_date)
print(posicion)

Faced with the possibility of entering a date that is not really on the list, you can treat the exception appropriately to your needs:

try:
    posicion = fecha_icp.index(valuation_date)
except ValueError:
    position = None

Keep in mind that this is valid if you only want the index of the first element that you find, because if you have a repeated date it will only return the index of the first one. In these cases you can use enumerate and list compression to get an iterable index of all occurrences:

posicion = [i for i, fecha in enumerate(fecha_icp) if fecha == valuation_date]
    
answered by 24.11.2017 / 17:03
source