问题描述:

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.

网友答案:

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().

网友答案:

datetime is both a module AND a class in that module. In your example you need datetime.datetime.

网友答案:

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.

网友答案:

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)
网友答案:

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))

相关阅读:
Top