2017-10-06 217 views
0

我遇到了一些與Python的dateutil.parser有關的問題。ValueError:未知的字符串格式dateparser python CSV

我有一個CSV文件,我負責閱讀和顯示月份。

一個組可能有29 Jun 2017 1600,而其中一些有「2017年6月29日1600小時」,只要數據有額外的字符串,如hrs。它會顯示此錯誤:ValueError: Unknown string format

這裏是我的代碼:dt = dateutil.parser.parse(data.GetDataType(frequency))

如何刪除hrs或允許程序能夠流暢運行?

回答

0
# full, working, python 3 solution 
# modified to work on strings with or without "hrs" 
# "$" in re.sub means hrs only matches at end of input string 
# I hope you read this, because I can change this answer, but I cannot comment :-D 

import re 
from datetime import datetime 

stringDateIn1 = "29 Jun 2017 1601" 
stringDateIn2 = "29 Jun 2017 1602 hrs" 

stringDateFixed1 = re.sub(" hrs$", "", stringDateIn1) 
stringDateFixed2 = re.sub(" hrs$", "", stringDateIn2) 

datetimeOut1 = datetime.strptime(stringDateFixed1, '%d %b %Y %H%M') 
datetimeOut2 = datetime.strptime(stringDateFixed2, '%d %b %Y %H%M') 

print("date = " + str(datetimeOut1)) 
print("date = " + str(datetimeOut2)) 
+0

有些數據有小時,有些則沒有。我如何確保它可以在有或沒有小時的情況下順利運行?謝謝您的幫助! –