Search code examples
pythondatetimetimestrptime

How get just the "time" part from a datetime.strptime object python


I have data like this: "2016-10-17 09:34:02" with the format: "%Y-%m-%d %H:%M:%S" and I use: from datetime import datetime

My variable is like this:

date_object = datetime.strptime(datetemp, format)

So far, so good...

But I need get only the time part from this object (date_object) to make some comparisons...

When I do this:

print(date_object.time)

I get the following error:

built-in method time of datetime.datetime object at 0x00A94AE8

How can i get just the time part from the object date_object? This will allow me to make comparisons within hourly ranges.


Solution

  • You need to add parenthesis () to your print(date_object.time) call:

    print(date_object.time())
    

    Example output:

    >>> import datetime
    >>> now = datetime.datetime.now()
    >>> now.time()
    datetime.time(22, 14, 6, 996000)
    >>> print(now.time())
    22:14:06.996000