首页 > 解决方案 > 使用熊猫解析时间到时间戳

问题描述

最近我收到了一些带有 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 新手,所以我不知道我是否天真。

谢谢!

标签: pythonpython-3.xpandastimestamp

解决方案


时间戳很可能是以毫秒精度提供给您的。如您所示,尝试使用秒精度将时间戳转换为日期时间会导致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')

推荐阅读