I'm learning python by myself for almost a month and i was confronted with an exercise that involves "datetime" and arithmetic operators.
First - they asked me to create a code where the users should enter the deadline for their project and the code must tell them how many days they have to complete.
And i did this:
import datetime
today = datetime.date.today()
delivery_date = input("Tell me your deadline (dd/mm/aa): ")
print("\n")
deadline = datetime.datetime.strptime(delivery_date, "%d/%m/%y").date()
days = delivery_date - today
print("You have", days.days, "days to finish your project.")
But the second part it's kinda tricky.
Second - they are asking me to try to give the answer as a combination of weeks and days and that i will need some math functions to solve this final part.
And i did this:
weeks = days // 7
remainder_days = days % 7
print("You have", weeks.days, "weeks and", remainder_days.days, "days.")
Only this final part fails. In the end i get this error message:
remainder_days = days % 7
TypeError: unsupported operand type(s) for %: 'datetime.timedelta' and 'int'
I know that the problem is with the modulus symbol (%) but if they are asking me to give the final result as a combination of weeks and days, it's possible, but i can't see how.
Is any other way with a simple math operation to solve this?
Do i need to put anything in my code?
Can someone help me please?
Thank you
days = delivery_date - today
should be days = deadline - today
. Also you should call it delta
, because it's a time delta, where you can do delta.days
to get the number of days. Simply use delta.days
later on.
Also delta.days
is just a number, so when doing delta.days // 7
, you don't want to call .days
on the result.
Something like the following should work:
import datetime
today = datetime.date.today()
delivery_date = input("Tell me your deadline (dd/mm/aa): ")
print("\n")
deadline = datetime.datetime.strptime(delivery_date, "%d/%m/%y").date()
delta = deadline - today
print("You have", delta.days, "days to finish your project.")
weeks = delta.days // 7
remainder_days = delta.days % 7
print("You have", weeks, "weeks and", remainder_days, "days.")
By the way the error points you in the right direction: TypeError: unsupported operand type(s) for %: 'datetime.timedelta' and 'int'
. It means you have a time delta object, on which you're applying the modulo operator with an integer, and python tells you it's not possible. So you'll need to somehow get an integer out of your time delta.