2012-03-19 53 views
0

我在csv文件類似這樣的文本行工作只有時間:轉換在python

2012-03-16  13:47:31.915 -0400  image 

我希望能夠通過CSV文件來運行一個for循環,並減去剛時間在每行代碼之間。目前,我只能通過日期和時間來完成,但這會造成一些混亂。這是我現在擁有的。

newLogFile = csv.reader(open('newLogFile.csv', 'r+'), delimiter="\t") 
    row_count = sum(1 for row in csv.reader(open('newLogFile.csv'))) 
    fmt = '%Y-%m-%d %H:%M:%S.%f' 


    for row in newLogFile: 
     time = (row[0] + " " + row[1]) 


     ts1 = datetime.datetime.strptime(time, fmt) 

     row_count+=1 
     if row_count == 33: 
     current = ts1 
     current = ts1 - current 

     print ("%s - %s" %(ts1,current)) 
     current = ts1 - current 
     print current 

輸出看起來是這樣的:

2012-03-16 13:52:09.462000 - 0:01:44.866000 
    2012-03-16 13:50:24.596000 

我試圖尋找通過datetime和時間模塊,但我找不到任何會工作。我知道減法中也有錯誤,但我想首先得到正確的轉換。

感謝您的幫助

UPDATE:

我想通了,我的問題......

newLogFile = csv.reader(open('newLogFile.csv', 'r+'), delimiter="\t") 

fmt = '%Y-%m-%d %H:%M:%S.%f' 
row_count = 0 

for row in newLogFile: 
    time = (row[0] + " " + row[1]) 
    timestamp = strptime(time, fmt) 
    current_value = mktime(timestamp) 

    row_count+=1 
    if row_count == 1: 
     previous_value = current_value 

    print ("%s - %s" %(current_value, previous_value)) 
    total_value = current_value - previous_value 
    print total_value 

    previous_value = current_value 

我決定將時間設置爲秒,找出更準確和可靠的價值。我也修正了我的減法,通過改變row_count並將previous_value重置爲current_value,然後結束for循環

+1

您確定這是輸出嗎? 'current = ts1; current = ts1 - current'當然不能將'current'設置爲'timedelta(0)'以外的任何值。 – geoffspear 2012-03-19 18:03:46

+0

我剛剛重新運行它,這就是我得到的。 2012-03-16 13:52:24.563000 - 2012-03-16 13:50:33.944000 0:01:50.619000。 – user1186173 2012-03-19 18:09:28

+0

如果你這麼說。我看不出您發佈的代碼可能會產生該輸出,但祝您好運。 – geoffspear 2012-03-19 18:16:34

回答

0

我想通了我的問題,請參閱原始問題下的更新。

newLogFile = csv.reader(open('newLogFile.csv', 'r+'), delimiter="\t") 

fmt = '%Y-%m-%d %H:%M:%S.%f' 
row_count = 0 

for row in newLogFile: 
    time = (row[0] + " " + row[1]) 
    timestamp = strptime(time, fmt) 
    current_value = mktime(timestamp) 

    row_count+=1 
    if row_count == 1: 
     previous_value = current_value 

    print ("%s - %s" %(current_value, previous_value)) 
    total_value = current_value - previous_value 
    print total_value 

    previous_value = current_value