2015-04-12 95 views
0

使用strptime嘗試將從網站提取的字符串轉換爲日期格式時出現錯誤消息。我要提取的文本數據轉換成我做了一個字符串,但我得到一個錯誤消息說:使用strptime時出現錯誤信息(Python)

exceptions.ValueError: time data 'Sat 18th Apr 2015' does not match format '%a %d %b'. 

我檢查的文件,我想我有權利參數。我真的想要以YYYY,MM,DD格式將此信息保存到數據庫中。

這是我嘗試解決這個問題

item ['date'] = info.xpath('.//span[@class="dates"]//text()').extract() # Extract date information. 
    convert = ''.join(str(t)for t in item['date'])+" 2015" 
    print convert 
    time.strptime(convert, "%a %dth %b %Y") 

插入到像這樣一個數據庫...

def process_item(self, item, spider):  
     try: 
      self.cursor.execute("INSERT INTO info (venue, datez, dateForm, link, genre) VALUES (%s, %s, %s, %s, %s)", (item['artist'][0], item['date'][0], item['dateForm'][0], item['trackz'], "clubbing"))   
      self.conn.commit() 
     except MySQLdb.Error, e: 
      print "Error %d: %s" % (e.args[0], e.args[1]) 

      return item 
+0

'%d'不支持序號,在那裏除掉'th' 。 –

+0

哪裏來的一年? –

+0

對不起,忘了把一年放在... –

回答

0

你不需要redateutil只是rstrip分割後的字母:

from datetime import datetime 

a, b, c = item["date"][0].split() 

print(datetime.strptime("{} {} {} {}".format(a,b.rstrip("ndthstr"),c,"2015"),"%a %d %b %Y").strftime("%Y,%m,%d")) 

2015,04,18 
+0

我編輯了這個問題來展示我如何獲取數據......可能需要一種不同的方法?謝謝你的Halp Padraic –

+0

@DanielParkin,嘗試'''.join(t.rstrip(「thrdstn」)if t [0] .isdigit()else t for item in'[date']]'這將剝離th,nd,st等等。假設每個't'都是單獨的字符串。元素不是已經是字符串了嗎? –

+0

仍然收到錯誤訊息。這對我來說似乎很奇怪...... 'exceptions.ValueError:time data'Sat 18th Apr 2015''與格式不匹配'%a%d%b%Y'。'' –