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

minutes challenge

What am I doing wrong here?

import datetime


def minutes(dt1, dt2):
    return round(dt2.minute - dt1.minute)

It's expecting 7 but my code is returning 53 or something.

When I try this out locally, it seems to work as expected:

import datetime


def minutes(dt1, dt2):
    return round(dt2.minute - dt1.minute)

dt1 = datetime.datetime.now()
dt2 = dt1 + datetime.timedelta(minutes=5)

print(minutes(dt1, dt2))

This prints 5 and there are 5 minutes between the two datetimes I fed the function.

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

You are not taking into account a difference in hours or days. 5:12 - 4:07 would be 65 not 5.

A better approach is to subtract the two datetime objects directly:

diff = dt2 - dt1

This produces a timedelta object. You can then use the diff.total_seconds() method to get the minutes by dividing by 60 (and rounding of course).

I see. Thanks for the help.