Python 问题拆分日期时间 - “str”对象没有属性“strptime”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14881063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:44:20  来源:igfitidea点击:

Issue splitting datetime - 'str' object has no attribute 'strptime'

pythondatetimetimestrptime

提问by bsiddiqui

I'm trying to split datetime... it works well to store date but I get an error whenever I try and store time.

我正在尝试拆分日期时间...存储日期效果很好,但是每当我尝试存储时间时都会出错。

The following code works:

以下代码有效:

datetime =  tweet.date.encode( 'ascii', 'ignore')
struct_date = time.strptime(datetime, "%a, %d %b %Y %H:%M:%S +0000")
date = time.strftime("%m/%d/%Y")

But if I add the following line, I get an error:

但是,如果我添加以下行,则会出现错误:

  time = time.strftime("%H:%M:%S")

AttributeError: 'str' object has no attribute 'strptime'

AttributeError: 'str' 对象没有属性 'strptime'

采纳答案by Martijn Pieters

You assigned a string to a variable named time. Use a different name instead, it is masking your timemodule import.

您将一个字符串分配给名为 的变量time。改用不同的名称,它会屏蔽您的time模块导入。

tm = time.strptime(datetime, "%H:%M:%S")

回答by tdelaney

It probably worked once and then stopped working because you overwrote the module 'time' with a variable named 'time'. Use a different variable name.

它可能工作过一次然后停止工作,因为您用名为“time”的变量覆盖了模块“time”。使用不同的变量名称。

This overwrites the time module

这会覆盖时间模块

>>> import time
>>> type(time)
<type 'module'>
>>> time = time.strftime("%H:%M:%S")
>>> type(time)
<type 'str'>
>>> time = time.strftime("%H:%M:%S")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'strftime'

This is how you should do it

这是你应该做的

>>> import time
>>> type(time)
<type 'module'>
>>> mytime = time.strftime("%H:%M:%S")
>>> type(time)
<type 'module'>
>>> time.strftime("%H:%M:%S")
'11:05:08'