python pandas read_csv 如何解析微秒

3 投票
1 回答
2939 浏览
提问于 2025-04-17 20:51

我有一个包含微秒时间的csv文件。

Time,Bid

2014-03-03 23:30:30:224323224323,0.8925

2014-03-03 23:30:30:224390224390,0.892525

2014-03-03 23:30:30:224408224408,0.892525

2014-03-03 23:30:30:364299364299,0.892525

我该如何用read_csv()或者其他函数把微秒解析成时间索引呢?也许可以用read_json?

谢谢!

1 个回答

4

接着@Jeff的评论,你可以这样做:

In [29]:
import pandas as pd
# specifically set the Time column to object dtype
df = pd.read_csv(r'c:\data\temp1.txt', dtype={'Time':object})
df

Out[29]:

                               Time       Bid
0  2014-03-03 23:30:30:224323224323  0.892500
1  2014-03-03 23:30:30:224390224390  0.892525
2  2014-03-03 23:30:30:224408224408  0.892525
3  2014-03-03 23:30:30:364299364299  0.892525

[4 rows x 2 columns]

In [32]:
# trim the erroneous data
df.Time=df.Time.apply(lambda x: x[:-6])
# now apply to_datetime and pass the format string
df.Time = pd.to_datetime(df.Time, format='%Y-%m-%d %H:%M:%S:%f')
df.dtypes

Out[32]:

Time    datetime64[ns]
Bid            float64
dtype: object

撰写回答