Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Timedelta minute coding challenge in Python question

why doesn't the following work:

def minutes(dt_one, dt_two):
    dif = dt_two.second - dt_one.second
   num = round(dif/60)
   return num

the following is the solution that did work:

def minutes(dt_one, dt_two): dif = dt_two - dt_one num = round((dif.seconds)/60) return num

my question is, shouldn't both work? what is the difference, and why is the second way better than the first way?

this is the code for the second way:

def minutes(dt_one, dt_two):
    dif = dt_two - dt_one
   num = round((dif.seconds)/60)
   return num

i know that here I messed up on the indentation, but when i actually ran it my indentation was fine for both ways

1 Answer

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

dt_one and dt_two are both datetimes. Let's say that dt_one is 2014-02-16 8:50:29 and dt_two is 2015-02-16 8:50:28.

Now, subtracting the second attribute from each of them will give you 1. Is there only one second of difference between those two datetimes?

I understand that, but why does dif.seconds give me the total amount of seconds between the two dates? if i do this:

import datetime

now = datetime.datetime.now()

three_days = now.replace(day = 19)

dif = three_days - now

print(dif.seconds)

I get 0, not 259200 (number of seconds in three days). So isn't it just subtracting the number of seconds from the number of seconds and printing that out without regard for the number of hours, days, years, or minutes between them?

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

We're not expecting the total elapsed seconds between one datetime and another. You'd check the .total_seconds() method for that. I know that the two datetime objects I give you have a certain number of seconds (not days or microseconds, since those are the only other attributes we could check) between them and that it's not an even number of minutes when converted.