python - 将纪元转换为日期时间格式 python - typeerror

标签 python python-3.x pandas typeerror python-datetime

我有一个包含 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/

相关文章:

python - 如何在 tkinter Canvas 上交换两个对象的位置

python - 使用日期时间对象重命名 pandas 列

python - 如何删除具有多个扩展名的文件

python - gspread import_csv file_id 参数是什么?

python - 属性错误: 'function' object has no attribute 'name' when using Click to create Hierarchical command groups

python-3.x - 在 Google Sheet API V4 中使用 Python 将特定单元格格式化为日期

python - 有没有更简洁的方法来查找字典中最高的 5 个值?

python - 将 uuid 添加到 pandas DataFrame 中的新列

python - 将字典中的列表作为新列添加到 DataFrame

python - 为什么当我使用 .astype(str) 时 numpy/pandas 仅返回第一个字符