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.

Python Dates and Times in Python Dates and Times strftime & strptime

Code not working. need help.

can someone help? my code isnt running.

timestrings.py
import datetime
## Examples
# to_string(datetime_object) => "24 September 2012"
# from_string("09/24/12 18:30", "%m/%d/%y %H:%M") => datetime
def to_string(datetime):
    return(datetime('%D %B %Y'))

def from_string(datetime):
    return(datetime("%D/%B/%Y %H:%M"))

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 67,911 Points

Hey Brendan Dzeguze, you are on the right path, Let's get finish this together

  • The module datetime was imported correct. By naming the to_string parameter "datetime", the imported module name is overwritten inside the function. This makes it not possible to use any datetime module functions. :point_right: avoid using module names or builtin function names as parameter names. Try using dtime as parameter name.
  • To convert to a string, a datetime object has a strftime method. :point_right: use `dtime.strftime() with your format string as the argument to convert a string
  • The "%D" format returns a full date, you probably meant to use "%d" for the day value. :point_right: "'%d %B %Y"
  • for from_string, you will need to call the constructor method datetime.datetime.strptime(string, format) where the string and frmt are passed into the function. Just using datetime points to the module, to get the class and method. It can be confusing when the main object class is the same name as its module name.

More on strptime in the docs

Post back if you need more help! Good luck!!