将时间序列的时间精度减少到毫秒

1 投票
2 回答
2664 浏览
提问于 2025-04-17 18:22

在解析数据文件时,我遇到了这样的时间格式:

1.296999421

目前在pandas中显示成这样:

<Timestamp: 2011-04-16 00:00:01.296999>

它的类型是'datetime64[ns]',但我知道原始测量只有毫秒的精度。

有没有办法生成一个只使用毫秒精度的pandas时间序列?我的一个目标是根据毫秒计数精确地连接不同的时间序列。

所以我希望只保留

<Timestamp: 2011-04-16 00:00:01.297>

这样我就可以在其他时间序列中精确匹配这个时间戳。

换句话说,是否有'datetime[ms]'这种类型,我该如何将不连续的时间戳转换成它?

2 个回答

1

我不知道你是怎么把 1.296999421 转换成 <Timestamp: 2011-04-16 00:00:01.296999> 的。我觉得你可以通过以下步骤创建一个 datetime64[ms] 的数组:

a = np.random.rand(100)*10
a.sort()
t = np.array(np.round(a*1000), dtype="timedelta64[ms]") + np.datetime64("2012-03-01")

然后你可以把 t 当作你的数据表的索引。Pandas 会把这个转换成 timedelta64[ns]

2

HYRY的解决方案是对的,但pandas不知道该怎么处理它。

使用最新的pandas 0.11-dev版本,现在对时间差(timedeltas)有了全面的支持。

http://pandas.pydata.org/pandas-docs/dev/timeseries.html#time-deltas

In [25]: a = np.random.rand(8)*10

In [26]: a.sort()

In [27]: a
Out[27]: 
array([ 0.72062151,  1.02039858,  2.07877837,  3.94256869,  5.5139672 ,
    6.80194715,  6.83050498,  8.63027672])

# trick is to pass a nanosecond value directly
# pandas keeps all values internally as timedelta64[ns]
In [5]: pd.Series((np.round(a*1000)/1000)*1e9,dtype='timedelta64[ns]')
Out[5]: 
0   00:00:00.721000
1   00:00:01.020000
2   00:00:02.079000
3   00:00:03.943000
4   00:00:05.514000
5   00:00:06.802000
6   00:00:06.831000
7   00:00:08.630000
dtype: timedelta64[ns]

如果你需要把这个转换成时间戳(Timestamp),

In [8]: pd.Series((np.round(a*1000)/1000)*1e9,dtype='timedelta64[ns]') + pd.Timestamp('20110406')
Out[8]: 
0   2011-04-06 00:00:00.721000
1   2011-04-06 00:00:01.020000
2   2011-04-06 00:00:02.079000
3   2011-04-06 00:00:03.943000
4   2011-04-06 00:00:05.514000
5   2011-04-06 00:00:06.802000
6   2011-04-06 00:00:06.831000
7   2011-04-06 00:00:08.630000
dtype: datetime64[ns]

撰写回答