2016-07-14 36 views
0

考慮下面的代碼:指定的strftime格式,加快大熊貓to_datetime()方法

import pandas as pd 
some_time='01/01/2011 12:02:41 AM' 
print(pd.to_datetime(some_time)) 
print(pd.to_datetime(some_time, format='%m/%d/%Y %I:%M:%S %r')) 

第一to_datetime()改建工程,並打印輸出

2011-01-01 00:02:41 

不幸的是,在我的實際應用我正在處理一個有200多萬行的DataFrame,即使我在關鍵字參數中設置了infer_datetime_format=True,默認to_datetime()的速度也非常慢。

我讀過to_datetime()可以通過明確指定字符串格式來加速。我已經嘗試過以下http://www.tutorialspoint.com/python/time_strftime.htm,但我上面的嘗試失敗,錯誤ValueError: 'r' is a bad directive in format '%m/%d/%Y %I:%M:%S %r'

如何指定正確的strftime格式將'01/01/2011 12:02:41 AM'轉換爲datetime?

回答

2

我想你只需要%p而不是%r。區別在於%r需要標點(A.M.或P.M.),而%p不需要(AM或PM)。

pd.to_datetime(some_time, format='%m/%d/%Y %I:%M:%S %p') 
0

正確的答案被root在評論給出:當我做出改變

您的代碼不會產生任何錯誤。爲了完整起見,%r需要由%p取代:

some_time='01/01/2011 12:02:41 AM' 
print(pd.to_datetime(some_time)) 
print(pd.to_datetime(some_time, format='%m/%d/%Y %I:%M:%S %p')) 

這產生輸出

2011-01-01 00:02:41 
2011-01-01 00:02:41 

即,具有和不具有format關鍵字參數相同的輸出。