我有一个包含 2 列的数据框 - 一些值和时间。时间戳采用纪元时间格式,我正在尝试使用 python 中时间库中的 strftime 函数进行转换。
这是一些示例数据
df = [{'A': 762, 'Time': 1512255906},
{'A': 810, 'Time': 1480719906}]
注意:时间采用纪元格式。我正在执行一些转换,以确保它的类型为 numeric(float),然后再通过 strftime 函数进行日期转换。
代码如下:
df['Time'] = pd.to_numeric(df['Time'], errors='coerce').fillna(0)
df['Time'].dtype
我在这条线上时收到错误
df['Time'] = time.strftime("%d-%m", time.localtime(df['Time']))
回溯:
TypeError Traceback (most recent call last)
<ipython-input-53-86f4db0b80e4> in <module>()
----> 1 df['Time'] = time.strftime("%d-%m", time.localtime(df['Time']))
TypeError: cannot convert the series to <class 'int'>
最佳答案
您可以使用pandas.DataFrame.apply
:
>>> import pandas as pd
>>> import time
>>> df = pd.DataFrame([{'A': 762, 'Time': 1512255906},
{'A': 810, 'Time': 1480719906}])
>>> df['Time'] = pd.to_numeric(df['Time'], errors='coerce').fillna(0)
>>> df['Time'] = df['Time'].apply(lambda t: time.strftime("%d-%m", time.localtime(t)))
>>> df
A Time
0 762 03-12
1 810 03-12
关于python - 将纪元转换为日期时间格式 python - typeerror,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47613582/