如何在pandas中通过start_time加execution_time计算end_time
实现方案
直接用Pandas内置的日期时间运算就能满足所有进位要求,不用手动处理时分天的进位逻辑,完整实现代码如下:
import pandas as pd # 示例数据构造,实际使用时替换为你自己的DataFrame即可 df = pd.DataFrame({ 'start_time': ['13-05-2013 04:04', '13-05-2013 04:44', '13-05-2013 23:24', '22-05-2013 16:31', '22-05-2013 20:55'], 'execution_time': ['00:24:48', '00:09:23', '00:06:51', '00:06:05', '00:06:51'] }) # 1. 转换start_time为日期时间类型,指定格式适配输入的日-月-年结构 df['start_time'] = pd.to_datetime(df['start_time'], format='%d-%m-%Y %H:%M') # 2. 转换execution_time为时间差类型 df['execution_time'] = pd.to_timedelta(df['execution_time']) # 3. 直接相加得到end_time,自动处理所有进位规则 df['end_time'] = df['start_time'] + df['execution_time'] # 若需要输出为和示例一致的字符串格式,可添加以下代码 df['end_time'] = df['end_time'].dt.strftime('%d-%m-%Y %H:%M:%S') print(df)
运行后输出结果和你给出的示例完全一致,跨天场景也会自动处理:比如start_time为13-05-2013 23:30、execution_time为01:40:00时,运算结果会自动变成14-05-2013 01:10:00。
内容的提问来源于stack exchange,提问作者nivedan gowda
相关产品推荐
相关产品推荐

