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 Dates and Times in Python (2014) Dates and Times Timedelta Minute

Y B
Y B
14,136 Points

converting timedeltas

I have a feeling that I'm don't quite know what the time delta attributes do, which means I'm failing this challenge. Does time delta.seconds give the time difference converted to seconds or only the seconds component of the time difference?

If it's the later do i therefore need to do time delta.days (then convert to minutes) time delta.hours then convert to minute etc.. and then add them all up. Surely there must be a simpler way?

minutes.py
import datetime


def minutes(dt1, dt2):
    dif = dt1 - dt2
    dif = round(dif.seconds/(60))
    return dif

3 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

You're super close. We're finding the difference (which means subtraction, like you did) between two datetimes. If I want the difference between 5 and 2, what math problem do I do? You should always think of newer/more recent datetimes as bigger.

Y B
Y B
14,136 Points

Arrgh... how did that slip back in. I had second - first in an earlier version. Thanks.

So in answer to my question above the seconds attribute does give the whole time delta converted into seconds?

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

No, it just gives the seconds aspect of the timedelta. For example:

>>> dt1 = datetime.datetime.now()
>>> dt2 = dt1.replace(day=dt1.day+1)
>>> td = dt2 - dt1
>>> td.seconds
0
>>> td.days
1

But the CC is, of course, written so that we don't have a gap that's measured in days. Everything up to 1 day will come out a seconds. Anything over 1 day, but not yet at 2 days, will come out as 1 day and some number of seconds. And on and on.

Y B
Y B
14,136 Points

ok so to make a universal function that would convert any time delta into minutes (i.e. one with days, months, years apart) I would have to break it into components i.e. the days the months etc... to convert to minutes. Is that not a really standard use that one would expect to be included in the library (i.e. conversion of any time delta into, any time unit, whether it be seconds or months etc.....)?

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Looking at the timedelta object, there's a .total_seconds() method that will give you the total number of seconds contained in the timedelta.