使用time.strptime()格式化会引发错误

时间:2013-05-13 14:57:56

标签: python datetime

我正在尝试将以下日期(字符串)转换为日期时间对象:

Fri, 26 Apr 2013 12:00:00 +0000

所以我做的是抛出+0000值,然后使用以下代码将其转换为datetime对象:

published = entry['published']
print published
published = published[:-6]
print published
published = time.strptime("%a, %d %b %Y %H:%M:%S",str(published))

然后会抛出异常,说明给定的值格式不正确

Fri, 26 Apr 2013 12:00:00 +0000
Fri, 26 Apr 2013 12:00:00
        C:\Python27\python.exe 
    C:/obfuscated.py
        Traceback (most recent call last):
        Fri, 26 Apr 2013 12:00:00 +0000
          File "C:/obfuscated.py", line 17, in <module>
        Fri, 26 Apr 2013 12:00:00
            class MyClass(object):
          File "C:/obfuscated.py", line 38, in MyClass
            published = time.strptime("%a, %d %b %Y %H:%M:%S",str(published))
          File "C:\Python27\lib\_strptime.py", line 467, in _strptime_time
            return _strptime(data_string, format)[0]
          File "C:\Python27\lib\_strptime.py", line 325, in _strptime
            (data_string, format))
        ValueError: time data '%a, %d %b %Y %H:%M:%S' does not match format 'Fri, 26 Apr 2013 12:00:00'

我不确定为什么会失败,因为datetime stringformat对我来说似乎是正确的。

1 个答案:

答案 0 :(得分:1)

你的参数循环错误,格式字符串应该是第二个参数。

尝试:

published = time.strptime(str(published),"%a, %d %b %Y %H:%M:%S")