Reputation: 485
I cannot understand why this is failing, can someone please explain:
import datetime
def test(timestamp):
xt = datetime(2013, 4,4)
dt = datetime.strptime(timestamp, '%d/%m/%Y %H:%M:%S')
print (xt,dt)
test('04/04/2013 08:37:20')
The error is:
Traceback (most recent call last): File "", line 12, in File "", line 5, in test TypeError: 'module' object is not callable
It seems to work ok with from datetime import datetime
instead. I can't understand what the difference is.
Thanks.
Upvotes: 2
Views: 1794
Reputation: 1477
Here datetime
can refer to the module or the class within the module so you have to disambiguate
import datetime
def test(timestamp):
xt = datetime.datetime(2013, 4,4)
dt = datetime.datetime.strptime(timestamp, '%d/%m/%Y %H:%M:%S')
print (xt,dt)
test('04/04/2013 08:37:20')
gives the following output:
(datetime.datetime(2013, 4, 4, 0, 0), datetime.datetime(2013, 4, 4, 8, 37, 20))
Upvotes: 1
Reputation: 383
datetime
is the datetime module, datetime.datetime
is the datetime type:
import datetime
def test(timestamp):
xt = datetime.datetime(2013, 4,4)
dt = datetime.datetime.strptime(timestamp, '%d/%m/%Y %H:%M:%S')
print (xt,dt)
Upvotes: 1
Reputation: 59974
Because in the datetime
module, there is a datetime()
function, but you didn't call it ( you instead tried to call the module, that's why you got a TypeError: 'module' object is not callable
).
import datetime
def test(timestamp):
xt = datetime(2013, 4,4) # Problem is this line.
dt = datetime.strptime(timestamp, '%d/%m/%Y %H:%M:%S')
print (xt,dt)
test('04/04/2013 08:37:20')
To fix the line, change it to:
xt = datetime.datetime(2013,4,4)
The reason from datetime import datetime
worked was because you imported the specific function, and so you wouldn't need to do datetime.datetime()
.
Upvotes: 5
Reputation: 500167
The
xt = datetime(2013, 4,4)
should be
xt = datetime.datetime(2013, 4,4)
Here, datetime
is the name of the module. The full name of the class is datetime.datetime
.
Upvotes: 1
Reputation: 38956
datetime
is both a module AND a class in that module. In your example you need datetime.datetime
.
Upvotes: 1