2013-07-24 35 views
2

我有一系列datetime64 [ns]對象。Python,將datetime64的系列轉換爲日期和分鐘

我想提取日期和分鐘(HH:MM)部分。到目前爲止,我使用下面的代碼,但它很慢。我怎麼能更有效地做到這一點?

>>> type(df['EXECUTION_TIMESTAMP']) 
Out[1]: pandas.core.series.Series 


>>> df['EXECUTION_TIMESTAMP'] 
Out[1]: 
0 2012-12-13 16:46:37 
1 2012-12-13 16:46:42 
2 2012-12-13 16:46:47 

... 

68 2010-09-07 15:21:38 
69 2013-07-21 21:40:14 
70 2010-07-21 22:44:46 
Name: EXECUTION_TIMESTAMP, Length: 769552, dtype: datetime64[ns] 


# Get the DateTimes Only 
ets = pd.Series(df['EXECUTION_TIMESTAMP']) 

print('Converting times') 
dt_min = [] 
dd  = [] 
for x in ets: 
    dt_min.append(pd.datetime(2000,1,1,x.hour,x.minute)) 
    dd.append(pd.datetime(x.year,x.month,x.day)) 

回答

2
In [1]: df = DataFrame(dict(time = Series([Timestamp('20121213 16:46:37'),Timestamp('20121213 16:46:42'),Timestamp('20121213 16:46:47'),Timestamp('20100907 16:21:38')]))) 

In [2]: df 
Out[2]: 
       time 
0 2012-12-13 16:46:37 
1 2012-12-13 16:46:42 
2 2012-12-13 16:46:47 
3 2010-09-07 16:21:38 

In [3]: df.dtypes 
Out[3]: 
time datetime64[ns] 
dtype: object 

In [4]: index = pd.DatetimeIndex(df['time']) 

In [5]: index 
Out[5]: 
<class 'pandas.tseries.index.DatetimeIndex'> 
[2012-12-13 16:46:37, ..., 2010-09-07 16:21:38] 
Length: 4, Freq: None, Timezone: None 

In [6]: zip(index.minute,index.second) 
Out[6]: [(46, 37), (46, 42), (46, 47), (21, 38)] 

顯示不是作爲元組的列表,但與小時日期,分提取

In [10]: Series([ datetime.datetime(2000,1,1,t.hour,t.minute) for t in pd.DatetimeIndex(df['time']).time ]) 
Out[10]: 
0 2000-01-01 16:46:00 
1 2000-01-01 16:46:00 
2 2000-01-01 16:46:00 
3 2000-01-01 16:21:00 
dtype: datetime64[ns] 

我猜你最終想要組通過這一點;只是直接做

df.set_index('time').groupby(lambda x: x.hour,lambda x: x.minute).apply(...) 
+0

感謝您的幫助。最後的zip命令給了我一分鐘和二秒的元組列表。有沒有辦法讓它返回日期時間的數據框呢? – Ginger

+0

不確定你的最終目標是什麼......但讓我知道是否有幫助 – Jeff