python调试简单的日期时间对象

mat*_*tel 2 python datetime

我不明白为什么这会失败,有人可以解释一下:

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')
Run Code Online (Sandbox Code Playgroud)

错误是:

回溯(最近一次调用最后一次):
  文件“”,第 12 行,在 
  文件“”,第 5 行,在测试中
类型错误:“模块”对象不可调用

它似乎可以正常工作from datetime import datetime。我无法理解有什么区别。

谢谢。

Ter*_*ryA 5

因为在datetime模块中,有一个datetime()函数,但你没有调用它(你尝试调用模块,这就是为什么你得到了一个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')
Run Code Online (Sandbox Code Playgroud)

要修复该行,请将其更改为:

xt = datetime.datetime(2013,4,4)
Run Code Online (Sandbox Code Playgroud)

有效的原因from datetime import datetime是因为您导入了特定功能,因此您不需要执行datetime.datetime().