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

时间:2017-12-18 09:33:19

标签: python pandas datetime financial

我有一个像这样的对象类型列:

 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

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

我已完成以下代码:

 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

但它仍然是对象类型:

page.ts

1 个答案:

答案 0 :(得分:1)

如果需要date s:

,您也需要datetime
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

或者更好的是将时间转换为timedelta s:

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]

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

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