Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a date from an excel sheet if it is the same date as today with Python?

I'm new to Python and I'm trying to automate excel using openpyxl. I'm importing datetime and I'd like my code to go through all the dates in one specific column and return a date if it's equal to date.today().

So far I've been trying to do something like this:

`present = date.today()
 for row in sheet.iter_cols(
                        min_col=3,
                        max_col=3,
                        min_row=2,
                        max_row=sheet.max_row,
                        values_only=True):
    if present == row:
        print(row)`

But it is not printing anything even though I fixed the date format in excel.

like image 688
anothercodingnoob Avatar asked Dec 22 '25 06:12

anothercodingnoob


1 Answers

Assuming your column holds dates and not date-like text, the reason why no value is printed is that at each iteration you're comparing a tuple of datetime objects (made by openpyxl) to a date one, which is today's date.

(
    datetime.datetime(2024, 1, 1, 0, 0),
    datetime.datetime(2024, 1, 12, 0, 0)
) == date.today() # this evalutes to False

So, even with values_only=True, you still have unpack the tuples (by adding an inner loop) and use the method date() to compare to :

for col in sheet.iter_cols(
    min_col=3,
    max_col=3,
    min_row=2,
    max_row=sheet.max_row,
    values_only=True
):
    for val in col:
        if present == val.date() :
            print(val)
like image 64
Timeless Avatar answered Dec 23 '25 19:12

Timeless