如何将对象类型转换为python jupyter中的datetime64 [ns]?
我有对象类型的这样的柱:如何将对象类型转换为python jupyter中的datetime64 [ns]?
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
回答:
你需要date
太如果需要datetime
S:
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
以上是 如何将对象类型转换为python jupyter中的datetime64 [ns]? 的全部内容, 来源链接: utcz.com/qa/262114.html