43

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)
Santiago
  • 1,984
  • 4
  • 19
  • 24

3 Answers3

52

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • The three-parameter constructor is equally valid, just redundant. http://docs.python.org/library/datetime.html#datetime.time – Ry- Sep 05 '12 at 23:46
  • @Martijn ok so what should I keep/change? – Santiago Sep 05 '12 at 23:48
  • @Martijn I have tried only importing datetime and time but when I do this I now get this error: 'module' object has no attribute 'strptime' refering to line : value = datetime.strptime(value, format) – Santiago Sep 05 '12 at 23:52
  • @Santiago: that's a classmethod, call `datetime.datetime.strptime()`. – Martijn Pieters Sep 05 '12 at 23:54
22

The constructor for time is:

class datetime.time(hour[, minute[, second[, microsecond[, tzinfo]]]])

(from http://docs.python.org/library/datetime.html#time-objects)

This works for me:

In [1]: import datetime

In [2]: t = datetime.time(0, 0, 0)

In [3]: print t
00:00:00
sandesh247
  • 1,658
  • 1
  • 18
  • 24
9

It's the fact that you're importing a conflicting datetime from datetime. You probably meant time, except you're also importing a conflicting time. So how about:

import datetime as dt

and

t = dt.time(0, 0, 0)
Ry-
  • 218,210
  • 55
  • 464
  • 476