我正在解析測量文件(大約200k行)的日期。格式是日期和度量。日期格式爲「2013-08-07-20-46」或時間格式爲「%Y-%m-%d-%H-%M」。往往時間戳有一個壞字符。 (數據來自有中斷的串行鏈路)。該條目看起來像:201-08-11-05-15。防止格式不匹配時退出datetime.strptime
我的分析線的時間字符串轉換成秒是:
time.mktime(datetime.datetime.strptime(dt, "%Y-%m-%d-%H-%M").timetuple())
我得到了它的在線和不完全瞭解它是如何工作的。 (但它的作品)
我的問題是防止程序在發生格式不匹配時拋出錯誤退出。有沒有辦法阻止strptime無法退出,但優雅地返回一個錯誤標誌,在這種情況下,我會簡單地丟棄數據行並轉移到下一個。是的,我可以使用正則表達式執行模式檢查,但我想知道是否有一些智能不匹配處理已經內置到了strptime中。
追加@阿南德小號庫馬爾
它工作了幾個壞線,但隨後失敗。
fp = open('bmp085.dat', 'r')
for line in fp:
[dt,t,p]= string.split(line)
try:
sec= time.mktime(datetime.datetime.strptime(dt, "%Y-%m-%d-%H-%M").timetuple()) - sec0
except ValueError:
print 'Bad data : ' + line
continue #If you are doing this in a loop (looping over the lines) so that it moves onto next iteration
print sec, p ,t
t_list.append(sec)
p_list.append(p)
fp.close()
輸出:
288240.0 1014.48 24.2
288540.0 1014.57 24.2
288840.0 1014.46 24.2
Bad data : �013-08-11-05-05 24.2! 1014.49
Bad data : 2013=0▒-11-05-10 �24.2 1014.57
Bad data : 201�-08-11-05-15 24.1 1014.57
Bad data : "0�#-08-1!-p5-22 24.1 1014.6
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError: too many values to unpack
>>>
追加@阿南德小號庫馬爾
它再次崩潰。
for line in fp:
print line
dt,t,p = line.split(' ',2)
try:
sec= time.mktime(datetime.datetime.strptime(dt, "%Y-%m-%d-%H-%M").timetuple()) - sec0
except ValueError:
print 'Bad data : ' + line
continue #If you are doing this in a loop (looping over the lines) so that it moves onto next iteration
print sec, p ,t
失敗:
2013-08-11�06-t5 03/9 9014.y
Bad data : 2013-08-11�06-t5 03/9 9014.y
2013-08-11-06-50 (23. 1014.96
295440.0 (23. 1014.96
2013-08-11-06%55 23.9 !�1015.01
Traceback (most recent call last):
File "<stdin>", line 5, in <module>
TypeError: must be string without null bytes, not str
>>> fp.close()
>>>
'嘗試 - except'是你在尋找什麼。 – Psytho
@GertGottschalk你可以檢查第二個錯誤的更新答案。 –
@Anand S Kumar謝謝。在檢查輸入行時,使用regexp可能是最簡單的(只需檢查是否存在3個字符串)。我還沒有決定。 –