我在pandas数据框中有一个列,从0到172800000,步长为10.我想转换为具有指定日期的日期时间戳,从当天的午夜开始。
所以,假设,
time = np.arange(0,172800000, 10)
我想按以下格式转换:
YYYY-MM-DD: HH:MM:SS.XXX
开始日期应 2016-09-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年,09年,20年而不是1970年开始使用年,月和日?
答案 0 :(得分:3)
这是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=20
代替periods=172800000
)
答案 1 :(得分:2)
尝试:
test['TIME'] = pd.to_datetime('2016-09-20') + pd.to_timedelta(time, 'ms')