2015-09-19 132 views
0

我在這個格式的字符串:「星期六9月19日十五時十八分51秒2015年」格式化字符串2.7

我想重新格式化爲「20150919」我有花了最近幾個小時閱讀這個網站上的Python文檔和Q/A有關,但我仍然堅持。我可以用切片和字符串處理來完成,但我正在尋找更好的方法來完成目標。正確的方向點將不勝感激。

回答

0

如果格式是持久的,則可以使用python datetime模塊。

代碼:

from datetime import datetime 
input = "Sat Sep 19 15:18:51 2015" 
# See if you can replace parse_format string with "%c" 
parse_format = "%a %b %d %H:%M:%S %Y" 
output_format = "%Y%m%d" 
datetimeobj = datetime.strptime(input, parse_format) 
output = datetimeobj.strftime(output_format) 
print output