2016-08-16 52 views
-1

我想解析這個「截至2015年12月31日的年份」,並使用datetime庫將其轉換爲2015-12-31。我將如何去分區,然後轉換日期?我的程序正在瀏覽一個帶有多個工作表的excel文件,並將它們合併爲一個;但是,現在需要添加日期列,但我只能將它寫入單元格的完整值。所以我的數據列目前在所有行中都有「截至2015年12月31日的年度」。解析一個字符串並使用Python轉換日期

在此先感謝!

這是現在正在工作的代碼塊。謝謝大家!編輯以解釋可能會有所不同的文字。

if rx > (options.startrow-1): 
      ws.write(rowcount, 0, sheet.name) 
      date_value = sheet.cell_value(4,0) 
      s = date_value.split(" ") 
      del s[-1] 
      del s[-1] 
      del s[-1] 
      string = ' '.join(s) 

      d = datetime.strptime(date_value, string + " %B %d, %Y") 
      result = datetime.strftime(d, '%Y-%m-%d') 
      ws.write(rowcount, 9, result) 
      for cx in range(sheet.ncols): 
+0

請分享你至今嘗試你怎麼了包括完整代碼。 –

+0

請看看這個。我希望這有幫助。 http://stackoverflow.com/questions/2265357/parse-date-string-and-change-format?noredirect=1&lq=1 – Ehsan

回答

4

簡單地包括硬編碼的部分,然後用適當的標識符:

>>> import datetime 
>>> s = "For The Year Ending December 31, 2015" 
>>> d = datetime.datetime.strptime(s, 'For The Year Ending %B %d, %Y') 
>>> result = datetime.datetime.strftime(d, '%Y-%m-%d') 
>>> print(result) 
2015-12-31 
+0

Ty正是我所需要的 –

2
from datetime import datetime 

date_string = 'For The Year Ending December 31, 2015' 
date_string_format = 'For The Year Ending %B %d, %Y' 
date_print_class = datetime.strptime(date_string, date_string_format) 
wanted_date = datetime.strftime(date_print_class, '%Y-%m-%d') 

print(wanted_date) 
+0

TY你好,但我用虎的解決方案。 –

相關問題