【问题标题】:TypeError: string indices must be integers datetimeTypeError:字符串索引必须是整数日期时间
【发布时间】:2015-12-18 10:08:36
【问题描述】:

我正在尝试转换日期时间,但我不知道如何让我的字符串成为整数。我尝试在 (entry["created_at"] 之后添加 [0] 但不是运气

代码:

$for 数据项:

   `$` convertedTweet = {}

for entry in item:
   convertedTweet["created_at"] = item["created_at"]
   fmt = '%Y-%m-%dT%H:%M:%SZ'
   temp = datetime.strptime(entry['created_at'],'%a %b %d %H:%M:%S +0000 %Y').replace(tzinfo=pytz.UTC)
   print temp.strftime(fmt)

错误:

temp = datetime.strptime(entry['created_at'],'%a %b %d %H:%M:%S +0000 %Y').replace(tzinfo=pytz.UTC)
TypeError: string indices must be integers

【问题讨论】:

  • I can't figure out how to get my string to be an integer int(string) 呢?
  • item 是转换推文,更新代码

标签: python string integer typeerror


【解决方案1】:

看起来 item 是一个字典(当你这样做时 - item["created_at"],它不会为你出错)。

如果是这样,当你遍历字典时 -

for entry in item:

entry 表示字典中的键,很可能是字符串。因此,当您尝试这样做时 - entry['created_at'] - 当您尝试对字符串使用字符串索引时,它会出错,这是不可能的。

看起来你根本不需要循环,你可以直接访问 - item["created_at"] - 来获取日期时间。示例 -

convertedTweet["created_at"] = item["created_at"] 
temp = datetime.strptime(item["created_at"],'%a %b %d %H:%M:%S +0000 %Y').replace(tzinfo=pytz.UTC)
print temp.strftime('%Y-%m-%dT%H:%M:%SZ')

【讨论】:

  • 很高兴它对你有用。如果答案有帮助,我还想请您接受答案(通过单击答案左侧的勾号),这将对社区有所帮助。
  • 我想我做到了。这是我的第一篇文章。再次感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2021-03-28
  • 2021-04-28
  • 2020-06-24
  • 2016-03-26
  • 2017-09-07
  • 2018-08-19
  • 2016-02-17
相关资源
最近更新 更多