python - 如何将熊猫系列整数时间戳转换为日期时间(使用 fromtimestamp)?错误 = 无法将系列转换为
问题描述
我有一个带有整数形式时间戳的数据框。我想将其转换为日期时间,因此我可以使用 mplfinance.plot() 绘制数据(如果我尝试使用时间戳进行绘制,则会出现以下错误):
Expect data.index as DatetimeIndex
以下是显示问题的示例:
import datetime as dt
data = {'timestamp': [1364774700, 1364775000,1364775900]}
df = pd.DataFrame (data, columns = ['timestamp'])
df['datetime'] = dt.datetime.fromtimestamp(df['timestamp'])
但这会产生错误:
TypeError: cannot convert the series to <class 'int'>
在单个时间戳值上使用 fromtimestamp 可以正常工作。
解决方案
这些整数时间戳是自纪元以来的 POSIX 秒;使用pandas.to_datetime
withunti=second
指定转换df['timestamp']
为DatetimeIndex
:
import pandas as pd
df = pd.DataFrame({'timestamp': [1364774700, 1364775000, 1364775900]})
df = df.set_index(pd.to_datetime(df['timestamp'], unit='s'))
# timestamp
# timestamp
# 2013-04-01 00:05:00 1364774700
# 2013-04-01 00:10:00 1364775000
# 2013-04-01 00:25:00 1364775900