Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
jun cheng wong17,021 Points
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.
import datetime def minutes(datetime1,datetime2): return round(datetime2.total_seconds()/60) - round(datetime1.total_seconds()/60)
Jeff MudayTreehouse Moderator 26,597 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
>>> 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
>>> 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