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

Using datetime

I’m having trouble with knowing how to format date time in Python. I’m mixing up variables by doing, for example, apples.timedelta() - oranges.timedelta, instead of doing, datetime.timedelta(apples - oranges). Can someone explain when u use dot notation or when you pass something in as a parameter? Also can someone explain when you are supposed to write the date time thing twice and when you’re not supposed to?

2 Answers

Steven Parker
Steven Parker
231,248 Points

The dot is also known as the "membership operator". You use dot notation to access something that is part of something else, like a class within a module, or method or attribute within a class.

Arguments are only passed when calling a function or method. This would include the internal __init__ method when constructing a new object.

And datetime is the name of both a module, and a class within that module. So if you import the module, you would use both names to access the class:

import datetime

start = datetime.datetime.now()
#       ^^^^^^^^ ^^^^^^^^ ^^^
#       module   class    method

But if you import the class itself, you can reference it without naming the module:

from datetime import datetime
#    ^^^^^^^^        ^^^^^^^^
#    module          class

start = datetime.now()

Thank you