'Python: TypeError: 'list' object cannot be interpreted as an integer (Loop using defined function to created variables)
def on_time_daysx(repayment_date, end_date, on_time_date, start_date):
if repayment_date == end_date:
on_time_days = (on_time_date - start_date).days + 1
else:
on_time_days = (on_time_date - start_date).days
return on_time_days
for s in range(1,5):
from datetime import date
globals()[f"on_time_days{s}"] = on_time_daysx(repayment_date, end_date, on_time_date, date([f'start_date{s}']))
I have start_date1 to start_date5 as variables and want to use them in the function to create variables for on_time_days1 to on_time_days5.
New to python and generally coding.
Solution 1:[1]
I think, the error happens in your last line. date is expecting an integer, but you are passing a list containing one string ([f'start_date{s}']).
I can recommend using strptime, which converts strings into datetime objects. You can read that up here: https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime
Another thing I see here is that you import a package inside a loop. That means it's imported over and over again. Usually, packages are imported at the very beginning of a file.
Best, Joey
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | joey192 |
