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 Today and Tomorrow

Jay Reyes
seal-mask
.a{fill-rule:evenodd;}techdegree
Jay Reyes
Python Web Development Techdegree Student 15,937 Points

datetime.time() purpose?

Docs says this:

"Return time object with same hour, minute, second, microsecond and fold. tzinfo is None. See also method timetz()."

So, I do not need to provide arguments when I run datetime.time() in the console. So it gives me datetime.time(0, 0). I expect the console to display "same" hour, minute, etc... but I don't know what "same" means :).

Now when I run (what I think is a similar) function, such as datetime.date(), I need to provide the year, month, and day as arguments.

Could someone elaborate the use of the time function?

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,064 Points

In the datetime.time()initialization, the documentation means it returns a datetime.time object with the save values [as the arguments provided]. The default values being zero. So, datetime.time() return a midnight time of "00:00".

A datetime.time object allow comparisons of times be less than, greater than, or equal. It also allows creation of a datetime.datetime object from a datetime.date object using thecombine() method.

>>> import datetime
>>> t = datetime.time()
>>> t
datetime.time(0, 0)
>>> t1 = datetime.time(11, 20)
datetime.time(11, 20)
>>> t2 = datetime.time(13, 45)
>>> t2
datetime.time(13, 45)
>>> t1 > t2
False
>>> t1 < t2
True

>>> d = datetime.date(2019, 5, 19)
>>> d
datetime.date(2019, 5, 19)
>>> datetime.datetime.combine(d, t)
datetime.datetime(2019, 5, 19, 0, 0)

# a quick way to get a datetime object from a date object:
>>> new_dt = datetime.datetime.combined(d, datetime.time()) 
>>> new_dt
datetime.datetime(2019, 5, 19, 0, 0)

Post back if you have more questions. Good Luck!!