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

如何在Pandas中正确合并日期与时间序列列?

解决Timestamp与datetime.time列合并的问题

直接对Timestamp类型的Date列和datetime.time类型的Time列执行+运算会报错,因为这两种类型不支持直接相加。以下是两种可行的合并方法:

方法1:利用Timestamp.combine()逐行合并

通过apply逐行处理,将Date列的日期部分(datetime.date)与Time列的时间部分组合成完整的datetime对象,再转为Timestamp:

import pandas as pd
from datetime import datetime

df['dt'] = df.apply(lambda row: pd.Timestamp.combine(row['Date'].date(), row['Time']), axis=1)

方法2:将Time转为Timedelta后与Date相加

把datetime.time类型转为字符串,再通过pd.to_timedelta转为时间差类型,直接与Timestamp类型的Date列相加:

df['dt'] = df['Date'] + pd.to_timedelta(df['Time'].astype(str))

两种方法都能得到合并后的Timestamp类型列,可根据个人习惯选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 21:25:51