If you have any questions, comments or issues with this project please post them here!
Hi, I was able to do the challenge but unsure why when finding the difference, we donāt use the timedelta function?
My solution worked, but was different from Davidās. I didnāt use the .days
parameter.
I asked ChatGPT about it, and learned something.
For reference, Davidās code and my code.
DAVIDāS SOLUTION:
import datetime
today = datetime.date.today()
print("EVENT COUNTDOWN")
day = int(input("Day: "))
month = int(input("Month: "))
year = int(input("Year: "))
event = datetime.date(year, month, day)
difference = event - today
difference = difference.days
if difference>0:
print(f"{difference} days to go")
elif difference<0:
print(f"ššššššš You missed it by {difference} days!")
else:
print("š„³š„³š„³š„³š„³š„³š„³ Today!")
My solution:
import datetime
today = datetime.date.today()
holiday = input("What's the event?\n> ").capitalize()
year = int(input("What's the year\n> "))
month = int(input("What's the month\n> "))
day = int(input("Input the day\n> "))
holidate = datetime.date(year, month, day)
difference = abs(holidate - today)
print(today)
print(holidate)
print(difference)
if holidate > today:
print(f"You have {difference} days until {holiday}!")
elif holidate < today:
print(f"It's been {difference} days since {holiday}!")
else:
print(f"{holiday} is today!")
ChatGPTās thoughts:
In Python, when you subtract two datetime.date
objects, the result is a datetime.timedelta
object, which represents the difference between two dates as a duration.
In Davidās code, the line difference = event - today
calculates the difference between event
and today
, resulting in a datetime.timedelta
object. To extract the number of days from the timedelta
object and convert it to an integer, the .days
attribute is used: difference = difference.days
.
On the other hand, in your code, you used abs(holidate - today)
to calculate the difference between holidate
and today
. Here, the abs()
function returns an absolute value, which results in a datetime.timedelta
object. However, in your code, you didnāt extract the .days
attribute, and thatās why your code worked without crashing.
The difference in behavior can be attributed to how you used the difference
variable in your code. In Davidās code, difference
is used later in the conditional statements, which require an integer comparison. Therefore, the .days
attribute is necessary to convert the timedelta
object to an integer.
In your code, you printed the difference
directly without any further calculations or comparisons, so you didnāt encounter any issues. However, if you were to use difference
in integer comparisons or calculations later in your code, you might need to use .days
as well.
To summarize, the .days
attribute is used to extract the number of days from a timedelta
object as an integer. Itās necessary if you need to perform integer comparisons or calculations with the result.
āholidateā¦ā this is amazing lol