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) Let's Build a Timed Quiz App Harder Time Machine

Why the replace function is not accepted by this question?

I was working on the challenge for datetime.timedelta and the question didn't like my following solution for the years:

date == 'years':
        return starter.replace(starter.year + num)

I know I could do this

date == 'years':
        return starter + datetime.timedelta(days = num * 365)

I get the same result from both line of code for a simple tests. Could you please let me know why the replace function was not accepted? Thank you!

Steven Parker
Steven Parker
230,274 Points

It would help to see the entire solution that was submitted to the challenge.

3 Answers

Steven Parker
Steven Parker
230,274 Points

Aha, I see now. The trick is in the expedience suggested by the comments: "Consider a year to be 365 days."

Your approach is actually better, because when there is an intervening leap year, the results in the suggested method will be slightly off. But the challenge is expecting those values.

Hello Steven, Please find the function below:

import datetime

starter = datetime.datetime(2015, 10, 21, 16, 29) def time_machine(num, date): if date == 'minutes': return starter + datetime.timedelta(minutes = num) elif date == 'hours': return starter + datetime.timedelta(hours = num) elif date == 'days': return starter + datetime.timedelta(days = num) elif date == 'years': return starter.replace(starter.year + num)

Examples from running the function:

time_machine(5, "minutes") datetime.datetime(2015, 10, 21, 16, 34)

time_machine(5, "years") datetime.datetime(2020, 10, 21, 16, 29)

Steven Parker
Steven Parker
230,274 Points

To preserve the integrity of posted code, use the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area. :arrow_heading_down:   Or watch this video on code formatting.

Thank you so much Steven!