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

John Reilly
John Reilly
10,800 Points

Expected 7 got 53! datetime challenge

I am trying to complete the challenge of finding the minutes between two times. I am using the code below and cannot for the life of me understand what is wrong. I am receiving the error shown in the title

Perhaps fresh eyes will notice my silly mistake straight away but my tired eyes are of no use to me at the moment!

Thanks in advance, John

minutes.py
import datetime

def minutes(datetime1, datetime2):
  min1 = (datetime1.minute)
  min2 = (datetime2.minute)
  minutes_rounded = round(min1 - min2)
  return (minutes_rounded)

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

Your approach of comparing the datetime.minute values does not account for wrapping across the hour boundary or day boundary.

Two datetimes can be substracted directly to produce a timedelta object. You can then get the minutes from this object using its built-in method total_seconds()

import datetime

def minutes(datetime1, datetime2):
    # create timedelta object
    # datetime 1 is "older", meaning it has a lower absolution time (small value)
    time_delta = datetime2 - datetime1
    minutes_rounded = round(time_delta.total_seconds()/60)
    return minutes_rounded