Python Dates and Times in Python Dates and Times Timedelta Minute

jun cheng wong
jun cheng wong
9,457 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.

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 25,376 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
jun cheng wong
jun cheng wong
9,457 Points

Thanks Jeff, that helps me a lot