在Pandas中将范围转换为时间戳

3

我在pandas数据框中有一列,范围从0到172800000,步长为10。我希望将其转换为指定日期的时间戳,从那一天的午夜开始计算。

例如,假设:

time = np.arange(0,172800000, 10)

我希望将它转换为以下格式:
YYYY-MM-DD: HH:MM:SS.XXX

起始日期应该是2016年9月20日

这是我所做的:

# Create a dummy frame as an example: 
test = pd.DataFrame()
time = np.arange(0, 172800000, 10)
test['TIME'] = time
data = np.random.randint(0, 1000, size=len(time))
test['DATA'] = data

# Convert time to datetime:
test['TIME'] = pd.to_datetime(test['TIME'], unit='ms') 

如果我检查数据框的头部,我会得到以下结果:
             TIME           DATA
0   1970-01-01 00:00:00.000 681
1   1970-01-01 00:00:00.010 986
2   1970-01-01 00:00:00.020 957
3   1970-01-01 00:00:00.030 422
4   1970-01-01 00:00:00.040 319

如何使年、月和日从2016年9月20日开始,而不是1970年开始?

2个回答

4
这就是 pandas.date_range() 的存在意义所在:
import pandas as pd

test = pd.DataFrame({'TIME': pd.date_range(start='2016-09-20',
                                           freq='10ms', periods=20)})
print(test)

输出:

                      TIME
0  2016-09-20 00:00:00.000
1  2016-09-20 00:00:00.010
2  2016-09-20 00:00:00.020
3  2016-09-20 00:00:00.030
4  2016-09-20 00:00:00.040
5  2016-09-20 00:00:00.050
6  2016-09-20 00:00:00.060
7  2016-09-20 00:00:00.070
8  2016-09-20 00:00:00.080
9  2016-09-20 00:00:00.090
10 2016-09-20 00:00:00.100
11 2016-09-20 00:00:00.110
12 2016-09-20 00:00:00.120
13 2016-09-20 00:00:00.130
14 2016-09-20 00:00:00.140
15 2016-09-20 00:00:00.150
16 2016-09-20 00:00:00.160
17 2016-09-20 00:00:00.170
18 2016-09-20 00:00:00.180
19 2016-09-20 00:00:00.190

(将periods=172800000替换为periods=20)


我也喜欢这个。 - piRSquared

3

尝试:

test['TIME'] = pd.to_datetime('2016-09-20') + pd.to_timedelta(time, 'ms')

谢谢。我喜欢这个,因为它真的很简洁!实际上,我有10天的毫秒级数据。因此,创建一个数据框,然后添加我的原始数据框可能会占用太多内存并减慢进程速度。 - Rohit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接