You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python Pandas识别DataFrame中的Epoch时间列并转换为可读日期

解决方案

原有代码问题

  • 取列名属性错误:应为df.columns而非df.column
  • 列引用方式错误:变量作为列名时必须用df[col],不能用df.col的点语法
  • 类型匹配逻辑错误:Epoch时间列是数值类型,无法用字符串匹配方法str.match判断
  • 转换逻辑错误:误将列名当做时间值做除法计算,没有处理列内的实际数据

完整实现代码

import pandas as pd

# 原始DataFrame构造代码
data = [['true', 'false',-1496188800000], ['false','true', 829008000000], ['true', 'false',],['true','true',1028678400000]]
df = pd.DataFrame(data, columns=['isconnect', 'isactive','datetime'])

# 核心处理逻辑
for col in df.columns:
    # 过滤非数值列,Epoch时间列必然是数值类型
    if not pd.api.types.is_numeric_dtype(df[col]):
        continue
    # 取非空值判断是否符合毫秒级Epoch特征:绝对值在1e11~1e13区间,覆盖1970前后50年的时间范围
    non_null = df[col].dropna()
    if len(non_null) == 0:
        continue
    # 匹配度阈值可按需调整,此处设置90%以上值符合特征即判定为时间列
    if (non_null.abs().between(1e11, 1e13)).mean() < 0.9:
        continue
    # 批量转换时间格式,转换失败的值设为None
    df[col] = pd.to_datetime(df[col], unit='ms', errors='coerce').dt.strftime('%Y-%m-%d').replace({'NaT': None})

# 输出结果
print(df)

如果你存储的是秒级Epoch时间,只需调整两个参数即可:

  1. 范围判断改为non_null.abs().between(1e9, 1e10)
  2. pd.to_datetime的unit参数改为's'

输出结果

isconnect isactive    datetime
0      true    false  1922-08-04
1     false     true  1996-04-09
2      true    false        None
3      true     true  2002-08-07

内容的提问来源于stack exchange,提问作者Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 16:54:03