python - 如何以毫秒为单位将 unix 时间戳转换为日期时间 python 3
问题描述
我有一个带有 unix(纪元)时间的大型数据集,我需要以毫秒为单位将其转换为日期时间。我的代码应该完成这项工作,因为我指定返回毫秒,但不知何故它只返回几秒钟。需要改变什么?
import pandas as pd
# reading in the excel file timestamps.xlsx
# this file contains a column 'epoch' with the unix epoch timestamps
df = pd.read_excel('epoch_time.xlsx')
# translate epochs into human readable and write into newly created column
# timestamps are in ms, hence the unit
df['time'] = pd.to_datetime(df['epoch'], unit='ms')
# remove epoch row
df = df.drop('epoch', axis=1)
# write to excel file 'new_timestamps.xlsx'
# index=False prevents pandas to add the indices as a new column
df.to_excel('new_timestamps.xlsx', index=False)
解决方案
我想这就是你要找的东西:
pd.to_datetime(1582200012345, unit='ms').to_datetime64()
输出:
numpy.datetime64('2020-02-20T12:00:12.345000000')
或用于列:
df['time'] = pd.to_datetime(df['time'], unit='ms').apply(lambda x: x.to_datetime64())
例子:
df=pd.DataFrame([1582200012345,1582200012346])
df['time'] = pd.to_datetime(df[0], unit='ms').apply(lambda x: x.to_datetime64())
df
0 time
0 1582200012345 2020-02-20 12:00:12.345
1 1582200012345 2020-02-20 12:00:12.346
推荐阅读
- python - 合并具有重复键的数据框
- gremlin - Gremlin-python:如何使用用户定义的步骤来重用遍历逻辑
- asp.net - 需要迁移到较旧的 Crystal 报表版本才能使用报表
- javascript - 我想从 react.js 中的按钮单击上的选择选项中获取选定的值
- javascript - 如何立即获得上个月第 15 天和当前月第 16 天
- ios - CocoaPods 在快照 (Podfile.lock) 中找不到 pod FirebaseCore 的兼容版本:
- python - python Pill在图像上应用功能并保存它们仅适用于第一张图像
- reactjs - 如何在 DigitalOcean 液滴上运行 docker 映像?
- bash - 在 bash 中等待本地主机
- javascript - 使用 reactjs 渲染 JSON 数据(来自 reddit API)