Skip to main content
 首页 » 编程设计

Python,将 datetime64 系列转换为日期和分钟

2024年11月01日8over140

我有一系列 datetime64[ns] 对象。

我想提取日期和分钟 (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)) 

请您参考如下方法:

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(...)