python - 使用熊猫解析时间到时间戳
问题描述
最近我收到了一些带有 epoch timeparse 的数据。使用 pandas 对其进行时间戳后,我注意到返回的年份是 1970 年,但数据来自 2018 年左右的电子游戏统计数据。
我试过了
df['date'] = pd.to_datetime(df.creationTime, inferdatetime_format=True)
df['date'].describe()
count 51490
unique 51052
top 1970-01-01 00:25:04.380431622
freq 3
first 1970-01-01 00:24:56.891694922
last 1970-01-01 00:25:04.707332198
Name: date, dtype: object
提供者说时间单位是秒,但是,例如
1504279457970
pd.to_datetime(1504279457970, infer_datetime_format=True)
Timestamp('1970-01-01 00:25:04.279457970')
和
pd.to_datetime(1504279457970, unit = 's')
...
OutOfBoundsDatetime: cannot convert input with unit 's'
Em'i 做错了什么?
我是 Python 新手,所以我不知道我是否天真。
谢谢!
解决方案
时间戳很可能是以毫秒精度提供给您的。如您所示,尝试使用秒精度将时间戳转换为日期时间会导致OutOfBoundsDatetime
错误。如果您假设时间戳的精度为毫秒,那么您得到的日期更可能是 2017 年。
inferdatetime_format=True
当您为方法提供参数时,pandas 似乎在猜测您使用的是纳秒级精确时间戳。
>>> pd.to_datetime(1504279457970, unit = 's')
Traceback (most recent call last):
...
pandas._libs.tslibs.np_datetime.OutOfBoundsDatetime: cannot convert input with unit 's'
>>> pd.to_datetime(1504279457970, unit = 'ms')
Timestamp('2017-09-01 15:24:17.970000')
>>> pd.to_datetime(1504279457970, unit = 'ns')
Timestamp('1970-01-01 00:25:04.279457970')
推荐阅读
- c# - 为什么这个循环只有在我不调试的时候才会无限循环?
- c# - 项目命令不能编辑列表中的另一个项目
- c# - 导出到 Excel 仅在 Web 应用程序中在 SaveAs 处引发错误
- python - 在 python 中的三元语句中引发错误,而不使用经典的 if/else 语法
- azure - 我可以使用 ADConnect 将用户迁移到 Azure B2C
- laravel - 流明:[ErrorException] chdir():没有这样的文件或目录(errno 2)
- android - Playstore 安装应用程序崩溃,但直接 android studio 安装运行良好
- r - 如何使用函数 sim.msm 重复函数并将值存储在 R 中
- c# - ASP.NET Core 2:在这种情况下,“多对一”关系背后的代码是什么?
- angular - 使用 ng2-pdf-viewer 或更优化的方式从 PDF 中读取文本?