2013-05-13 64 views
0

我試圖在以下日期(這是一個字符串)轉換爲datetime對象:格式與time.strptime()拋出一個錯誤

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' 

我不確定爲什麼這會失敗,因爲日期時間字符串格式對我來說似乎是正確的。

+0

閱讀[文件](http://docs.python.org/2/library/time.html#time.strptime)!錯誤信息其實很清楚(時間數據'xxx'與格式'yyy'不匹配) – 2013-05-13 15:04:10

+0

是的,愚蠢的錯誤>< – 2013-05-13 15:07:12

回答

1

你的參數是錯誤的,格式字符串應該是第二個參數。

嘗試:

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

哇,愚蠢的錯誤><謝謝! – 2013-05-13 15:06:22

+0

不用擔心。如果它解決了您的問題,您可能需要考慮接受我的答案。謝謝 – stonesam92 2013-05-13 15:09:46