python - 具有亚秒级(例如毫秒)分辨率的 to_datetime

标签 python numpy pandas

我有一个系列将时间戳保存为字符串,如下所示:

404     02:59:34,787
626     10:04:09,622
668     11:10:52,190
796     14:40:32,032
1022    17:20:58,314
1035    17:47:55,895
1071    18:50:12,628
1075    19:20:19,642
8902    23:50:54,408
Name: my_time, Length: 9, dtype: object

据我所知,我可以在技术上使用 pd.to_datetime 将其转换为一系列 datetime 对象。然而,看着strftime我没有看到任何支持亚秒分辨率(在我的例子中是 ms)的格式规范。

我错过了什么吗?将此 Series 字符串转换为 Series datetime 对象的最佳方法是什么

最佳答案

这是一个完全矢量化的解决方案。首发系列

In [32]: x
Out[32]: 
404     02:59:34,787
626     10:04:09,622
668     11:10:52,190
796     14:40:32,032
1022    17:20:58,314
1035    17:47:55,895
1071    18:50:12,628
1075    19:20:19,642
8902    23:50:54,408
Name: value, dtype: object

将','替换为'.',转换为timedelta并添加日期

In [33]: pd.to_timedelta(x.str.replace(',','.')) + Timestamp('20130101')
Out[33]: 
404    2013-01-01 02:59:34.787000
626    2013-01-01 10:04:09.622000
668    2013-01-01 11:10:52.190000
796    2013-01-01 14:40:32.032000
1022   2013-01-01 17:20:58.314000
1035   2013-01-01 17:47:55.895000
1071   2013-01-01 18:50:12.628000
1075   2013-01-01 19:20:19.642000
8902   2013-01-01 23:50:54.408000
Name: value, dtype: datetime64[ns]

关于python - 具有亚秒级(例如毫秒)分辨率的 to_datetime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26024520/

相关文章:

python - 在 python 中使用 for 循环将 skimage.filters.threshold_otsu() 应用于图像/数组中的段列表时遇到问题

python - 如何获得两个 datetime.time Pandas 列之间的绝对差?

python - 将具有重复键的 Pandas DataFrame 转换为字典

python - 子包和 __init__.py

python - 检索 IP 地址作为 Django URL 中的参数

python - 在 Python 中从文件加载数组数据的最简单方法是什么?

Numpy Einsum 路径差异和优化参数

python - 如何将数据帧与数组时间戳合并并根据数组的条件进行绘图?

python - 如何删除列表中字符串中的所有空格

python - TensorFlow 未编译为使用 SSE(等)指令,但这些指令可用