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

Write a function named minutes that takes two datetimes and, using timedelta.total_seconds() to get the number of second

I could not spot any problem in my code.

minutes.py
import datetime

def minutes(datetime1,datetime2):
    return round(datetime2.total_seconds()/60) - round(datetime1.total_seconds()/60)

2 Answers

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,722 Points

You have the idea mostly right-- let's build on that.

The issue comes from datetime objects which don't have a total_seconds() method. So your code would throw errors. The timedelta object is a bit different than a datetime object. And the timedelta object has the total_seconds() method.

>>> import datetime
>>> # time is midnight on Feb 22, 2021
>>> datetime1 = datetime.datetime(2021, 2, 22)
>>> datetime1
datetime.datetime(2021, 2, 22, 0, 0)
>>> datetime1.total_seconds()
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    datetime1.total_seconds()
AttributeError: 'datetime.datetime' object has no attribute 'total_seconds'

Now let's create a second datetime object datetime2

>>> # create a datetime the same day at 3:00 AM
>>> datetime2 = datetime.datetime(2021,2,22,3,0)
>>> datetime2
datetime.datetime(2021, 2, 22, 3, 0)

Let's create a timedelta object by subtracting the two times. We can see total_seconds() method works on the timedelta object.

>>> tdelta = datetime2 - datetime1
>>> type(tdelta)
<class 'datetime.timedelta'>
>>> tdelta.total_seconds()
10800.0

Spolier alert... don't look at the solution if you want to solve it yourself!

Good luck with your Python journey!

def minutes(datetime1, datetime2):
    tdelta = datetime2 - datetime1 # calculate the time delta here
    return round( tdelta.total_seconds()/60 ) # convert to minutes, and round

Thanks Jeff, that helps me a lot