python - 反向 Pandas to_datetime() 方法获取时间戳

标签 python pandas dataframe datetime python-datetime

我有一个 DataFrame,其中一列 sensorTime 表示以纳秒为单位的时间戳 (currentTimeMillis() * 1000000)。示例如下:

sensorTime
1597199687312000000
1597199687315434496
1597199687320437760
1597199687325465856
1597199687330448640
1597199687335456512
1597199687340429824
1597199687345459456
1597199687350439168
1597199687355445504

我正在使用

将此列转换为日期时间
res['sensorTime'] = pd.to_datetime(res['sensorTime'])

如何将日期时间转换回以纳秒为单位的时间戳,以便获得如上例所示的准确值?

最佳答案

最明显的方法是使用 astype 将日期时间系列转换为 Unix 时间(自纪元以来的纳秒):

import pandas as pd
res = pd.DataFrame({'sensorTime': [1597199687312000000, 1597199687315434496, 1597199687320437760]})
res['sensorTime'] = pd.to_datetime(res['sensorTime'])

# back to nanoseconds / Unix time - .astype to get a pandas.series
s = res['sensorTime'].astype('int64')

print(type(s), s)
<class 'pandas.core.series.Series'> 
0    1597199687312000000
1    1597199687315434496
2    1597199687320437760
Name: sensorTime, dtype: int64

另一个选择是使用 view :

# .view to get a numpy.ndarray 
arr = res['sensorTime'].values.view('int64')

print(type(arr), arr)
<class 'numpy.ndarray'> 
[1597199687312000000 1597199687315434496 1597199687320437760]

但要小心,它只是一个 View ,因此底层数据保持不变。这意味着,如果您更改数据帧系列中的值,此更改也将在 View 数组中可见。

关于python - 反向 Pandas to_datetime() 方法获取时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65908937/

相关文章:

python - 寻求比较和过滤 Pandas 日期范围重叠的有效方法

python - Pandas 替换在多列子集上无法按预期工作

python - 无法在 Google Colab 中安装自定义包

python - 使用字典交叉数据框列 "contains List"

python - Pandas 根据条件过滤行,但始终保留第一行

python - 在 Pandas 图中添加图例

arrays - 属性错误: 'numpy.ndarray' object has no attribute 'toList'

python - 我可以在机器人框架中编写独立的测试用例吗?

python - pandas 基于不完全匹配的时间戳进行合并

python - 设置索引,使用常见的列值作为数据框的索引