Here in this python code example, we will find the column number of a cell having the given date in excel data. For this we require to have below libraries on system. So, install them if they are not installed.
import xlwings as xw
from datetime import datetime
Now write below code lines to open the workbook the select the required sheet.
#Open the workbook and select the sheet
wb = xw.Book('your_excel_file.xlsx') # need to write name of your excel file
sheet = wb.sheets['Sheet1] #Change 'Sheet1' to your sheet name
Now define the date to search for by writing below code line. Here for example we will find 10-03-2025.
This code will convert the search date to a datetime object and compare it with the values in the second row, ensuring that the date format matches.
#Define the date to search for
search_date = datetime.strptime("10-03-2025", "%d-%m-%Y")
Define the range where to find.
# Get the range of the second row
row_range = sheet.range(‘2:2’)
Now write below code lines to find the column number of cell that contains the search_date.
#Find the cell with the specified date
for cell in row_range:
if isinstance(cell.value, datetime) and cell.value.date() == search_date.date():
column_number = cell.column
print(f"The column number is: (column.number)")
break
else:
print("Date not found in the specified range.")
The entire code will look like this.
import xlwings as xw
from datetime import datetime
#Open the workbook and select the sheet
wb = xw.Book('your_excel_file.xlsx') # need to write name of your excel file
sheet=wb.sheets['Sheet1] #Change 'Sheet1' to your sheet name
#Define the date to search for
search_date= datetime.strptime("10-03-2025", "%d-%m-%Y")
# Get the range of the second row
row_range = sheet.range(‘2:2’)
#Find the cell with the specified date
for cell in row_range:
if isinstance(cell.value, datetime) and cell.value.date() == search_date.date():
column_number = cell.column
print(f"The column number is: (column .number)")
break
else:
print("Date not found in the specified range.")