首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用TimeDelta时的时间:类型对象'datetime.datetime‘没有属性’AttributeError‘

问使用TimeDelta时的时间:类型对象'datetime.datetime‘没有属性’AttributeError‘
EN

Stack Overflow用户
提问于 2018-07-19 04:48:57
回答 1查看 3.3K关注 0票数 0

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

代码语言:javascript
复制
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)

错误:

代码语言:javascript
复制
    t = datetime.datetime(*struct_time[:6])
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-19 04:52:47

您正在从datetime导入datetime。在后面的代码中,你使用了datetime.datetime,所以这会给你带来错误。

你应该直接打电话给t = datetime(*struct_time[:6])

或

只需执行import datetime并将其命名为t = datetime.datetime(*struct_time[:6])

正确的程序应该如下所示:

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51410772

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档