Python 使用timedelta时的AttributeError:type object';datetime.datetime';没有属性';日期时间';

Python 使用timedelta时的AttributeError:type object';datetime.datetime';没有属性';日期时间';,python,time,Python,Time,我有下面的代码,其中我试图读取时间字符串,并减少8小时的时间,并以人类可读的格式打印,但遇到以下错误。有人能提供如何解决这个问题的指导吗 import time from datetime import datetime time_string = '2018-07-16T23:50:55+0000' #Reduct 8 hours and print in human readable format struct_time = time.strptime(time_string, "%Y-%

我有下面的代码,其中我试图读取时间字符串,并减少8小时的时间,并以人类可读的格式打印,但遇到以下错误。有人能提供如何解决这个问题的指导吗

import time
from datetime import datetime
time_string = '2018-07-16T23:50:55+0000'

#Reduct 8 hours and print in human readable format
struct_time = time.strptime(time_string, "%Y-%m-%dT%H:%M:%S+0000")
t = datetime.datetime(*struct_time[:6])
delta = datetime.timedelta(hours=8)
print(t+delta)
错误:

    t = datetime.datetime(*struct_time[:6])
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'

您正在从
datetime
导入
datetime
。稍后在代码中,您将使用
datetime.datetime
,因此这会给您带来错误

您只需调用
t=datetime(*struct\u time[:6])

只需执行导入日期时间
并将其命名为
t=datetime.datetime(*struct_time[:6])

正确的程序应如下所示:

import time
import datetime
time_string = '2018-07-16T23:50:55+0000'

#Reduct 8 hours and print in human readable format
struct_time = time.strptime(time_string, "%Y-%m-%dT%H:%M:%S+0000")
t = datetime.datetime(*struct_time[:6])
delta = datetime.timedelta(hours=8)
print(t+delta)

您需要:
从datetime导入datetime
然后使用
datetime(*…)
;或者
导入datetime
然后使用
datetime.datetime(*…)
。名为
datetime
的模块包含一个名为
datetime
的类,因此您必须知道哪些名称当前在范围内。您当前试图访问不存在的
datetime.datetime.datetime
,因此出现了错误。@jonrsharpe-我的代码中已经有
来自datetime import datetime
,为什么它仍在抱怨?请阅读错误。这是因为,尽管将类作为
datetime
显式导入到当前范围中,您试图实例化它,就像您将整个模块导入为
datetime
。然后它抛出一个错误
AttributeError:type对象“datetime.datetime”在第
delta=datetime.timedelta(小时=8)行没有属性“timedelta”
@kemosabee只需编写
import datetime
,不从日期时间导入日期时间,并保持代码不变。我更新了我的答案时间增量增加了8个小时,我想减少8个小时,这怎么做/@kemosabee…减去它而不是增加它?!