Pandas:将Timestamp和Milliseconds转换为DatetimeIndex

时间:2012-10-22 21:42:21

标签: csv pandas date-parsing

df = read_csv('data\query.csv')

我得到了:

    TIMESTAMP   MILLISECONDS    PRICE
0   15.10.2012 08:00:06     350     24.6
1   15.10.2012 08:00:06     630     24.7
2   15.10.2012 08:00:06     640     24.9
3   15.10.2012 08:00:06     650     24.5
4   15.10.2012 08:00:06     710     24.3

我发现这一个

df = read_csv('data\query.csv', parse_dates=[[0, 1]], index_col=0)

将前两列连接到一个字符串但仍然没有将索引识别为DatetimeIndex

另外这个

Import datetime
datetime.datetime.strptime("15.10.2012 15:30:00 890", "%d.%m.%Y %H:%M:%S %f")

正在进行转换工作。

问题:如何在read_csv上快速进行转换和DatetimeIndex?

3 个答案:

答案 0 :(得分:1)

In [188]: from dateutil import parser

In [189]: from StringIO import StringIO

In [190]: data = """\
TIMESTAMP;MILLISECONDS;PRICE
15.10.2012 08:00:06;350;24.6
"""

In [191]: def date_parser(s):
    return parser.parse(s[:-4]).replace(microsecond=int(s[-3:])*1000)
   .....:

In [192]: df = pd.read_csv(StringIO(data), sep=';', parse_dates=[[0, 1]], date_parser=date_parser)

In [193]: df
Out[193]:
       TIMESTAMP_MILLISECONDS  PRICE
0  2012-10-15 08:00:06.350000   24.6

In [194]: df.set_index('TIMESTAMP_MILLISECONDS', inplace=True)
Out[194]:
                            PRICE
TIMESTAMP_MILLISECONDS
2012-10-15 08:00:06.350000   24.6

In [195]: df.index
Out[195]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2012-10-15 08:00:06.350000]
Length: 1, Freq: None, Timezone: None

答案 1 :(得分:0)

答案 2 :(得分:0)

您是否尝试过.to_timestamp()

df_trend = pd.read_csv('googletrends.csv',parse_dates=True, index_col=0)
ts_iphone = df_trend.ix['2007':'2013','iphone'].to_timestamp()

您可以找到文档here