2017-09-14 31 views
0

我有一個數據集,其中包含時間戳,其中一些數字在秒內有小數,但有些則沒有。我需要比較這些時間戳並對這些時間戳進行分類。我不知道如何爲這些記錄定義不同的格式。未轉換的數據僅保留一些記錄

因此,對於那些在秒小數,我可以這樣寫:

a = datetime.strptime(time, "%H:%M:%S.%f") 

併爲那些沒有,我寫:

a = datetime.strptime(time, "%H:%M:%S") 

我需要比較一個到另一個時間戳。

回答

1

使用string.split函數將字符串分隔成3個字段,並查看第三個字符串是否有「。」。你可能需要比我在這裏提供的更多的錯誤處理。

def has_seconds(a_string): 
    return "." in a_string.split(":")[2] 

if has_seconds(a_time): 
    a = datetime.strptime(a_time, "%H:%M:%S.%f") 
else: 
    a = datetime.strptime(a_time, "%H:%M:%S") 
0

我也設法刪除小數,所以他們現在都在一個相同的格式。