how to initialize time() object in python

Santiago picture Santiago · Sep 6, 2012 · Viewed 72.6k times · Source

I am trying to initialize a time object like this:

t = datetime.time(0,0,0)

but I am getting this error:

descriptor 'time' requires a 'datetime.datetime' object but received a 'int'

I have these things imported

import datetime
from datetime import datetime, date, time
import time

They seem a bit redundant so I am wondering if this is what is causing the problem

I am also using the strptime method and the combine method

    earliest = datetime.combine(earliest, t)
    value = datetime.strptime(value, format)

Answer

Martijn Pieters picture Martijn Pieters · Sep 6, 2012

You can create the object without any values:

>>> import datetime
>>> datetime.time()
datetime.time(0, 0)

You, however, imported the class datetime from the module, replacing the module itself:

>>> from datetime import datetime
>>> datetime.time
<method 'time' of 'datetime.datetime' objects>

and that has a different signature:

>>> datetime.time()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: descriptor 'time' of 'datetime.datetime' object needs an argument
>>> datetime.time(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: descriptor 'time' requires a 'datetime.datetime' object but received a 'int'

Either import the whole module, or import the contained classes, but don't mix and match. Stick to:

import datetime
import time

if you need both modules.