【问题标题】:Issue splitting datetime - 'str' object has no attribute 'strptime'问题拆分日期时间 - 'str' 对象没有属性 'strptime'
【发布时间】:2013-01-30 14:57:09
【问题描述】:

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

以下代码有效:

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")

但是如果我添加以下行,我会得到一个错误:

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

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

【问题讨论】:

    标签: python datetime time strptime


    【解决方案1】:

    您将字符串分配给名为time 的变量。请改用其他名称,它会掩盖您的 time 模块导入。

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

    【讨论】:

      【解决方案2】:

      它可能工作了一次然后停止工作,因为你用一个名为“时间”的变量覆盖了模块“时间”。使用不同的变量名。

      这会覆盖时间模块

      >>> 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'
      

      你应该这样做

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-28
        • 2019-04-29
        • 1970-01-01
        • 1970-01-01
        • 2019-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多