使用timedelta时发生AttributeError:类型对象'datetime.datetime'没有属性'datetime'

时间:2018-07-18 20:48:57

标签: 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-%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'

1 个答案:

答案 0 :(得分:1)

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

您应该致电t = datetime(*struct_time[:6])

只需import datetime并将其命名为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)