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

Anish Walawalkar
Anish Walawalkar
8,534 Points

Write a function to calc the minute diff between 2 datetime objs. assume arg1>arg2.

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

I get an error on the interactive code challenge environment

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

1 Answer

Dan Johnson
Dan Johnson
40,533 Points

Since datetime objects represent points in time checking against their specific components won't tell you too much

For example, this will print out 19:

# Equivalent to the date: January 1st 1980 at 12:30
earlier_date = datetime.datetime.fromtimestamp(315577830)
# At the time of this post: May 23rd 2015 at 14:11
today = datetime.datetime.fromtimestamp(1432415498)

print(round(earlier_date.minute - today.minute))

It's been a bit longer than 19 minutes since the 1980s but this only checks against the minute component of the time so that's what you get.

What you'll want to do is use the resulting timedelta from subtracting two datetime objects and then use the total_seconds method to get the elapsed time.

Using the dates from before:

# Note the latest date first
print( round((today - earlier_date).total_seconds() / 60) )

This will result in 18614021, the actual minutes that have elapsed.