如何在 python jupyter 中将对象类型转换为 datetime64[ns]?

how to convert object type to datetime64[ns] in python jupyter?

我有一列对象类型如下:

 quote['SellTime'].head()


 Out[32]:
  0    94520
  1    94538
  2    94609
  3    94615    
  4    94617
  Name: SellTime, dtype: object

我想将其转换为日期时间 (datetime64[ns]) 格式。

我做了以下代码:

 quote['SellTime'].astype(str).astype(int)
 t2 = quote['SellTime'].astype(str).str.zfill(6)
 quote['SellTime'] = pd.to_datetime(t2, format='%H%M%S').dt.time

但它仍然是对象类型:

 quote['SellTime'].head()

 0    09:45:20
 1    09:45:38
 2    09:46:09
 3    09:46:15
 4    09:46:17
 Name: SellTime, dtype: object

你也需要 dates 如果需要 datetimes:

quote['SellTime'] = pd.to_datetime(t2, format='%H%M%S')
print (quote)
             SellTime
0 1900-01-01 09:45:20
1 1900-01-01 09:45:38
2 1900-01-01 09:46:09
3 1900-01-01 09:46:15
4 1900-01-01 09:46:17

或者更好的方法是将时间转换为 timedeltas:

quote['SellTime']=pd.to_timedelta(pd.to_datetime(t2,format='%H%M%S').dt.strftime('%H:%M:%S'))
print (quote['SellTime'])
0   09:45:20
1   09:45:38
2   09:46:09
3   09:46:15
4   09:46:17
Name: SellTime, dtype: timedelta64[ns]

因为如果将日期时间转换为 times:

quote['SellTime'] = pd.to_datetime(t2, format='%H%M%S').dt.time

print (quote['SellTime'].dtype)
object

print (quote['SellTime'])
0    09:45:20
1    09:45:38
2    09:46:09
3    09:46:15
4    09:46:17
Name: SellTime, dtype: object

print (quote['SellTime'].apply(type))
0    <class 'datetime.time'>
1    <class 'datetime.time'>
2    <class 'datetime.time'>
3    <class 'datetime.time'>
4    <class 'datetime.time'>
Name: SellTime, dtype: object