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.
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)
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