【问题标题】:Error with time.strptime() and python-twittertime.strptime() 和 python-twitter 出错
【发布时间】:2010-11-18 21:37:14
【问题描述】:

我使用python-twitter 获取推文的日期并尝试使用time.strptime() 函数对其进行解析。当我以交互方式进行操作时,一切正常。当我从我的 bash 调用程序时,我得到一个 ValueError 说(例如):

time data u'Wed Aug 12 08:43:35 +0000 2009' does not match 
          format '%a %b %d %H:%M:%S +0000 %Y'

代码如下:

api = twitter.Api(username='username', password='pw')
user = api.GetUser(username)
latest = user.GetStatus()
date = latest.GetCreatedAt()
date_struct = time.strptime(date, '%a %b %d %H:%M:%S +0000 %Y')

抛出上述异常。

它适用于交互式外壳:

>>> user = api.GetUser('username')
>>> latest = user.GetStatus()
>>> date = latest.GetCreatedAt()
>>> date
u'Wed Aug 12 08:15:10 +0000 2009'
>>>> struct = time.strptime(date, '%a %b %d %H:%M:%S +0000 %Y')
>>>> struct
time.struct_time(tm_year=2009, tm_mon=8, tm_mday=12, tm_hour=8, tm_min=15, tm_sec=10, tm_wday=2, tm_yday=224, tm_isdst=-1)

有人知道为什么会这样吗?

我正在使用 Ubuntu 9.04、Python 2.6.2 和 python-twitter 0.6。 unicode 格式的所有文件。

【问题讨论】:

  • 你可能运行了不同版本的python?比较交互式 shell 和 bash shell 的默认解释器的 sys.version 输出。
  • 不,交互式 shell 说“2.6.2(release26-maint,2009 年 4 月 19 日,01:56:41)\n[GCC 4.3.3]”并且 Bash 说(python --version) “Python 2.6.2”

标签: python twitter


【解决方案1】:

要尝试的事情:

(1) 您的交互式会话和您的“bash”是否可能使用不同的语言环境?将print time.strftime(some known struct_time) 放入您的脚本中,看看日期和月份是否以不同的语言显示。

(2) 将print repr(date) 放入您的脚本中,以明确显示您从latest.GetCreatedAt() 调用中得到了什么。

【讨论】:

  • (1) 帮助解决了这个问题。多谢! test = time.gmtime() print time.strftime('%a %b %d %H:%M:%S +0000 %Y', test) 在我的语言环境(de_DE)中打印它,例如'Wed'星期三是 Mittwoch 的“Mit”。这导致 strptime() 失败。我设置了 locale.setlocale(locale.LC_ALL, 'C'),它目前正在工作。稍后我将更深入地研究这个问题。再次感谢!
猜你喜欢
  • 2012-08-30
  • 1970-01-01
  • 2012-03-02
  • 2010-12-03
  • 1970-01-01
  • 2013-11-02
  • 2012-05-05
  • 2014-12-20
  • 2015-10-25
相关资源
最近更新 更多