I'm trying to increment a date using openpyxl. Here's some example code:
import openpyxl
import os
import datetime
os.chdir("C:\\Personal\\Rentals\\xxxx")
wb = openpyxl.load_workbook(filename = 'Income_Receipts.xlsx', read_only=False)
sheet = wb['Sheet1']
cellreference = "B" +str(6)
cell = sheet[cellreference]
def LastRowNumber():
global sheet, cellreference, cell
i = 4
BlankRowNumber = 0
while BlankRowNumber == 0:
i = i + 1
cellreference = "B" + str(i)
cell = sheet[cellreference]
if cell.value == None:
BlankRowNumber = i
return i
def FormatDatesToNumbers(RowNumber):
global sheet, cellreference, cell, wb
#if sheet["B" + str(RowNumber)].value == "Airbnb":
sheet["I" + str(RowNumber)].number_format = "######.0"
sheet["F" + str(RowNumber)].number_format = "######.0"
wb.save('Income_Receipts.xlsx')
def AirbnbDueDates(RowNumber):
global sheet, wb
if sheet.cell(row = RowNumber, column = 2).value =="Airbnb":
DateAsFloat = sheet["F" + str(RowNumber)].value + 5
sheet["I" + str(RowNumber)] = DateAsFloat + 5
wb.save('Income_Receipts.xlsx')
LastRowToProcess = LastRowNumber() - 1
i = 4
while i <= LastRowToProcess:
i = i + 1
FormatDatesToNumbers(i)
i = 4
while i <= LastRowToProcess:
i = i + 1
AirbnbDueDates(i)
wb.save('Income_Receipts.xlsx')
Please excuse the code if its a little untidy - I keep playing around trying to get around the issue which is - I get the following error message:
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'int'
The issue is I am trying to increment a given date by 5 days for example - but I can't mix datetime.datetime and ints.
I've tried typecasting the datetime to an int or a float, but that doesn't work...
If I manually open the excel sheet and change the data type to an integer (as I try to do in my code above) then my code works fine. However if the relevant cells are formatted as a date I get the error.
I thought saving the worksheet after the change in formatting would sort the issue, but unfortunately not...
Any pointers much appreciated,
Thanks
Rob