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

如何在Python中将float类型列转换为datetime64类型?

解决float类型日期列转datetime64的问题

针对float类型列转datetime64失败的情况,分以下几种场景处理:

场景1:float列是年份数值(如2020.0、2021.5)

如果你的数据是年份(含小数可能代表季度/月份比例),按需求处理后转换:

  • 若仅需整数年份,先转整数再转datetime:
    newdf["Year_Sold"] = pd.to_datetime(df["Year_Sold"].astype(int), format="%Y")
    
  • 若保留带小数的年份(如2020.25代表2020年第一季度),直接转换并处理异常值:
    newdf["Year_Sold"] = pd.to_datetime(df["Year_Sold"], errors="coerce", format="%Y")
    

场景2:float列是Excel日期序列号(如44197对应2021-01-01)

Excel的日期以浮点数存储(1对应1900-01-01,存在闰年bug),转换时需指定起始原点:

newdf["Year_Sold"] = pd.to_datetime(df["Year_Sold"], unit="D", origin="1899-12-30")

场景3:列中存在NaN或无效浮点值

先将浮点值转为字符串并清理,再强制转换无效值为NaT:

newdf["Year_Sold"] = pd.to_datetime(df["Year_Sold"].astype(str).str.strip(), errors="coerce")

内容的提问来源于stack exchange,提问作者Richard Oppong Kwarteng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 22:52:19