Python datetime类型转换为线性回归可输入格式时出现报错如何解决
Python datetime类型转线性回归可接受数值的正确转换方法
报错原因说明
AttributeError: 'datetime.datetime' object has no attribute 'astype':astype是Pandas对象专属方法,原生Python datetime对象无该属性,属于混淆了原生datetime和Pandas Timestamp类型导致的错误ValueError: unconverted data remains:str(now)会输出包含时分秒、微秒的完整时间字符串,你用%Y-%m-%d格式只能匹配日期部分,剩余的时间字符无法解析- 不需要绕
strptime做转换:原生datetime对象本身就支持直接转序数、时间戳等数值类型,无需转字符串再解析,绕路反而容易出错
正确转换方案
方案1:按日期粒度转整数序数
适合只需要日期维度特征的场景,输出为从公元1年1月1日开始计数的连续整数:
import datetime now = datetime.datetime.now() x = now.date().toordinal()
方案2:按完整时间粒度转时间戳
适合需要保留小时、分钟等时间维度信息的场景,输出为从1970-01-01 00:00:00 UTC开始的秒级浮点数值:
x = now.timestamp()
方案3:转相对于指定基准时间的天数差
适合时间跨度较小、需要特征数值更集中的场景,输出为带小数的天数,特征数值范围更小,更适合线性回归训练:
# 自定义基准时间,可根据你的数据集时间范围调整 base_time = datetime.datetime(2023, 1, 1) # 计算时间差转小数天 x = (now - base_time).total_seconds() / (3600 * 24)
Pandas datetime列批量转换
如果你的数据源是Pandas的Datetime列,批量转换写法:
import pandas as pd # 转序数 df['date_ordinal'] = df['datetime_col'].dt.toordinal() # 转时间戳 df['date_timestamp'] = df['datetime_col'].astype('int64') // 10**9
可选优化
如果时间跨度较大,建议对转换后的数值做标准化/归一化处理,可提升线性回归的训练效果。
内容的提问来源于stack exchange,提问作者DavisGrininger
相关产品推荐
相关产品推荐

